// Stack

Durable Objects

Last updated ·

Durable Objects are a special kind of Cloudflare Worker: each object is a single, globally addressable instance of a class with its own strongly consistent storage. EOXLABS uses a Durable Object wherever several clients must agree on one piece of state: an upload session, a conversation, a rate-limit window or a live WebSocket room.

What does a Durable Object guarantee?

Cloudflare's storage options guide states the core property: only one instance of a Durable Object with a given ID runs at once, anywhere in the world, and requests for that ID are routed to it. The instance runs one event at a time. Its storage is private; no other object can read it.

Three runtime mechanisms make that model safe to program against, and Cloudflare's rules of Durable Objects describes each:

  • Input gates stop new events from being delivered while a storage operation is in flight.
  • Output gates hold a response until the writes made before it are persisted, so a client is never told a write succeeded before it is safely stored.
  • Write coalescing commits several writes made without an intervening await as one atomic transaction.

The gap matters as much as the guarantee. Input gates protect storage operations only. A fetch() to another service or a write to R2 lets other requests interleave, so EOXLABS re-reads state after any external await before acting on it.

How does EOXLABS model Durable Objects?

The design question is always the same: what is the atom of coordination? EOXLABS gives each tenant, conversation, upload or device its own object, and never routes all traffic through one global object, which Cloudflare lists as an anti-pattern. CONDUIT, the EOXLABS edge file-transfer product, coordinates resumable, chunked uploads with Durable Objects. The sketch below shows the shape of that pattern, not product code:

import { DurableObject } from "cloudflare:workers";

export class UploadSession extends DurableObject<Env> {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    ctx.blockConcurrencyWhile(async () => {
      this.ctx.storage.sql.exec(
        "CREATE TABLE IF NOT EXISTS parts (n INTEGER PRIMARY KEY, etag TEXT NOT NULL)",
      );
    });
  }

  async recordPart(n: number, etag: string): Promise<number> {
    this.ctx.storage.sql.exec("INSERT OR REPLACE INTO parts (n, etag) VALUES (?, ?)", n, etag);
    // One alarm per object: each new part pushes the expiry an hour out.
    await this.ctx.storage.setAlarm(Date.now() + 60 * 60 * 1000);
    return this.ctx.storage.sql
      .exec<{ total: number }>("SELECT count(*) AS total FROM parts")
      .one().total;
  }

  async alarm(): Promise<void> {
    // Alarms run at least once, so cleanup must be safe to repeat.
    await this.ctx.storage.deleteAll();
  }
}

// In the calling Worker: const total = await env.UPLOADS.getByName(uploadId).recordPart(3, etag);

The conventions behind it:

  • Names versus unique IDs. getByName() suits entities whose ID the caller already knows. For a brand-new entity, newUniqueId() is faster on first use, because a name-derived ID needs a global uniqueness check that Cloudflare's namespace reference says can take up to a few hundred milliseconds.
  • RPC methods, not a fetch() handler, so calls are typed and the object exposes a narrow interface.
  • SQLite storage with migrations in the constructor, wrapped in blockConcurrencyWhile() so no request sees a half-migrated schema.
  • Alarms for deadlines. Each object holds one alarm; the Alarms API guarantees at-least-once execution and retries a failed handler with exponential backoff from 2 seconds, up to 6 times. Durable Object alarms in practice covers idempotent handlers in depth.
  • Hibernating WebSockets. Connections accepted with ctx.acceptWebSocket() stay open while the object leaves memory, and per-connection state travels in serializeAttachment(). Cloudflare's WebSocket guide notes that billable duration does not accrue during hibernation. The real-time inbox note and real-time voice build on this.

What limits and trade-offs come with Durable Objects?

PropertyValueDesign consequence
Storage per object10 GB on Workers Paid, 1 GB on Free (SQLite backend); 8 MB per row or key-value pairLarge files go to R2; the object keeps references
Throughput per objectSoft limit of 1,000 requests per second; excess requests queue, then fail as overloadedHot entities are sharded across several objects
Point-in-time recoveryAny point in the past 30 days, per objectA bad write can be rolled back without a separate backup system
LocationCreated near the first request and does not currently move; location hints are best effortObjects are created from real traffic, or with a hint
Jurisdictioneu, us or fedramp namespaces constrain where an object runs and stores dataUsed where residency rules apply; the same name in another jurisdiction is a different object

Where should coordination state live?

Durable ObjectD1Workers KV
Concurrent writersSerialized by the object's single threadSerialized by a single-threaded primary databaseLast write wins; 1 write per second per key
Read freshnessStrongly consistentSequentially consistent within a sessionEventually consistent; changes can take 60 seconds or more to appear elsewhere
Scale unitMany small objectsMany databases of up to 10 GBUnlimited keys per namespace
Best fitPer-entity coordination, timers, WebSocketsRelational queries across entitiesRead-mostly configuration

Each object's storage is visible only to that object, so cross-entity reporting needs a second store. EOXLABS writes per-entity state in the object and projects what must be queried across entities into D1. Read-heavy settings that tolerate delay are better served from the edge cache of Workers KV.

When not to use Durable Objects

  • Stateless request handling. A plain Worker avoids the routing hop to wherever the object lives.
  • One global object for everything. A single object that every request touches becomes the bottleneck at its throughput limit.
  • Queries across many entities. Reporting, search and analytics need D1 or Postgres; there is no SQL across objects.
  • One entity with more than 10 GB of data. That data belongs in R2 or a dedicated database.
  • Residency enforced by location hints. Hints are best effort. Only a jurisdiction-restricted namespace constrains where data is stored.

Durable Objects sit beside Cloudflare Workers in the EOXLABS stack. In telecommunications systems built around live sessions, EOXLABS starts the design from the session object.

→

Related

+

More stack

Have a system that can’t go dark?

Start a project →