Cloudflare Workers
medium 30 minCloudflare Workers runs small programs in Cloudflare's data centres around the world, close to the user.
See it run
Follow a request into an isolate, watch isolates come and go, read an old copy, meet in one object, and choose a place.
Operations
One request
A user in Sydney opens a page.
Step 1 of 5
Handshake
The user starts TLS. The location learns the host name and may load the script now.
Step 1: Handshake
export default { async fetch(request, env, ctx) { const flag = await env.FLAGS.get("new-page"); const page = await fetch(env.ORIGIN + pathFor(flag, request)); ctx.waitUntil(env.LOG.send({ flag })); return page; },};- Time
- a few ms of CPU
- What you need
- one isolate
Mention the TLS handshake: the script is loaded while the visitor waits for it anyway.
In the real world
The same cloudflare workers doing real jobs. Pick one and step through it.
The flag cannot be read.
Step 1 of 3
Error
500
The call to KV fails and the script has no plan. Users see an error page.
Step 1: Error
Common mistakes
The bugs interviewers watch for, with the fix beside each.
State in a global
criticalIsolates are many and may vanish; two users may also share one.
Wronglet user;export default { async fetch(r) { user = await who(r); ... } };Rightexport default { async fetch(r) { const user = await who(r); ... },};Stock in KV
criticalOld reads and lost updates sell more than there is.
Wrongconst n = await env.KV.get("stock");await env.KV.put("stock", n - 1);Rightconst item = env.STOCK.get(env.STOCK.idFromName(id));const ok = await item.take(1); // Durable ObjectWork that nobody awaits
majorIt may be cancelled when the request ends.
Wrongenv.LOG.send(entry);return page;Rightctx.waitUntil(env.LOG.send(entry));return page;Whole body in memory
major128 MB is shared by all requests of the isolate.
Wrongconst all = await response.arrayBuffer();return new Response(all);Rightreturn new Response(response.body, response);
Interview tips
How to explain it
- Isolates in a shared process.
- Runs near the user.
- State lives elsewhere.
Memory trick
- Globes show, the book remembers.
- 128 MB, 30 s of CPU.
- KV: a minute old.
Reach for it when
- Every request needs a check.
- One room needs one order.
- Users are all over the world.
Be careful with
- Data far from the code.
- One object for everything.
- Global releases at once.