Cloudflare Workers

A serverless execution environment at the edge

By Leander Gilles

What we'll cover

  • Edge Computing
  • Serverless
  • Benefits of Workers
  • Limitations
  • Edge Storage
  • Cloudflare Pages

Edge Computing

Serverless

  • Only write functions
  • No need to manage servers, VMs or containers
  • No manual security updates needed*
  • Instant automatic scaling
  • Simple deployments
  • Pay-Per-Use

				addEventListener("fetch", event => {
					event.respondWith(handleRequest(event.request))
				})
				
				async function handleRequest(request) {
					return new Response("Hello world")
				}
Cold starts

Azure Functions and sometimes takes 10s to respond

Workers take 5ms to start

How can Cloudflare claim 0ms cold starts?

  • Uses Google's V8 JavaScript Engine under the hood
  • ... same as Chormium and Node.js
  • Support for JS, Rust, C and C++

Workers are not Node.js


          var http = require('http');
          var url = require('url');
          var fs = require('fs');
What can we use instead?

Web standards

Web standards

  • Encoding API
  • URL
  • ​Fetch
  • ​Timers: setInterval(), setTimeout()
  • Base64 utility methods: atob(), btoa()
  • Event Listeners
  • Web Crypto
  • Streams
CommonJS Modules do not work in workers

            var http = require('http');
Instead use ES Modules

            import { parse } from "cookie"
Cloudflare's policy on breaking changes:
"A change to the Workers runtime must never break an application that is live in production."

Developers may now opt into backwards-incompatible fixes by setting a compatibility date.


            # wrangler.toml
            compatibility_date = "2021-09-20"
          

How does the Workers runtime implement compatibility dates?


            if (compatibility_date < "2021-09-20") {
              // run old behavior
            } else {
              // run new behavior
            }
          
The Workers runtime is updated at least once a week

Workers are given 30s to complete any requests

Limits

  • 30s CPU Time
  • 128MB per Worker isolate
  • 1MB maximum script size (soon 2MB)

Pricing

Free plan Paid Plan - Unbound Paid plan - Bundled
Requests 100,000 / day 1 million, + $0.15/million 10 million, +$0.50/million
Duration 10ms CPU time / invocation 400,000 GB-s, + $12.50/million GB-s1,2 50 ms CPU time / invocation

Minimum of $5 per month on the Paid Plan

What's the point of Edge Computing without Edge Storage?

Workers KV

is a global, low-latency, key-value data store

Workers KV

  • Good for frequent reads and infrequent writes
  • Eventually-consistent
  • Takes up to 60 seconds to propagate to edge locations
  • Bad for non-atomic operations
  • Very infrequent read values are stored centrally

Workers KV


          addEventListener("fetch", event => {
            event.respondWith(handleRequest(event.request))
          })
          
          async function handleRequest(request) {
            const value = await NAMESPACE.get("first-key")
            if (value === null) {
              return new Response("Value not found", {status: 404})
            }
          
            return new Response(value)
          }

Durable Objects

  • Strongly-consistent
  • Only stored in one datacenter at a time
  • Every worker with the object's ID can send messages to it
  • Stored in-memory
  • Also persistet to disk
  • Automatically migrates to the closest datacenter

Durable Objects

Perfect use case:

Real-time collaborative document editing

R2 Storage

  • Rapid and Reliable Object Storage, minus the egress fees
  • Think AWS S3 or Azure Blob Storage
  • Replicates frequently requested objects to other regions
  • Automatic tiering
  • Complies with data sovereignty requirements (same as Durable Objects)

R2 Storage

  • Free egress (downloading data)
  • Free infrequent storage operations (single digits per second)
  • $0.015 per GB of data stored per month
  • AWS S3: $0.0245
  • Azure Blob Storage: $0.02

R2 Storage

Not yet generally available 😢

Storage summary

  • KV
  • Durable Objects
  • R2
  • Cache

Location-based personalization

  • Country: “US”
  • City: “Austin”
  • Continent: “NA”
  • Latitude: "30.27130"
  • Longitude: “-97.74260”
  • Postal code: "78701"
  • Metro code(dma): “635”
  • Region: “Texas”
  • Timezone: “America/Chicago”

Local development

  • Wrangler CLI
  • Miniflare: Fully-local simulator for Cloudflare Workers

🔥 Miniflare

  • Supports most Workers features, including KV, Durable Objects, WebSockets, modules and more.
  • Test and develop Workers without an internet connection
  • Reload code on change quickly

Environments


              # wrangler.toml
              type = "webpack"
              name = "my-worker-dev"
              account_id = "12345678901234567890"
              zone_id = "09876543210987654321"
              route = "dev.example.com/*"
              vars = { ENVIRONMENT = "dev" }
              
              [env.staging]
              name = "my-worker-staging"
              vars = { ENVIRONMENT = "staging" }
              route = "staging.example.com/*"
              
              [env.production]
              name = "my-worker"
              vars = { ENVIRONMENT = "production" }
              routes = [
              "example.com/foo/*",
              "example.com/bar/*"
              ]

wrangler publish --env staging

Similar products

  • AWS Lambda@Edge
  • Fastly Compute@Edge
  • And many more

Infastructure as Code

  • Terraform
  • Serverless Framework

Want to learn more?

Open-source headless CMS build by Cloudflare:

https://blog.cloudflare.com/production-saas-intro/

Bonus Slide: Cloudflare Pages

  • Host static sites
  • Globally deployed
  • Built-in, privacy-first, free web analytics
  • Workers support
  • Image compression and device-based resizing
  • This presentation is hosted on Pages
  • Preview link for every commit on GitHub or GitLab

Bonus Slide 2: Cloudflare Tunnel

  • Share your local development environment with collaborators
$ brew install cloudflare/cloudflare/cloudflared
$ cloudflared login
$ cloudflared tunnel --url http://localhost:3000
Links