Cloudflare Durable Objects explained with a restaurant

Claude Chat anonymous·5d ago #cloudflare #architecture #learning
Open in Claude Open in ChatGPT
U
You

I understand Workers (stateless functions at the edge). I do not understand Durable Objects. Every explanation says "single-threaded coordination point" and my brain slides off it. Try an analogy.

C
Claude

Workers are a chain of fast-food counters: thousands of identical staff, anywhere in the world, each takes one order and forgets you instantly. Great for “give me a burger” (an HTTP request). Terrible for “we’re a table of six and we want to split the bill” — no counter remembers who ordered what, and two counters might both decide they’re handling table six.

A Durable Object is one named table with one dedicated waiter.

  • Named: you ask for “table six” (idFromName('table-6')) and you always get the same one, from anywhere in the world. There is exactly one “table six”; if two customers ask for it at once, they get the same waiter.
  • One waiter: he handles requests for that table one at a time. That’s the “single-threaded” bit — not a limitation, the whole point. Nobody can double-book table six, because only he writes on its notepad.
  • Durable: his notepad (storage) survives even if the restaurant closes for the night (the object is evicted from memory) — next morning, same table, same notepad.
  • Fast: the waiter stands next to the table. Every request for the table goes to him, so a chat room, a game lobby, a document being edited, a rate-limit counter — anything where “who did what, in what order” matters — has one place where that order is decided.

What it is not: a database for everything. You don’t make one Durable Object for the whole restaurant; you make one per table, per document, per room. Millions of tiny waiters, each remembering one thing perfectly.

The pattern in code: a Worker receives the request (fast-food counter), works out which table it belongs to, and forwards it: env.ROOMS.get(env.ROOMS.idFromName(roomId)).fetch(request). The Worker stays dumb; the Durable Object holds the state and the WebSocket connections for that room.

U
You

So a rate limiter per user would be one object per user?

C
Claude

Yes — idFromName(userId). Each object keeps a tiny counter and a window in memory (and optionally in storage), and because only one waiter touches it, you can never over-count due to two Workers racing. The cost is one extra hop per request, which is why for coarse limits people sometimes use KV or a D1 upsert instead; for “exactly N per minute, no cheating” the object is the right tool.

Comments (0)

No comments yet.

Sign in to comment.

Report this post