AlgoViz

Cloudflare Workers

medium 30 min

Cloudflare 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

User, SydneySydney locationrouterIsolateloadingKVlocal copyOriginFrankfurt

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

User, SydneySydney locationrouterIsolateyour scriptKVfailingOriginFrankfurt

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

    critical

    Isolates are many and may vanish; two users may also share one.

    Wrong
    let user;export default { async fetch(r) { user = await who(r); ... } };
    Right
    export default {  async fetch(r) { const user = await who(r); ... },};
  • Stock in KV

    critical

    Old reads and lost updates sell more than there is.

    Wrong
    const n = await env.KV.get("stock");await env.KV.put("stock", n - 1);
    Right
    const item = env.STOCK.get(env.STOCK.idFromName(id));const ok = await item.take(1);   // Durable Object
  • Work that nobody awaits

    major

    It may be cancelled when the request ends.

    Wrong
    env.LOG.send(entry);return page;
    Right
    ctx.waitUntil(env.LOG.send(entry));return page;
  • Whole body in memory

    major

    128 MB is shared by all requests of the isolate.

    Wrong
    const all = await response.arrayBuffer();return new Response(all);
    Right
    return 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.