An Introduction to Cloudflare Workers

Share this article

An Introduction to Cloudflare Workers
Cloud computing in its various incarnations — SaaS, PaaS, IaaS — has had big successes. Some of us still recall the $212 million purchase of PaaS provider Heroku in 2010, which at that time was — architecturally speaking — little more than a high-level deployment layer. It had a very posh gem for smooth and easy deployment of apps and frameworks like RoR, Python or Node apps running on Amazon’s infrastructure. The concept of Serverless Computing was born.
There have been a host of different models for cloud products ever since then. Various experiments have come and gone as providers looks for the sweet spot, with proliferation continuing and new terms being born, like BaaS and MBaaS. Protocol Labs, a crypto startup looking to redefine the cloud model, collected $257 million in its 2017 ICO, breaking all records. Airtable, with its high-level, spreadsheet-meets-database products and api, reached a $1.1 billion valuation in its 2018 financing round.

Serverless Computing

Serverless computing is a subset term of cloud computing that makes a point of doing away with the classical server product, providing developers with a high-level environment to run their code, charged on an as-used basis, and freeing those developers from worrying about the underlying software stack. Serverless computing has allowed further flexibility in paying for used processing power, rather than paying for pre-allocated packages as with classical cloud. The term “serverless” is semantically wrong, because the code is still executed on a server, but users conceptually don’t have to deal with servers anymore. Provided certain conventions are adhered to, the underlying stack, and all the infrastructure and deployment issues, are handled by vendors. The main type of product that sprang out from this is FaaS — a cloud execution environment, or a runtime that allows deployment of code without any boilerplate. Amazon’s Lambda, Oracle Fn and Alibaba’s Function Compute are some examples.

Cloudflare

Cloudflare is a San Francisco company that was started nine years ago. It’s a Content Delivery Network that provides delivery of static assets for websites from its global network of edge nodes. It also provides firewall and DDOS protection, and has a reputation for the fastest DNS service
on the internet. When talking about Cloudflare, and what it brings to the arena of serverless computing, it’s necessary to add one more term to the list of cloud buzzwords we used here — edge computing. As explained on Wikipedia:
edge computing is a distributed computing paradigm in which computation is largely or completely performed on distributed device nodes. Edge computing pushes applications, data and computing power (services) away from centralized points to locations closer to the user.*

Cloudflare Workers

Screenshot of a Kenton Varda tweet Cloudflare Workers are a peculiar, and powerful, incarnation of FaaS (function as a service), with code being instantly deployed to Cloudflare’s global network of nodes, to be executed as close as possible to the visitor. As Kenton Varda has said on the Cloudflare blog:
When responding to a user in New Zealand, your code should run in New Zealand. When crunching data in your database, your code should run on the machines that store the data. When interacting with a third-party API, your code should run wherever that API is hosted. When human explorers reach Mars, they aren’t going to be happy waiting a half an hour for your app to respond. Your code needs to be running on Mars.
Cloudflare Workers are a code execution environment designed on V8, the JavaScript engine designed for Google Chrome and used also by Opera, Node.js, Brave browser, Electron, and others. Workers use the Service Worker API — but the code resides on Cloudflare, not in the browser. They can “modify your site’s HTTP requests and responses, make parallel requests, and even reply directly from the edge”. This means that, if we were up for it, our application could reside on the CDN. This also means that, while we run dynamic JavaScript code that’s not server-side code in the classical sense, and it has a much better latency both in comparison to server-side apps and to classical FaaS services, our code is still not running in the browser, which means it’s not open to the public. According to the words of its lead developer, Workers are the beginning of something that could develop into much more refined products in the future. In many cases, perceived speed and efficiency are as good as if the execution was happening in the visitor’s browser, but without the processing overhead. It all happens in the cloud. Comparable technology (which was available so far to users of NGINX) is Lua scripting — with the difference that Cloudflare executes workers’ code on its network of edge nodes, closest to the visitor. Cloudflare Workers can be tested, quick and dirty, on the Cloudflare Workers Playground.

Potential Uses

Cloudflare has uploaded a number of code examples to a GitHub repo. Among them is a Slack bot, which fetches prices or cryptocurrencies from CoinMarketCap and caches them on the Cloudflare infrastructure. The code is very simple, and is available here. It demonstrates the main advantage of Cloudflare Workers — the simplicity of doing away with dealing with the entire software stack underneath the application. Cloudflare Workers leave developers free to focus on the application logic. Then there’s the more advanced example — the edge caching solution for WordPress — which gives a polished solution for caching, and purging the HTML output of WordPress, by putting together Cloudflare Workers, Workers KV (key-value store), and a plugin for WordPress, which all work in concert to make it possible to bypass the cache in case some cookies are present, to make atomic cache purging possible, and so on. You can find out more about this example here. Then there are code examples of using custom logic to put a layer of protection between the origin website and the Internet. There is an example of using workers logic to rewrite 3rd-party scripts
included in the web page HTML, to origin URLs with content hash, and then extending their browser cache, and also caching it on Cloudflare edge nodes — so there’s no need for three round trips to third-party servers for each script. This can make a big performance difference in some cases, and the beauty of it is that workers use JavaScript — which means there’s a rich programmable interface for conjuring all the power of the Cloudflare infrastructure to do our bidding. There are other code examples in their repository.

How It’s Done

When we open the Cloudflare dashboard, there’s a Workers menu item among the icon-menu items on the top. The Workers menu option To start, we need to open the Workers dashboard link in the top, and we will need to set up a subdomain for our workers: setting up a subdomain for our workers Then we’ll be presented with the workers dashboard, where we’ll be able to deploy new workers, monitor thier usage, and so on. There’s also an editor, which we can use to edit the logic of the workers: The workers editor As we said, Workers use the JavaScript V8 engine, and — obviously — JavaScript syntax. The documentation is solid and detailed, and has a number of templates so we can jump-start our work.

Wait, There’s More!

For those of us who want the ability to put more logic into this layer, and want to squeeze more performance from this infrastructure, there’s more. In October 2018, Cloudflare announced support for WebAssembly for Workers — which means support for compiled languages like C, C++ and Rust. This makes Workers potentially very serious, if not game-changing contender in this space.

Conclusion

Serverless computing, with the conveniences it offers, is grabbing the attention of more and more developers. It gives them freedom to focus on application logic, and not to have to worry about the underlying libraries and software infrastructure. Those of us who’ve had to handle hundreds of megabytes of npm libraries, who encountered the mess with versions of different dependencies, who had to install and work with Ruby Version Manager, or PyEnv, virtualenv, and similar delicacies, know the pain, and know that resolving these issues can take 80% of one’s work. Serverless cloud offerings available today have found their market, and Cloudflare Workers are one of the most interesting products in this niche. I hope you’ve found this introduction useful!

Frequently Asked Questions (FAQs) about Cloudflare Workers

What are the key benefits of using Cloudflare Workers?

Cloudflare Workers provide several key benefits. Firstly, they allow you to run JavaScript in Cloudflare’s 200+ data centers around the world. This means your code is executed closer to the user, reducing latency and improving performance. Secondly, they offer a serverless environment, eliminating the need for server management and scaling concerns. Lastly, they provide a secure environment for your code, as they are isolated from other scripts and your user’s data.

How does Cloudflare Workers compare to traditional server setups?

Traditional server setups require you to manage and maintain your own servers, which can be time-consuming and costly. With Cloudflare Workers, you can write and deploy code without worrying about server management. Your code runs in a serverless environment, which automatically scales to meet your traffic needs. This can lead to significant cost savings and improved performance.

Can I use Cloudflare Workers for complex applications?

Yes, Cloudflare Workers are designed to handle complex applications. They support asynchronous JavaScript, which allows you to perform tasks like API calls and data processing without blocking the main thread. This makes them ideal for building complex, high-performance applications.

How secure are Cloudflare Workers?

Cloudflare Workers are designed with security in mind. Each worker runs in its own isolated environment, separate from other scripts and user data. This isolation prevents any potential security threats from affecting your code or your user’s data.

How do I get started with Cloudflare Workers?

Getting started with Cloudflare Workers is simple. You can write your code directly in the Cloudflare dashboard, or you can use the Wrangler CLI tool to write and deploy your code from your local development environment. Once your code is ready, you can deploy it to Cloudflare’s global network with a single command.

What is the pricing for Cloudflare Workers?

Cloudflare offers a free tier for Workers, which includes up to 100,000 requests per day. For more usage, they offer a $5/month plan that includes 10 million requests, with additional requests charged at $0.50 per million.

Can I use my own domain with Cloudflare Workers?

Yes, you can use your own domain with Cloudflare Workers. You simply need to configure your DNS settings to point to Cloudflare’s servers, and your Workers will be accessible at your chosen domain.

What languages are supported by Cloudflare Workers?

Cloudflare Workers primarily support JavaScript, but you can also use any language that compiles to WebAssembly, including Rust, C, and C++.

How do I debug my Cloudflare Workers?

Cloudflare provides several tools for debugging Workers. You can use the Workers dashboard to view real-time logs, or you can use the Wrangler CLI tool to simulate your Workers locally and debug them using standard JavaScript debugging tools.

Can I use Cloudflare Workers with other Cloudflare services?

Yes, Cloudflare Workers can be used in conjunction with other Cloudflare services, such as Cloudflare Pages for deploying static websites, or Cloudflare Stream for video streaming. This allows you to build powerful, integrated applications using Cloudflare’s suite of services.

Tonino JankovTonino Jankov
View Author

Tonino is a web developer and IT consultant who's dived through open-source code for over a decade. He's also a crypto enthusiast, Linux fan, and moderate libertarian.

baasCloudFlareFaaSIAASPaaSSaaSworkers
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week