Cloudflare Workers

SHARE

Cloudflare Workers let you run JavaScript in Cloudflare’s 120+ edge locations around the world. Using a Worker, you can modify your site’s HTTP requests and responses, make parallel requests, or generate responses from the edge. Cloudflare enters the game of FaaS providers as a strong competitor, even for players like Google Cloud Platform or AWS.

Use cases
  • Load balance between multiple origins to improve speed or reliability.
  • Render HTML templates while fetching dynamic content from your origin.
  • Dynamically respond to requests without needing to connect to an origin server at all.
  • Generate parallel requests to different services and combine the responses.
  • Create custom security rules and filters to block unwanted visitors and bots.
  • Perform data sanitisation and validation before sending a request to your origin.
  • Use custom logic to decide which requests are cacheable and improve cache hit rate.
  • Deploy fast fixes to your site in seconds without having to update your origin server.

All of these actions happen inside Cloudflare’s lightning-fast edge. Your code will be deployed to hundreds of data centres around the world returning responses to your users faster than your origin ever could. You get all the speed and security of the world’s most peered CDN with all the power of JavaScript.

But yeah… it’s still JavaScript.

Cloudflare Workers are modeled on the Service Workers available in modern web browsers, and use the same API whenever possible. Unlike standard Service Workers, Cloudflare Workers run on Cloudflare’s servers, not in the user’s browser.

While Cloudflare does use V8, they do not use Node.js. The JavaScript APIs available to you inside workers are implemented directly. Working with V8 directly allows to run code more efficiently and securely.

Cloudflare1Cloudflare workers’ edge locations

Example

Example of returning a blocked response based on country (with the response itself in the Worker!):

if (request.cf.country == "UK") {
 return new Response("<html>No cats for you!</html>", {
   headers: { "Content-Type": "text/html" },
   status: 403,
   statusText: "Forbidden"
 });
}

Example of blocking an IP address to requests to your origin servers:


addEventListener('fetch', event => {
 event.respondWith(fetchAndApply(event.request))
})

async function fetchAndApply(request) {  
 if (request.headers.get('cf-connecting-ip') === '225.0.0.1') {
   return new Response('Sorry, this page is not available.',
       { status: 403, statusText: 'Forbidden' })
 }

 return fetch(request)
}

Push this to the worker and you have this code deployed globally with a minimum response time from anywhere!

Serverless

Serverless is a paradigm for building applications without concern for the underlying infrastructure. It lets developers focus on writing code and lets them deploy quickly and cheaply to a cloud provider which manages servers, networking, and configuration.

The Serverless Framework helps you develop and deploy serverless applications using Cloudflare Workers. It’s a CLI that offers structure, automation, and best practices out-of-the-box, allowing you to focus on building sophisticated, event-driven, serverless architectures, comprised of Functions and Events.

The Serverless Framework manages your code as well as your infrastructure. It lets you manage your Worker routing in a configuration file that you can keep in alongside the rest of your code in version control. And it intelligently manages your routes as you edit them and re-deploy your application.


# serverless.yml

service:
   name: hello-world
   config:
     accountId: CLOUDFLARE_ACCOUNT_ID
     zoneId: CLOUDFLARE_ZONE_ID
     workers:
       hello:
         routes:
           - example.com/hello/*
       foo_script:
         routes:
           - example.com/foo/*

provider:
 name: cloudflare

plugins:
 - serverless-cloudflare-workers

functions:
 helloWorld:
   # What the script will be called on Cloudflare
   worker: hello
   # The name of the script on your machine, omitting the .js file extension
   script: helloWorld
   # Events are only relevant to the `serverless invoke` command and don’t affect deployment in any way
   events:
     - http:
         url: example.com/hello/user
         method: GET
         headers:
           someKey: someValue

 

When you deploy with the Framework by running serverless deploy, everything in serverless.yml is deployed at once.

Performance

There’s a great blogpost with testing Cloudflare Workers performance and comparison with AWS Lambda.

This is a chart showing what percentage of requests to each service were faster than a given number of ms. It is based on thousands of tests from all around the world, evenly sampled over the past 12 hours. At the 95th percentile, Workers is 441% faster than a Lambda function, and 192% faster than Lambda@Edge.  

Cloudflare2

Source: https://blog.cloudflare.com/serverless-performance-comparison-workers-lambda/

Pricing

Workers is a usage-based product. You will be billed on the number of requests made to your Cloudflare-powered domains that trigger Workers. Since Cloudflare Workers run before the Cloudflare cache, the caching of a request still incurs costs.

You will be charged a minimum monthly fee of $5.00 per domain with Workers enabled. That fee includes the first 10 million Worker-powered requests made to that domain. After the first ten million, requests are billed at $0.50 per million. Workers pricing is not dependent on how much CPU time your Workers use, but we do raise the CPU time limits based on which Cloudflare plan you are on.

Your Worker can be configured to only run on specific routes within your site. For example you may only wish your Worker ran on URLs within a specific subdomain or the index page of your site. Only requests which actually trigger Workers count against your billed usage.

Here's the deployment history of one of Minecraft’s APIs. It went from 0 to 5 million requests with no scaling, no resizing, no servers, no clusters, and no containers. Just code. And for 50 cents for every 1 million requests, it's incomparable to the other serverless solutions on the market.

Cloudflare30 to 5 million requests with no scaling, no resizing, no servers, no clusters, and no containers.

Summary

You can go from 0 to 5 million requests with no scaling, no resizing, no servers, no clusters, and no containers. Just code.

You can deliver that code manually or using Serverless framework or Terraform.

The Developer experience is just amazing!

With all this mentioned, Cloudflare enters the game of FaaS providers as a strong competitor with its Cloudflare workers.

Literature

https://developers.cloudflare.com/workers/about/

https://blog.cloudflare.com/minecraft-api-with-workers-coffeescript