Cloudflare and Edge Roadmap
Cloudflare runs one of the largest networks in the world, and a growing share of web traffic passes through it. Most people first meet it as a DNS host, a CDN and a firewall in front of a website. Over the last few years it has become a place to run the application itself: Workers for code, KV, R2 and D1 for data, Durable Objects for state, Queues for background work and Workers AI for models. The word edge describes the idea behind all of it: do the work in a data centre near the user.
This roadmap is for developers who want to build and operate on that platform, and for engineers who are asked about edge computing, caching and serverless design in interviews. It starts with the web basics that every edge product depends on, then covers Workers, storage, caching, security, async processing, AI and operations. Each topic explains the general concept first, so what you learn about isolates, eventual consistency or cache keys applies to other edge platforms too.
When you finish, you can deploy a Worker with a router and tests, pick the right store for each kind of data, cache and secure a site correctly, run reliable background jobs, and explain the trade-offs of the edge model in an interview. Practise the coding parts in your own free account, and use system design practice to rehearse design questions.
- Level
- Beginner to advanced
- Time
- 10-14 weeks at about 8 hours a week
- Scope
- 65 topics in 10 stages
- Before you start
- JavaScript Roadmap fundamentals, including promises and async code; Basic understanding of HTTP, requests and responses; Comfort with a terminal and Git; A free Cloudflare account and a test domain (optional but useful)
What you will be able to do
- Explain how DNS, a reverse proxy, a CDN and a firewall work together for one request.
- Build, test and deploy a Worker with routing, validation and typed bindings using Wrangler.
- Choose between KV, R2, D1 and Durable Objects for a given data need and defend the choice.
- Design cache headers and edge caching rules that are fast and safe for personal data.
- Secure an application with TLS, security headers, rate limiting and a WAF.
- Run reliable background work with Queues and Workflows, including retries and dead letter queues.
- Build a retrieval-based AI feature with Workers AI and Vectorize behind a gateway.
- Ship with a pipeline and diagnose production faults using logs, metrics and debugging tools.
The roadmap at a glance
- Stage 1Web and Edge FoundationsBeginner · 1-2 weeks · 8 topics
- Stage 2Workers CoreBeginner · 2 weeks · 8 topics
- Stage 3Frameworks and Developer ToolsIntermediate · 2 weeks · 8 topics
- Stage 4Storage: KV, R2 and D1Intermediate · 3 weeks · 9 topics
- Stage 5State at the Edge: Durable ObjectsAdvanced · 2 weeks · 5 topics
- Stage 6Caching, Security and DeliveryIntermediate · 2-3 weeks · 9 topics
- Stage 7Async Work, Events and IntegrationAdvanced · 2-3 weeks · 7 topics
- Stage 8AI on the EdgeAdvanced · 2-3 weeks · 5 topics
- Stage 9Media and Browser ServicesIntermediate · 1-2 weeks · 3 topics
- Stage 10Operations: Ship, Observe, DebugIntermediate · 1-2 weeks · 3 topics
Stage 1 Web and Edge Foundations
Goal. Explain what the edge is, how a request travels through DNS, a CDN and a proxy, and why serverless suits it.
Edge Computing Fundamentals Core
Edge computing means running code and keeping data in many small locations close to users, instead of in one or two large regions. Cloudflare operates data centres in hundreds of cities, and every one of them can answer requests. A visitor in Lagos is served from a nearby site rather than from a server in Virginia.
The gain is latency. Light in fibre takes time to cross an ocean, and a page that needs six round trips to a distant origin feels slow however fast the server is. The cost is that your code runs in many places at once, so global shared state is hard. Most edge design is about deciding what can be cached or computed locally and what must still live in one authoritative place.
Practice. Use a trace tool or the browser network panel to compare the time to first byte of a site behind a CDN and one that is not.
HTTP and Web Protocols Core
Everything on the edge is HTTP. A request has a method, a URL, headers and an optional body. A response has a status code, headers and a body. You should know the meaning of the common methods (GET, POST, PUT, PATCH, DELETE) and the status families: 2xx success, 3xx redirects, 4xx client errors, 5xx server errors.
Know the versions too. HTTP/1.1 sends one request at a time per connection, HTTP/2 multiplexes many over one connection, and HTTP/3 runs over QUIC on UDP to avoid head-of-line blocking at the transport layer. Cloudflare terminates all of them at the edge and talks to your origin in whichever version it supports. TLS, cookies, CORS and the cache headers Cache-Control, ETag and Vary matter every day in this work.
Practice. Use curl with the verbose flag to read the headers of three public sites and explain each cache-related header you see.
DNS, CDN and Reverse Proxy Basics Core
DNS turns a name into an address. When you put a domain on Cloudflare you point its nameservers at Cloudflare, which then answers DNS for you. Records you will meet are A and AAAA (addresses), CNAME (an alias), MX (mail), TXT (verification and policy) and NS (delegation).
A record can be proxied, shown as an orange cloud. Then the name resolves to a Cloudflare address, not your origin, and traffic flows through Cloudflare's reverse proxy. That is what lets it cache static files, absorb attacks, terminate TLS and run the web application firewall (WAF) before anything reaches your server. A grey cloud record is DNS only and bypasses all of this.
Practice. Add a free domain or a test zone, create one proxied and one DNS-only record, and show with dig which addresses each returns.
Understand Serverless Architecture Core
Serverless means you write functions and the platform handles servers, scaling and patching. You pay for use rather than for idle machines. There are still servers, you just do not manage them.
Workers is Cloudflare's version. You deploy a small script, and it runs on demand in any data centre. There is no region to choose. Compared with a traditional function service the key differences are very fast start-up, because Workers uses lightweight isolates rather than containers, and global deployment by default.
Practice. List three workloads that fit a Workers model and three that do not, with one reason each.
JavaScript Fundamentals Core
Workers are written in JavaScript or in languages that compile to it or to WebAssembly. You need solid JavaScript: const and let, arrow functions, destructuring, modules with import and export, and above all asynchronous code.
Almost every call at the edge returns a promise. Use async and await, know that await pauses only the current function, and run independent calls together with Promise.all. Understand that an unhandled rejection becomes a failed request.
const [user, prefs] = await Promise.all([
getUser(id),
getPrefs(id),
]);
Practice. Write an async function that fetches two public JSON endpoints in parallel and returns a merged object.
TypeScript Fundamentals Recommended
Most Workers projects use TypeScript. It catches mistakes such as a missing binding or a misspelled property before you deploy. You need the basics: type annotations, interfaces and type aliases, unions, generics and unknown over any.
The key Workers idea is typing the environment. Wrangler can generate a type definition from your configuration so that env.MY_BUCKET is known to be an R2 bucket, and it also generates types for the runtime APIs. Run the type generation command again whenever you add a binding.
interface Env {
CACHE: KVNamespace;
DB: D1Database;
API_KEY: string;
}
Practice. Define an Env interface for a Worker that uses one KV namespace and one secret, and use it in a fetch handler.
Node.js and NPM Core
You do not run Workers on Node.js, but you use Node.js to build them. It runs Wrangler, your tests, your type checker and your bundler. Install a current long-term-support release.
NPM is the package manager. package.json lists dependencies and scripts, and the lockfile pins exact versions so builds repeat. Know npm install, npm run, npx and the difference between dependencies and dev dependencies. Pnpm and Yarn work equally well.
Practice. Create a project folder with npm, add one small dependency and a script, and explain what changed in package.json and the lockfile.
Basic Command-line Knowledge Core
Cloudflare work is driven from the terminal. You should be at ease moving between folders, listing files, reading and searching text, setting environment variables, chaining commands with pipes and reading exit codes.
Useful tools here are curl for sending requests and reading headers, jq for slicing JSON, git for history and dig for DNS. You will run Wrangler dozens of times a day, and scripts in CI use the same commands.
curl -sI https://example.com | head -n 5
curl -s https://api.example.com/items | jq '.items[0]'
Practice. Write a shell one-liner that calls an API with curl, filters one field with jq and saves the result to a file.
Stage 2 Workers Core
Goal. Build, run and deploy a Worker that routes requests, reads input and returns correct responses.
Workers Runtime Environment Core
The Workers runtime is called workerd. It is open source and built on the V8 JavaScript engine, the same engine that powers Chrome. It exposes web-standard APIs and a few Cloudflare-specific ones, and it also runs WebAssembly.
A Worker is a module that exports handlers. The most common is fetch, which receives a request, the environment and an execution context, and returns a response.
export default {
async fetch(request, env, ctx) {
return new Response('Hello from the edge');
},
};Other handlers are scheduled for cron triggers, queue for message batches and email for incoming mail. Limits apply to CPU time per request, memory, subrequests and bundle size. They differ by plan and change over time, so read the current limits page before you design around them.
Practice. Write a Worker that returns JSON containing the request method and path, and run it locally.
Isolates Architecture Core
A V8 isolate is a lightweight sandbox inside one process. Many isolates share one runtime process, and each has its own memory heap and cannot see the others. Starting one takes a few milliseconds, far less than booting a container or a virtual machine.
That is why Workers rarely suffer from the cold starts people complain about elsewhere. It is also why the platform can host a very large number of customer scripts on the same machines. Cloudflare can also begin warming the isolate while the TLS handshake is still in progress.
Practice. Add a module-level counter to a Worker, call it repeatedly, and write down why the number is not reliable.
Workers Lifecycle Core
Each request moves through a clear sequence. The platform picks a location, finds or creates an isolate with your code, runs the handler and sends back the response. When the response is finished, the request is over, and the runtime may stop work that you left running.
To do work after responding, use ctx.waitUntil(promise). It tells the runtime to keep the isolate alive until the promise settles, for example to write a log line or refresh a cache entry without delaying the user. Without it, pending work can be cancelled.
ctx.waitUntil(env.LOGS.put(key, entry));
return new Response('ok');
Practice. Use waitUntil to record a log entry after sending a response, and show that the response does not wait for it.
Fetch API and Runtime APIs Core
fetch is the one HTTP client you need. It takes a URL or Request and returns a promise of a Response. Use it to call origins, other APIs and your own Workers. The runtime also provides Headers, URL, URLSearchParams, FormData, TextEncoder, crypto.subtle for hashing and signing, crypto.randomUUID(), streams, setTimeout and console.
Cloudflare adds extras. On outgoing fetches a cf option lets you control caching and image resizing for that call. On incoming requests, request.cf carries properties such as the visitor's country, city, colo, ASN and TLS details, which is handy for localisation and for security rules.
Practice. Return the visitor country and colo from request.cf in a JSON response and test it from two networks if you can.
Request/Response Handling Core
Real handlers read several parts of a request. Parse the URL with new URL(request.url) to get the path and query string. Read headers with request.headers.get('x-name'). Read a body once, as .json(), .text(), .formData() or .arrayBuffer(). The body is a stream, so a second read fails unless you call request.clone() first.
Build responses with the right status and headers. Response.json(data, { status: 201 }) handles the content type for you. Use 400 for bad input, 401 or 403 for access problems, 404 for missing items and 429 when you throttle.
const url = new URL(request.url);
if (request.method === 'POST') {
const body = await request.json();
return Response.json({ received: body }, { status: 201 });
}
Practice. Write a POST endpoint that validates a JSON body, returns 400 with a helpful message on bad input and 201 on success.
Wrangler Core
Wrangler is the command line tool for Workers. wrangler init or a project generator creates a project, wrangler dev runs it locally, wrangler deploy publishes it, wrangler tail streams live logs and wrangler secret put stores a secret.
Configuration lives in a file at the project root, either wrangler.toml or the newer wrangler.jsonc. Cloudflare now recommends JSON with comments for new projects, but both work.
{
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2025-01-01",
"kv_namespaces": [{ "binding": "CACHE", "id": "abc123" }]
}The compatibility_date pins runtime behaviour. New behaviour is turned on by a later date, so old Workers keep working. Set it to a recent date when you create a project, and update it deliberately, not by accident.
Practice. Create a project with Wrangler, deploy it to a workers.dev address, tail its logs and roll back to an earlier version.
Routing Core
Routing means deciding which code handles a request. There are two layers. First, Cloudflare must send the request to your Worker. You can attach a Worker to a custom domain, to a route pattern such as example.com/api/* or to the free workers.dev subdomain. Second, inside the Worker you pick a handler by method and path.
A small project can use plain checks.
const { pathname } = new URL(request.url);
if (pathname === '/health') return new Response('ok');
if (pathname.startsWith('/api/')) return api(request, env);
return new Response('Not found', { status: 404 });As routes grow, a router library gives you path parameters, method matching and middleware. Hono and Itty Router, covered next, are the common choices. Keep the route table readable: a single glance should show what the service exposes.
Practice. Attach a Worker to a route pattern on a test domain and add three routes with different methods.
Bindings Core
A binding is a named connection between your Worker and a resource, declared in configuration. At runtime it appears as a property of env. Instead of fetching a database by URL with a password, you write env.DB.prepare(...), and the platform handles the connection and the permission.
Bindings exist for KV namespaces, R2 buckets, D1 databases, Durable Objects, Queues, Vectorize indexes, Workers AI, other Workers (service bindings), plain-text variables and secrets.
Practice. Add a KV namespace and a secret as bindings and read both inside a Worker.
Stage 3 Frameworks and Developer Tools
Goal. Structure larger Workers with a router, serve full applications and set up a fast local and test workflow.
Hono and Itty Router Core
Hono is a small, fast web framework built on web standards. It runs on Workers, Deno, Bun and Node.js, so what you learn transfers. It gives you a router, path parameters, middleware, validators and typed bindings.
import { Hono } from 'hono';
const app = new Hono<{ Bindings: Env }>();
app.get('/items/:id', async (c) => {
const row = await c.env.DB.prepare('SELECT * FROM items WHERE id = ?')
.bind(c.req.param('id')).first();
return row ? c.json(row) : c.notFound();
});
export default app;The context object c wraps the request and the response helpers. Exporting the app as the default export works because it has a fetch method. Hono is a sound default for an API on Workers.
Practice. Rebuild a small CRUD API in Hono with typed bindings and a 404 handler. Then: implement the same three routes with Itty Router and compare the built bundle size with the Hono version.
Middleware Patterns Core
Middleware is code that wraps handlers to do shared work: logging, authentication, CORS headers, rate checks, error handling and timing. Each piece calls the next one, or stops the chain by returning a response.
In Hono, app.use('*', fn) registers a function that receives the context and a next callback. Code before await next() runs on the way in, and code after it runs on the way out, where you can adjust the response.
app.use('*', async (c, next) => {
const start = Date.now();
await next();
c.header('X-Response-Time', String(Date.now() - start));
});
Practice. Write middleware that checks a bearer token, and another that adds a request id to every response and log line.
Any Frontend Framework Recommended
Workers can serve and render full applications. Cloudflare supports React, Vue, Svelte, Astro, Next.js, Remix and others, usually through an adapter that builds the app into a Worker plus static assets.
Two rendering styles matter. Static files go to the asset hosting layer and are cached at the edge. Dynamic pages run server-side rendering inside a Worker, so the HTML is built close to the user and can read from bindings directly, with no separate API server.
Practice. Deploy a starter app from a framework of your choice to Cloudflare and note which parts are static and which run as a Worker.
Pages Functions Recommended
Cloudflare Pages is the product for deploying a front-end site from Git. Each push builds the site, and each pull request gets a preview address. Pages Functions add server-side code: files in a functions folder become routes, so functions/api/hello.js answers at /api/hello.
Under the hood they are Workers, with the same bindings, but with file-based routing and a Pages-specific context object.
Direction of travel: Cloudflare has been bringing static asset hosting and Git builds into Workers itself and recommends Workers for new projects, while Pages continues to work. If you inherit a Pages project, you can maintain it as it is. If you start fresh, check current guidance, and expect that the concepts are the same in both.
Practice. Add a Pages Function that returns the current time as JSON and call it from the static page.
Development Tools Core
A good local loop makes Workers pleasant. wrangler dev starts the real runtime on your machine, serves your Worker on a local port and reloads on every save. It can simulate bindings locally, so KV, R2, D1 and Durable Objects work offline with local data.
You can also run against remote resources for a more faithful test, at the cost of touching real data, so use a separate preview environment, not production.
Practice. Set up staging and production environments in configuration with different KV namespaces and deploy to staging.
Miniflare Recommended
Miniflare is the local simulator for Workers. It started as a community project and is now maintained by Cloudflare. Wrangler uses it under the hood in local mode, and the Workers test integration is built on it.
Its job is to run your Worker and its bindings in-process with in-memory or on-disk storage, so that tests do not need a network or a Cloudflare account. You can also use it directly through its JavaScript API to dispatch requests and inspect storage.
Practice. Use the Miniflare API or the dev server to send a request to a Worker with a KV binding and inspect what was stored.
DevTools and DevTools Integration Recommended
Wrangler connects a debugger to your Worker through the same inspector protocol that Chrome DevTools uses. While wrangler dev runs, press the key shown in the terminal to open DevTools, set breakpoints, step through code, inspect variables, watch network calls and take memory profiles.
Editors can attach too. In Visual Studio Code you can add a launch configuration that connects to the inspector port, so you debug without leaving the editor. Source maps map the bundled code back to your TypeScript.
Practice. Set a breakpoint in a handler under wrangler dev and inspect the request headers when it pauses.
Testing Frameworks Core
Cloudflare provides a Vitest integration that runs your tests inside the real Workers runtime, so env has working bindings with isolated storage per test. That is the recommended route for new projects. A test can call the Worker's fetch handler directly or use a helper that behaves like a request from outside.
import { SELF } from 'cloudflare:test';
import { it, expect } from 'vitest';
it('returns health', async () => {
const res = await SELF.fetch('https://example.com/health');
expect(res.status).toBe(200);
});Test at three levels: pure functions with plain unit tests, handlers with fake or local bindings, and a small number of end-to-end checks against a deployed preview. Mock outgoing calls to third parties so tests stay fast and deterministic.
Practice. Write three Vitest tests for a handler: success, validation failure and a storage read.
Stage 4 Storage: KV, R2 and D1
Goal. Choose between KV, R2 and D1 for a given need and use each correctly from a Worker.
Workers KV Core
Workers KV is a global key-value store tuned for reads. You write a value under a key, and it is replicated and cached across the network, so reads in most places are very fast. The catch is consistency: writes are eventually consistent. After a change, another location may serve the old value for up to about a minute, and heavy write rates to one key are limited.
Practice. Store a feature-flag JSON object in KV, read it from a Worker, change it and time how long the update takes to appear elsewhere.
Key-value Operations, Metadata Handling and Bulk Operations Core
The core calls are get, put, delete and list. Use the type argument to parse on read, and expirationTtl to make a key disappear on its own.
await env.CACHE.put('user:42', JSON.stringify(user), { expirationTtl: 3600 });
const user = await env.CACHE.get('user:42', 'json');
const page = await env.CACHE.list({ prefix: 'user:', limit: 100 });Design keys with a prefix scheme such as type:id, because list filters by prefix and returns keys in lexicographic order, in pages that you follow with a cursor. A get of a missing key returns null, not an error. For hot keys, KV also caches reads at the edge, and you can raise cacheTtl for values that rarely change, trading freshness for speed.
await env.CACHE.put('doc:1', body, { metadata: { title: 'Intro', updated: 1730000000 } });
const { value, metadata } = await env.CACHE.getWithMetadata('doc:1');
Practice. Build a tiny URL shortener on KV and list every short code that starts with a given prefix. Then: store a document with a title in metadata and list all titles in one call without reading any values. Then: write a script that loads five hundred records into KV using the bulk API in chunks.
R2 Storage and Object Storage Core
Object storage keeps whole files, called objects, in buckets and addresses them by key. It is the right place for images, video, backups, logs and user uploads. R2 is Cloudflare's object store. It speaks the S3 API, so existing tools and SDKs work, and it does not charge for egress, the data you send out. That removes a major cost of serving large files from other clouds.
await env.BUCKET.put('avatars/42.png', request.body, {
httpMetadata: { contentType: 'image/png' },
});
const obj = await env.BUCKET.get('avatars/42.png');
return new Response(obj.body, { headers: { etag: obj.httpEtag } });
Practice. Create a bucket, upload a file through a Worker, and serve it back with correct content-type and cache headers.
Bucket Operations and Bucket Lifecycle Core
Beyond put and get you need head (metadata only, no body), delete (one key or many), and list with a prefix and a delimiter to simulate folders. Listing returns pages, so follow the cursor until truncated is false.
Access has three common shapes. A Worker binding gives private access with your own rules, such as checking a session before returning a file. A public bucket, through a custom domain, serves files directly. A presigned URL, made with the S3-compatible API, lets a browser upload or download a single object without going through your Worker.
Practice. Implement list-with-prefix pagination and a presigned upload URL, and upload a file from the browser with it. Then: add a rule that deletes objects under tmp/ after seven days and one that aborts stale multipart uploads.
Large File Handling Recommended
A single request body has size limits that depend on plan, and a Worker has memory limits, so never read a big file into memory. Stream it. Passing request.body straight into bucket.put, or returning object.body as a response, moves bytes without buffering.
For very large uploads, use multipart upload. The file is split into parts, each uploaded separately and possibly in parallel, then completed into one object. A failed part is retried alone. The browser can do this directly using presigned part URLs.
Practice. Upload a file larger than your Worker body limit using multipart upload and verify its checksum.
D1 Core
D1 is Cloudflare's serverless SQL database, built on SQLite. You get tables, indexes, joins, transactions inside a batch, and the SQL you already know, with no server to run. It is accessed from a Worker through a binding, or through an HTTP API.
const { results } = await env.DB
.prepare('SELECT id, title FROM posts WHERE author = ? ORDER BY id DESC LIMIT 20')
.bind(authorId)
.all();Always use prepare with bind for parameters. It prevents SQL injection and lets the engine reuse plans. Databases have a size cap per database, so the intended pattern is many smaller databases, for example one per tenant, instead of one huge one. Read replication can place copies of the data near readers, and the Sessions API keeps reads in order for one user.
Practice. Create a D1 database with two tables, insert rows with bound parameters and join them in a query.
Schema Management and Migrations Core
A schema changes as the product grows, and migrations are the controlled way to do it. D1 has first-class support: wrangler d1 migrations create makes a numbered SQL file, and wrangler d1 migrations apply runs unapplied files in order and records them in a table so none runs twice.
-- migrations/0002_add_slug.sql
ALTER TABLE posts ADD COLUMN slug TEXT;
CREATE UNIQUE INDEX idx_posts_slug ON posts(slug);Rules to keep. Never edit a migration that has run; add a new one. Test migrations against a local database first. Make changes backwards compatible, so that old code still works while new code rolls out: add a column, deploy code that uses it, then remove the old one later. SQLite supports fewer ALTER TABLE forms than larger systems, so some changes need a copy-table approach.
Practice. Write two migrations, apply them locally and remotely and add a rollback note to the second.
Query Optimization Recommended
Fast D1 queries come from the same habits as any SQL database. Add indexes for columns used in WHERE, JOIN and ORDER BY. Select only the columns you need. Use LIMIT and keyset pagination rather than large offsets. Avoid running a query inside a loop; fetch many rows at once, or send several statements in one batch.
Use EXPLAIN QUERY PLAN to see whether SQLite scans a whole table or uses an index. The response from D1 also includes metadata such as rows read and written and the duration, which you should log for slow paths, since billing follows rows read.
EXPLAIN QUERY PLAN
SELECT * FROM posts WHERE author = 7 ORDER BY id DESC;
Practice. Take a slow query, run EXPLAIN QUERY PLAN, add a composite index and compare rows read before and after.
Prisma and Drizzle Recommended
An ORM or query builder maps tables to typed code. Two popular choices work with D1.
Drizzle is a light, SQL-like TypeScript library. You define the schema in code, build queries that read like SQL and get inferred types. It adds little to bundle size, which suits Workers, and it generates migrations that work with Wrangler.
Prisma has a schema file, a generated client and a strong migration tool. It supports D1 through a driver adapter, so it can run on Workers, though the client adds more weight than Drizzle and you should check current setup notes.
Practice. Model a posts table in Drizzle, run a typed select and insert, and print the SQL it generates.
Stage 5 State at the Edge: Durable Objects
Goal. Use Durable Objects to hold coordinated state, build real-time features and reason about their guarantees.
Durable Objects Core
A Durable Object is a small stateful server with a name. Each object has a unique id, and all requests for that id are routed to a single instance somewhere in the world, so they are handled one at a time with no race conditions. Think of it as a class instance that lives at the edge and remembers its fields.
You define a class, bind it in configuration and call it through a stub.
export class Counter extends DurableObject {
async increment() {
let n = (await this.ctx.storage.get('n')) ?? 0;
await this.ctx.storage.put('n', ++n);
return n;
}
}
// in a Worker
const stub = env.COUNTER.getByName('page:home');
const n = await stub.increment();
Practice. Build a counter object, call it from a Worker and prove with parallel requests that no increment is lost.
Persistence Core
Each object has private durable storage. Two flavours exist. The key-value API has get, put, delete and list. A SQLite-backed object also gives you a real SQL database per object through ctx.storage.sql, which is the recommended choice for new classes.
Writes are persisted before the object releases its output, so a response you sent reflects data that survived. The input and output gates in the runtime ensure that while a storage operation is pending, no other event interleaves, which is what gives you simple, correct code without explicit locks.
Practice. Store a list of messages in the object storage, restart the dev server and confirm the list survives.
Coordination Core
The strength of Durable Objects is coordination. Because one instance owns an id, it can serialise work for everyone who touches that thing. Typical uses are: a lock or leader election for a job, a unique-name reservation, a rate limiter per user, a matchmaking queue, a collaborative document where edits are ordered, and a WebSocket chat room.
For WebSockets, the object accepts connections and fans messages out to all connected sockets. The hibernation API lets an object sleep while sockets stay open, so you pay only while it processes messages.
Practice. Build a chat room object that accepts WebSockets and broadcasts messages to everyone connected.
State Management Recommended
Where should state live? A helpful table of choices: per-request data lives in local variables; hot, shareable but disposable data lives in the cache; slow-changing global data lives in KV; relational records live in D1; files live in R2; and anything needing strict ordering or atomic updates lives in a Durable Object.
A frequent design is to combine them. A Worker checks the cache, then KV, then falls back to D1, and a Durable Object serves as the writer for items that need exact counters. The edge makes a fresh decision necessary for every piece of state: how stale may it be, who writes it, and how many writers are there.
Practice. Draw a table for a shop app listing each kind of data, where it lives and the staleness it tolerates.
Transactional Operations Recommended
Atomicity at the edge depends on the product. In a Durable Object, ctx.storage.transaction and the SQL transactionSync run a group of operations all-or-nothing, and since the object is single-threaded, there is no concurrent writer to conflict with.
D1 runs a batch of prepared statements inside an implicit transaction: if one fails, the batch rolls back. It does not offer long interactive transactions with application code between statements, so keep the logic in the SQL or in a single batch.
Practice. Transfer an amount between two accounts using a D1 batch and show that a failed second statement rolls back the first.
Stage 6 Caching, Security and Delivery
Goal. Cache correctly, secure traffic and applications at the edge and expose private services safely.
Cache API Core
The Cache API lets a Worker store and read responses in the data centre's cache with caches.default.match, put and delete. The key is a request URL, and the cache is local to that data centre, not global, so a change in one place does not appear in another.
const cache = caches.default;
let res = await cache.match(request);
if (!res) {
res = await fetch(request);
res = new Response(res.body, res);
res.headers.set('Cache-Control', 'public, max-age=300');
ctx.waitUntil(cache.put(request, res.clone()));
}
return res;Only GET responses are cached, and the response needs headers that allow it. Note the clone: a body can be read once. Purging works through the dashboard or API by URL, tag or prefix, and tiered caching can reduce the load on your origin by asking an upper-tier data centre first.
Practice. Cache an upstream API response for five minutes in a Worker and show the second request is a cache hit.
Caching Strategies and Caching Patterns Core
A strategy is a decision about what to cache, for how long, and how to refresh it. Static assets with hashed file names can be cached for a year as immutable. HTML changes more often, so use a short lifetime or revalidation. APIs that return personal data must not be cached by shared caches, which means Cache-Control: private or no-store.
Know the directives: max-age for browsers, s-maxage for shared caches, stale-while-revalidate to serve old content while fetching a new copy, and stale-if-error for resilience. The Vary header makes a cache keep separate versions, for example by language, but a loose Vary fragments the cache.
Practice. Choose and write the cache headers for four resource types: hashed script, HTML page, public API and private API. Then: implement stale-while-revalidate in a Worker and log when the background refresh runs.
Edge SSL/TLS Core
TLS encrypts traffic and proves the server's identity. At Cloudflare there are two connections: browser to edge, and edge to origin. The edge handles the first with a certificate it manages for you. The second depends on the encryption mode you choose.
The modes, from weakest: Off, Flexible (HTTPS to the edge, plain HTTP to the origin, which leaves a hole), Full (HTTPS to origin without checking its certificate) and Full (strict), which validates the certificate. Use Full (strict) on every production site. Origin certificates, which Cloudflare issues for free, work for the hop between the two.
Practice. Set Full (strict) with an origin certificate on a test zone and show that Always Use HTTPS redirects plain requests.
Web Security Headers Core
Response headers instruct the browser to protect users. The ones to know are:
Strict-Transport-Securityforces HTTPS on later visits.Content-Security-Policylimits where scripts, styles and frames may load from, and is the strongest defence against cross-site scripting.X-Content-Type-Options: nosniffstops the browser guessing content types.Referrer-Policycontrols how much of the address leaks to other sites.Permissions-Policyswitches off features such as camera access.X-Frame-Optionsor the CSPframe-ancestorsrule blocks clickjacking.
Practice. Write a Worker that adds a full set of security headers to an upstream response and check the result with a header scanner.
Rate Limiting Core
Rate limiting caps how often a client may do something, to stop abuse, brute-force logins and runaway scripts. Cloudflare offers it at several levels. WAF rate limiting rules run before your code and count requests by IP, header, path or other characteristics. A Workers rate limiting binding lets you check a limit from code, keyed on something you choose such as a user id. For exact, global counts, a Durable Object per key is the precise tool.
Practice. Protect a login route with a limit of five attempts per minute per user, using a rate limiting rule or a Durable Object.
Bot Management and the WAF Recommended
The web application firewall inspects requests and blocks known attack patterns such as SQL injection and cross-site scripting. Cloudflare's managed rulesets are maintained for you, and you add custom rules, written as expressions over the request, for your own cases.
Bot Management goes further. It scores each request from 1 to 99, where low means likely automated, using machine learning and behavioural signals. You can write rules that challenge or block low scores, while allowing verified good bots such as search engines. Simpler products include Bot Fight Mode and Turnstile, a CAPTCHA alternative that proves a visitor is human with little friction.
Practice. Write a custom rule that challenges requests to a login path with a low bot score and review its matches in analytics.
Workers Security Model Core
Isolation is the base of security on Workers. Each script runs in its own V8 isolate, with no shared memory, no access to the file system and no way to open arbitrary sockets except through the APIs you are given. The runtime also hides high-resolution timers, which blunts side-channel attacks. Cloudflare applies additional hardening and monitoring around the engine.
Your responsibilities start where theirs end. Keep secrets in secrets and not in code or plain variables. Grant each Worker only the bindings it needs. Validate every input. Verify webhook signatures. Pin the dependencies you bundle and review them, because a compromised package runs with your permissions.
Practice. Review a Worker and list its bindings, secrets and inputs, then remove one binding it does not need.
Tunnels Recommended
Cloudflare Tunnel connects a private service to Cloudflare without opening an inbound port. You run a small program called cloudflared next to the service. It makes outbound connections to Cloudflare, and traffic for a hostname flows back through them.
cloudflared tunnel login
cloudflared tunnel create demo
cloudflared tunnel route dns demo app.example.com
cloudflared tunnel run demoThe benefits: the origin has no public address to attack, you do not need a static IP or firewall changes, and you can combine it with Access so only authenticated people reach the service. Common uses are exposing a home or office server, internal dashboards, and development servers shared for review.
Practice. Expose a local web server at a real hostname through a tunnel and protect it with an Access policy.
HTML Rewriting Recommended
HTMLRewriter is a streaming HTML parser built into the runtime. You attach handlers to CSS selectors, and as the response flows through, your handlers can change attributes, replace text and insert or remove elements. Because it streams, it does not wait for the whole page and uses little memory.
return new HTMLRewriter()
.on('a[href^="http://"]', {
element(el) {
el.setAttribute('href', el.getAttribute('href').replace('http://', 'https://'));
},
})
.transform(await fetch(request));Good uses: personalising a cached page, injecting a script or banner, rewriting links when you migrate a site, A/B tests and adding security attributes. The selectors are limited compared with a browser, and you cannot walk to a parent node, so plan your changes as local edits.
Practice. Use HTMLRewriter to add rel="noopener" to every external link of a proxied page.
Stage 7 Async Work, Events and Integration
Goal. Move slow and unreliable work out of the request path and connect Workers to each other and to outside systems.
Queues and Background Jobs Core
Cloudflare Queues is a message queue with guaranteed delivery. A producer Worker sends messages, and a consumer Worker receives them in batches. This is the standard way to run background jobs: sending email, resizing images, calling a slow API or fanning out a task, all without making the user wait.
// producer
await env.JOBS.send({ type: 'welcome-email', userId: 42 });
// consumer
export default {
async queue(batch, env) {
for (const msg of batch.messages) {
await handle(msg.body, env);
msg.ack();
}
},
};Delivery is at least once, so a message can arrive twice. Make handlers idempotent, for example by recording a job id before acting. Batch size and wait time are settings that trade latency for throughput. Queues also offers delayed delivery, which suits retries and scheduled follow-ups.
Practice. Build a producer and consumer that sends a fake email job, and make the consumer safe to run twice for the same message.
Message Processing and Dead Letter Queues Core
In a consumer, you decide for each message whether it succeeded. Call ack() on success and retry() on a temporary failure, with an optional delay. If the handler throws and you have not acknowledged, the batch is retried. Acknowledge messages one by one so that a failure of the last item does not repeat all the earlier ones.
A message that keeps failing, called a poison message, must not loop forever. Set a maximum number of retries and a dead letter queue. After the limit, the platform moves the message to that second queue, where you can inspect it, fix the bug and replay it, or alert on it.
{ "queues": { "consumers": [{
"queue": "jobs", "max_retries": 5, "dead_letter_queue": "jobs-dlq"
}] } }
Practice. Make a consumer fail on purpose for one message and confirm it ends in the dead letter queue after the retry limit.
Workflows Recommended
Cloudflare Workflows runs a multi-step process durably. You write a class with a run method, and each unit of work is a step.do. The result of a finished step is stored, so if the workflow is interrupted or a later step fails, it resumes from where it stopped without redoing earlier work. Steps retry automatically with a policy you set.
export class Onboarding extends WorkflowEntrypoint {
async run(event, step) {
const user = await step.do('create account', () => createAccount(event.payload));
await step.sleep('wait a day', '1 day');
await step.do('send tips', () => sendTips(user));
}
}step.sleep can pause for days at no cost, and step.waitForEvent can wait for an outside signal such as a human approval. Use Workflows for onboarding flows, order processing, data pipelines and agent tasks. Keep each step small and idempotent.
Practice. Build a three-step workflow with a sleep and a deliberately failing step, and watch it retry and resume.
Event-driven Architectures and Webhook Handling Core
In an event-driven design, components react to events instead of calling each other directly. A user signs up, an order is paid or a file lands in R2, and each interested part handles it on its own. Cloudflare supplies the parts: R2 event notifications that publish to a Queue, cron triggers that run a scheduled handler, queues for decoupling and Durable Objects for ordered state.
Webhooks are the events other services send you. A Worker is a good endpoint. Three rules apply. Verify the signature, using a shared secret and a constant-time comparison, before you trust anything. Respond quickly with a 2xx, and put the real work on a queue, because senders time out and retry. Deduplicate by event id, since retries are normal.
const ok = await crypto.subtle.verify('HMAC', key, sigBytes, encoder.encode(rawBody));
if (!ok) return new Response('bad signature', { status: 401 });
await env.EVENTS.send(JSON.parse(rawBody));
return new Response('ok');
Practice. Receive a signed webhook, verify the signature, enqueue it and process each event id only once.
Email Workers Optional
Email Routing lets you receive mail for your domain and send it to an inbox. Email Workers adds code: an email handler receives each incoming message and can forward it, reject it with a reason, read its content or reply.
export default {
async email(message, env, ctx) {
if (message.from.endsWith('@spam.example')) {
message.setReject('Not accepted');
return;
}
await message.forward('team@example.com');
},
};Use cases are filtering, routing by address to different teams, turning email into support tickets, parsing receipts and triggering workflows from an email. You can also send mail from a Worker through the email sending binding to addresses you have verified. For bulk or marketing mail use a dedicated email provider, and keep SPF, DKIM and DMARC records correct so that mail is trusted.
Practice. Route mail for two addresses to two destinations and reject messages from one sender in an Email Worker.
Service Bindings and Inter Worker Communication Recommended
Service bindings let one Worker call another directly, with no public URL and no extra network hop. The call stays on the same machine in most cases and costs no extra request billing for the inner call. This enables a microservice-style design of many small Workers: an auth Worker, an API Worker, a billing Worker.
The newer RPC style is more pleasant than passing HTTP requests. You export a class that extends WorkerEntrypoint, and the caller calls its methods as if they were local.
export class Auth extends WorkerEntrypoint {
async verify(token) { return checkToken(token, this.env); }
}
// caller
const user = await env.AUTH.verify(token);
Practice. Split an auth check into its own Worker and call it from an API Worker through an RPC service binding.
External API Integration Core
Most real Workers call third-party services. Some habits make this reliable. Set a timeout with AbortSignal.timeout(5000) so a slow dependency cannot hold your request. Retry only idempotent calls, with back-off and a limit. Cache responses when the data allows. Handle every failure with a useful fallback or an honest error.
const res = await fetch('https://api.example.com/rates', {
headers: { Authorization: `Bearer ${env.API_KEY}` },
signal: AbortSignal.timeout(5000),
cf: { cacheTtl: 300, cacheEverything: true },
});
if (!res.ok) return Response.json({ error: 'upstream' }, { status: 502 });Never expose API keys to the browser; call the service from the Worker and hand the browser only the result. Watch subrequest limits, and respect the provider's rate limits by queuing work when you must make many calls. This role, a safe façade over third parties, is among the most common uses of Workers.
Practice. Write a Worker that proxies a public API with a timeout, a cache and a clear 502 on failure.
Stage 8 AI on the Edge
Goal. Run models, search by meaning and route model traffic from a Worker.
Workers AI and AI Model Integration Recommended
Workers AI runs open models on Cloudflare's GPUs, with no servers to manage. You add an AI binding and call a model by name. The catalogue includes text generation, embeddings, image generation, classification, translation and speech models, and it changes as models are added and retired, so check the current list.
const out = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
messages: [{ role: 'user', content: 'Summarise: ' + text }],
});
return Response.json(out);For integration beyond the hosted models, a Worker can equally call any outside model API with fetch, keeping the key in a secret. Pick by quality, price, latency and data rules. The Worker's job is to build the prompt, call the model, validate the output and handle errors. See Prompt Engineering Roadmap and AI Agents Roadmap for what to do around the call.
Practice. Call a text model from a Worker with a system prompt and return the answer as JSON.
Text Generation and Speech Recognition Recommended
Text generation models take a list of messages and return a reply. Control it with max_tokens, temperature and, where supported, a response format that forces valid JSON. Streaming returns tokens as they are produced, with stream: true, and you pass the event stream straight to the browser so users see text appear at once.
const stream = await env.AI.run(model, { messages, stream: true });
return new Response(stream, { headers: { 'content-type': 'text/event-stream' } });Speech recognition turns audio into text. Workers AI offers Whisper-family models: you pass audio bytes and get a transcript, often with timestamps. Typical flow: a user uploads audio to R2, a Queue consumer transcribes it, and the text goes to D1 or a summarising model. Mind the limits on audio length, and chunk long recordings.
Practice. Stream a model reply to the browser, and transcribe a short audio clip and print its text.
Vectorize, Vector Embeddings and Similarity Search Recommended
An embedding is a list of numbers that places a piece of text, an image or other data in a space where similar meanings sit close together. A model creates it; Workers AI has embedding models. Similarity search finds the stored vectors nearest to a query vector, usually by cosine similarity.
Vectorize is Cloudflare's vector database. You create an index with a fixed number of dimensions and a metric, insert vectors with an id and optional metadata, and query for the top matches.
const emb = await env.AI.run('@cf/baai/bge-base-en-v1.5', { text: [question] });
const hits = await env.VEC.query(emb.data[0], { topK: 5, returnMetadata: 'all' });
Practice. Embed twenty short documents, store them in Vectorize and query with a paraphrase of one of them.
AI-powered Search and Filtering Recommended
Meaning-based search handles questions that keyword search misses. A typical design for retrieval-augmented generation has two phases. At index time, split documents into chunks, embed each and store it with metadata such as the source and section. At query time, embed the question, fetch the top chunks, then give them to a text model with an instruction to answer only from them and cite the source.
Practice. Build a question-answering endpoint over a folder of markdown files with chunking, retrieval, a permission filter and a cited answer.
AI Gateway Recommended
AI Gateway is a proxy that sits between your application and model providers. You change the base URL of your model calls to the gateway address, and you gain a control point without changing your code much.
What it gives you: logs of every request and response, token and cost analytics, caching of identical prompts, rate limiting, retries and fallbacks to another model or provider when one fails, and a single place to manage keys. It works with Workers AI and many outside providers.
Practice. Route a model call through a gateway, repeat it to see a cache hit and read the cost in the analytics.
Stage 9 Media and Browser Services
Goal. Serve images and video efficiently and automate a headless browser.
Images, Image Processing and Asset Management Recommended
Cloudflare Images stores, resizes and delivers pictures. Image transformations can also work on images that live elsewhere, such as in R2 or at your origin. You request a size, format and quality through a URL, and the edge makes the variant once and caches it. Automatic format negotiation serves AVIF or WebP to browsers that support them.
From a Worker you can transform on the fly with the cf.image option on a fetch, or use the Images binding for processing steps like resize, rotate and draw overlays.
return fetch(imageUrl, { cf: { image: { width: 800, fit: 'cover', format: 'auto' } } });
Practice. Serve one R2 original in three widths using transformations and compare the byte sizes.
Stream, Video Delivery, Video Processing, Live Streaming and Calls Optional
Cloudflare Stream is a managed video service. You upload a file or a link, and it encodes it into several qualities, stores it and delivers it with adaptive bitrate streaming (HLS and DASH) so that players pick a quality to match the viewer's connection. Pricing is based on minutes stored and minutes delivered, not on bandwidth.
For live streaming, you send an RTMPS or SRT feed to a live input, and viewers watch through the same player. Recording to a video on demand copy is built in. Signed URLs and tokens restrict who may watch.
Practice. Upload a short clip to Stream, embed the player and generate a signed URL that expires in an hour. Then: sketch the signalling messages two browsers need to start a call and note where a Durable Object would help.
Browser Rendering Optional
Browser Rendering gives a Worker a headless Chromium browser that Cloudflare runs for you. You control it with Puppeteer or Playwright, or a simple REST API, to take screenshots, make PDFs, scrape pages that need JavaScript, test pages and capture rendered HTML.
import puppeteer from '@cloudflare/puppeteer';
const browser = await puppeteer.launch(env.BROWSER);
const page = await browser.newPage();
await page.goto('https://example.com');
const png = await page.screenshot();
await browser.close();Browsers are heavy, so limit concurrency, reuse sessions where you can, and always close them. Run long jobs from a queue. Respect the sites you visit: obey their terms, robots rules and rate limits. Cloudflare's own bot controls identify this service as automated traffic, so it is not a way to evade protection on other sites.
Practice. Write a Worker that returns a PNG screenshot of a URL given in the query string, with a domain allow-list.
Stage 10 Operations: Ship, Observe, Debug
Goal. Deploy safely, watch production and find faults quickly.
CI/CD Pipelines Core
A pipeline tests and ships each change the same way every time. A common flow: on a pull request, install dependencies, type-check, lint, run tests and deploy to a preview; on merge to the main branch, deploy to staging, run smoke tests and then production.
Wrangler works in CI. Create an API token with only the permissions needed, store it as a CI secret and run wrangler deploy. Cloudflare also offers Workers Builds, which connect a Git repository and build on every push. Use versions and gradual deployments to send a small share of traffic to the new version first, then raise it, and roll back immediately if error rates rise.
- run: npm ci
- run: npm test
- run: npx wrangler deploy
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CF_TOKEN }}
Practice. Create a pipeline that tests, deploys to staging on merge and deploys to production after a manual approval.
Logging and Monitoring, and Monitoring Tools Core
You cannot attach a debugger to production, so logs and metrics carry the load. console.log output is visible live with wrangler tail and in the dashboard. Turn on Workers Logs, which stores and indexes logs, and Logpush to send them to storage or an analytics service. Log structured JSON with a request id, route, status and duration, rather than free text, so that you can search and aggregate.
Practice. Add a structured JSON log line with request id and duration to a Worker, and search for it in the log viewer. Then: write a data point to Analytics Engine for every request and query the count by route with SQL.
Debugging Techniques Core
Start with the question: what changed? Check the latest deployment, a configuration change, a binding, a dependency or an upstream service. Then reproduce. Copy the failing request with its headers, replay it with curl against local wrangler dev, and use DevTools breakpoints.
- A script that exceeded CPU time points to heavy loops, large JSON or expensive crypto.
- Error 1101 means an uncaught exception in your Worker; look at the logs for the stack.
- A 522 or 524 comes from the origin timing out, not from your Worker.
undefinedonenv.Xmeans the binding is missing in the configuration for that environment.- Stale content means a cache layer; check headers such as
cf-cache-status.
Practice. Break a Worker in four ways from the list above and write how you would tell each one apart from the logs.
Projects to build
Build these in order. Each one should end up in a public repository with a short README that explains your decisions.
- Edge redirect and link shortenerBeginner
Build a service that maps short codes to long addresses. Store the table in KV, serve redirects from a Worker, add an admin endpoint protected by a token and count visits. Write tests for the routes.
Workers · KV · Routing · Secrets · Testing
- Security headers and proxy WorkerBeginner
Put a Worker in front of an existing site that adds security headers, rewrites insecure links with HTMLRewriter and caches HTML for a short time. Compare the result before and after with a header scanner and a speed test.
Fetch · HTMLRewriter · Caching · Security headers
- Image upload and galleryIntermediate
Let users upload pictures straight to R2 with presigned URLs, record each in D1 and show a gallery with resized, format-negotiated variants. Add a lifecycle rule for abandoned uploads and a limit on allowed sizes.
R2 · D1 · Image transformations · Presigned URLs · Migrations
- Real-time chat with rate limitsIntermediate
Create chat rooms where each room is a Durable Object using WebSockets, with messages kept in its storage and a per-user rate limit. Add a Hono API for room lists backed by D1.
Durable Objects · WebSockets · Rate limiting · Hono
- Webhook processing pipelineAdvanced
Receive signed webhooks, verify them, queue each event, process with a consumer that is safe to repeat and send failures to a dead letter queue. Add a Workflow that follows up after a day. Include dashboards for queue depth and errors.
Queues · Workflows · Idempotency · Monitoring
- Document question-answering serviceAdvanced
Index a set of documents with embeddings in Vectorize, answer questions with a Workers AI model using retrieved chunks and cite sources. Add per-tenant filtering, an AI Gateway for logging and caching, and a small evaluation set of questions.
Workers AI · Vectorize · AI Gateway · Filtering · Evaluation
Interview questions
Try to answer each question out loud before you open the answer.
What is the edge, and why run code there?Junior
The edge is a set of data centres spread near users. Running code there removes long round trips to a central region, so pages and APIs respond faster, and it absorbs load and attacks before they reach the origin. The cost is that code runs in many places, so shared state needs care. I put per-request logic, caching and routing at the edge, and keep strongly consistent data in one authoritative store such as D1 or a Durable Object.
How does a request reach your site when it is proxied through Cloudflare?Junior
The browser resolves the name through DNS and gets a Cloudflare address, because the record is proxied. The request reaches the nearest data centre, which terminates TLS, applies firewall and rate rules, and checks the cache. On a hit it replies directly. On a miss, or if a Worker is attached to the route, the Worker runs and may fetch the origin, then the response goes back through the cache to the user.
How are Workers different from containers or virtual machines?Junior
Workers run in V8 isolates, many to a process, each with its own heap. An isolate starts in milliseconds, uses little memory and is deployed everywhere without choosing a region. Containers offer a full operating system and any language, but start slower and cost more at idle. Isolates have tighter limits on CPU time and memory, no file system and no arbitrary sockets. I choose Workers for request-driven logic and a container for heavy or long-running software.
What is a binding and why does Cloudflare use them?Junior
A binding connects a Worker to a resource through configuration and appears as a property of the env object. There is no URL or credential in the code. Access is limited to what is declared, secrets cannot leak through code, and calls stay inside Cloudflare's network. It also helps tests, since I can supply fakes for env.
When would you choose KV over D1, R2 or a Durable Object?Mid
KV suits read-heavy data that tolerates a delay, such as configuration, flags and redirect tables, because reads are cached globally and writes become visible within about a minute. D1 is for relational data and queries. R2 is for files. A Durable Object is for data with strict ordering or counters. I decide by asking how stale a read may be, who writes and how many writers there are.
Explain eventual consistency in KV with an example of a bug it can cause.Mid
After a write, other locations may serve the old value for a short time. If a user updates a setting and the next request lands in a different data centre, they may see the old value and think the save failed. Using KV to count stock or to enforce one-time tokens is worse, since two locations can both see the old state. I would use a Durable Object or D1 for those, or read-your-writes handling in the client.
How do you make a queue consumer safe when messages can be delivered more than once?Mid
Delivery is at least once, so the handler must be idempotent. I give every message a unique id and record it in D1 or a Durable Object before acting, or I use an operation that is naturally repeatable, such as setting a value rather than incrementing it. I acknowledge each message individually, set a retry limit with back-off and attach a dead letter queue so poison messages are kept for inspection.
How do you cache an API response safely on Cloudflare?Mid
I first decide whether the response is the same for everyone. If so, I set Cache-Control with s-maxage, add stale-while-revalidate for smoothness and make the cache key ignore irrelevant query parameters. If it is personal, I send private or no-store so shared caches do not keep it. I check the cf-cache-status header, track hit ratio and use tags or versioned URLs for invalidation rather than manual purges.
What are Durable Objects and what problem do they solve?Mid
A Durable Object is a named, single-instance object with private storage. All requests for one id go to the same instance, one at a time, so there are no races. It solves coordination: counters, locks, chat rooms, collaborative documents and per-user rate limits. The design rule is one object per unit of coordination, never one for the entire app, otherwise it becomes a bottleneck.
How would you rate limit a login endpoint?Mid
I use a WAF rate limiting rule for a coarse limit by IP, which stops floods before they reach code. Inside the Worker I limit by account name too, with a Durable Object or the rate limiting binding, since attackers spread attempts across addresses. I return 429 with Retry-After, add Turnstile after repeated failures and log blocked attempts. Shared IPs mean the account key matters more than the address.
Describe the TLS modes between Cloudflare and your origin.Mid
Flexible encrypts only the visitor leg and talks plain HTTP to the origin, which leaves traffic readable on the open internet. Full encrypts both legs but accepts any certificate. Full (strict) validates the origin certificate, which can be a free Cloudflare origin certificate. I use Full (strict) for production, add HSTS and redirect to HTTPS. A redirect loop usually means Flexible mode with an origin that forces HTTPS.
A Worker is slow for users in one region. How do you investigate?Senior
I look at metrics by data centre, split CPU time from wall time and check subrequest durations. High wall time with low CPU points to a slow dependency, often a database or origin far from where the Worker runs. Smart Placement, a cache layer, fewer round trips or a read replica may help. I also check cache hit ratio and whether the issue began after a deployment, using version history.
How would you build a retrieval-based question answering feature on this platform?Senior
Documents are chunked, embedded with Workers AI and stored in Vectorize with metadata for source and tenant. A query is embedded with the same model, filtered by tenant, matched to the top chunks and passed with an instruction to answer from them only and cite sources. A gateway adds logging, caching and fallbacks. I evaluate with a fixed set of questions and watch retrieval quality separately from generation quality.
What are the limits and trade-offs of the Workers model?Senior
CPU time, memory and subrequests are limited, there is no file system, long jobs must move to Queues or Workflows, and Node-only packages may not run. State must live in a storage product, and consistency differs by product. In return you get global deployment, quick start-up, low operations work and pricing that follows use. I would avoid it for heavy compute or software that needs a specific operating system.
Common mistakes
- Keeping state in module variables; the isolate can be replaced at any time, so use KV, D1 or Durable Objects.
- Using KV for counters or stock, which fail under eventual consistency; use a Durable Object or D1.
- Leaving SSL on Flexible mode; use Full (strict) with an origin certificate.
- Caching responses that contain personal data; send private or no-store and test with two accounts.
- Reading whole files into memory; stream bodies between R2, fetch and the response.
- Forgetting waitUntil for background work, so it is cancelled when the response finishes; wrap it.
- Writing queue consumers that are not idempotent; record a message id before acting.
- Putting secrets in configuration files or code; use wrangler secret and keep .dev.vars out of Git.
- Not setting a compatibility date, or changing it without testing; pin it and update on purpose.
- Deploying straight to production from a laptop; use a pipeline with staging and gradual rollout.
Ready-for-interview checklist
- I can trace a request from DNS lookup to the response through the proxy, the cache and a Worker.
- I can explain isolates and why Workers start so quickly.
- I can write a Worker with a router, validation, typed bindings and tests.
- I can choose between KV, R2, D1 and Durable Objects and state the consistency of each.
- I can write correct Cache-Control headers for static, HTML and personal responses.
- I can explain the four SSL/TLS modes and pick the right one.
- I can set up rate limiting and explain how to choose its key.
- I can build an idempotent queue consumer with retries and a dead letter queue.
- I can describe what a Workflow does and when it beats a queue.
- I can build a basic retrieval pipeline with embeddings and a vector index.
- I can write migrations for D1 and apply them safely.
- I can set up a deployment pipeline with staging, preview and rollback.
- I can use logs and metrics to find the cause of an error spike.
- I can explain the limits of the Workers model and when I would pick another platform.
Related roadmaps
- Cloud Computing RoadmapService models, networking, storage, cost and multi-cloud.
- AWS RoadmapCore services: IAM, EC2, S3, VPC, RDS, Lambda and more.
- Node.js RoadmapEvent loop, modules, HTTP, streams, frameworks and deployment.
- TypeScript RoadmapTypes, generics, narrowing, utility types and project setup.
- Docker RoadmapImages, containers, networking, volumes, Compose and security.
- System Design RoadmapScalability, caching, queues, consistency and the classic designs.
FAQ
How long does it take to learn Cloudflare Workers?
With solid JavaScript, you can deploy a useful Worker in a weekend. Becoming comfortable with storage, caching, security and queues takes about two to three months of regular practice. The edge concepts take longer than the syntax, so build small projects on each product.
Do I need to know Node.js to use Workers?
You need Node.js tooling to build and deploy, but the code runs in a web-standards runtime, not Node. Knowing promises, fetch, Request and Response matters more than knowing Node modules.
Is Cloudflare a replacement for AWS?
Not wholly. It covers many web workloads well, especially delivery, security, light APIs and storage, with simple pricing. Large organisations still use hyperscalers for specialised services. Learning both is common. See AWS Roadmap and Cloud Computing Roadmap.
Should I learn Workers or Pages first?
Learn Workers first. Pages Functions are Workers with file-based routing, and Cloudflare now steers new projects towards Workers with static assets, so the core knowledge is the same.
Is the edge useful if my users are all in one country?
Yes, though the latency gain is smaller. You still benefit from caching, DDoS protection, TLS handling, bot control and a simple deployment model. Check the value against your own numbers.