Unofficial · Cloudflare Durable Objects

A Durable Object is a globally addressable unit of compute with its own storage (CORE-01).

How to read this page: every section has an interactive widget you can play, step, or reset; use the sound toggle in the header if you want audio; orange simplified badges mark where the animation simplifies reality.

Requests from many directions reach the same object; each arrival is a stub.get() style hop (ADDR-09).

01

Core idea

Cloudflare Workers are stateless: a request is handled and the isolate moves on. KV holds data, but updates are eventually consistent across the planet (CMP-01). That is fine for caches, not for counters or rooms that need one serial order.

A Durable Object is compute, storage, and an ID in one bundle (CORE-01). Only one instance with a given ID runs at once, worldwide (CORE-05). It is single-threaded (CORE-04), so handlers see a single total order of storage (CMP-06).

The widget runs the same N increment requests twice: ten stateless Workers doing read-modify-write on a shared counter simplified, and one object that queues work through its input gate.

People sometimes say “a DO is a database.” It has storage, but it is active compute with an identity—not a passive SQL store like D1 (CMP-03, CMP-05).

Compare lost updates on a shared counter vs. a single object draining its queue.

Sources: CORE-01, CORE-03–05, CMP-01, CMP-03, CMP-05–06, ADDR-09, SIMP-02

02

Addressing

A namespace is the set of objects for one Worker class; your code reaches it through an env binding (ADDR-01, ADDR-02).

You name an object with idFromName, mint a random ID with newUniqueId, or rebuild one from a saved string with idFromString (ADDR-03–ADDR-07). get(id) and getByName(name) return a stub immediately (ADDR-09, ADDR-10, ADDR-11). They do not create the object—life starts when you call it (ADDR-08).

The widget shows a teaching hash of the name into a 64-digit hex ID simplified . Send from several regions: every request routes to the same marker for that name.

Type a name, see its ID, and send requests from different cities to one object.

Sources: ADDR-01–ADDR-11, SIMP-01

03

Placement

By default an object is created in a data centre close to the first get() (PLACE-01). It does not currently change location after that (PLACE-02). Callers far away pay extra latency (PLACE-03).

A location hint (locationHint) on the first get() nudges placement; it is best effort (PLACE-04, PLACE-05). Choose IDs and hints with real user regions in mind (PLACE-07).

A jurisdiction restricts where an object runs and stores its data, for example for GDPR or FedRAMP; Workers anywhere can still call it (PLACE-08). The recommended way to use one is a subnamespace, env.NS.jurisdiction("eu"), and the same name can map to different IDs in different jurisdictions (PLACE-10).

Durable Objects are not replicated to every edge PoP simplified . An instance can be replaced on another machine with storage intact (PLACE-12); this page says it “stays where it was created” and does not model relocation (SIMP-04).

Click the map or pick a region; arcs show one-way latency to the object’s home.

Sources: PLACE-01–PLACE-08, PLACE-10, PLACE-12, SIMP-02–SIMP-04

04

Gates

Each Durable Object runs one JavaScript request at a time, but await creates natural pause points. While one request waits on async work, another can run (CONC-01).

The input gate closes during await on the async storage API (ctx.storage.get / put): no new incoming events — including fetch() responses — are delivered until that storage work finishes (CONC-02, CONC-03). The gate does not cover a bare fetch() await; those waits still let other requests interleave (CONC-04).

The output gate holds outgoing responses (and other network messages) until in-flight writes are confirmed, so clients never see success for data that is not yet persisted (CONC-06, CONC-08). Synchronous SQLite calls (sql.exec, ctx.storage.kv) never yield, so they never interleave (CONC-12). Use blockConcurrencyWhile() when you need to block all delivery until a critical section finishes (CONC-13).

Cloudflare calls this trade-off Easy, Fast, Correct — choose three (CONC-10).

Step through two concurrent handlers: watch the input and output doors, and the highlighted await line.

Sources: CONC-01–CONC-04, CONC-06, CONC-08, CONC-10, CONC-12, CONC-13, SIMP-14

05

Storage

SQLite-backed Durable Objects run the database in the same thread as your code, so ctx.storage.sql.exec() can finish in microseconds (STOR-04, STOR-05). The synchronous KV API on ctx.storage.kv sits on a hidden SQLite table __cf_kv (STOR-07). Legacy key-value classes only expose the async get/put API — new work should use SQLite (STOR-01, STOR-02).

Storage keeps a small in-memory cache: a recent get() can return instantly (STOR-11). Ordinary JavaScript variables are not durable — they disappear when the object hibernates or is evicted, so persist what matters (STOR-12).

Write coalescing: several writes with no await between them are committed together (STOR-10). transactionSync(fn) runs a synchronous callback in one transaction; a throw rolls back (STOR-09). Point-in-time recovery (PITR) can restore the whole SQLite database — SQL and KV data — to a bookmark within the last 30 days (STOR-15, STOR-16).

Run presets to see cache hits vs disk reads, coalesced commits, SQL, eviction, and PITR restore.

Sources: STOR-01–02, STOR-04–07, STOR-09–12, STOR-15–16, SIMP-05–SIMP-06

06

RPC vs fetch

You reach an object through a stub. There are two ways to call it. With RPC, public methods on your class that extends DurableObject are called directly on the stub (RPC-02). Use it for projects with a compatibility date on or after 2024-04-03 (RPC-01). Every call is asynchronous for the caller, so you always await it, even if the method is synchronous (RPC-03).

With fetch, you send a Request with stub.fetch() and return a Response. The URL must be well-formed but doesn't need to resolve (RPC-07). Before RPC, people routed requests to private methods by URL path inside fetch(); RPC removes that manual parsing (RPC-08).

RPC accepts structured-cloneable values, functions, RpcTarget classes, streams, Request/Response and stubs, up to 32 MiB per call. Other application classes can't be passed (RPC-04, RPC-05).

Errors differ. An error thrown in an RPC method reaches the caller as a new error: the name, message and serializable own properties are kept, but instanceof and the original stack are not (RPC-06). With fetch nothing is thrown at the caller; you choose a status code and the caller checks res.ok.

Which to use? Use RPC by default. Use fetch() when you're stuck on an older compatibility date, or when you really do want to send a Request and return a Response (RPC-07).

Step through one call in each style, with and without a throw in the object. The code is real TypeScript, type-checked against the Workers types.

Sources: RPC-01–RPC-08

07

Lifecycle & billing

A Durable Object is in one of five documented states: Active, Idle, hibernateable, Idle, non-hibernateable, Hibernated and Inactive, which is where every object starts (LIFE-01). The first request or event, such as an alarm, runs the constructor and then the method (LIFE-02).

An idle object that can hibernate does so after 10 seconds without requests or events (LIFE-03). It can't if it has a pending setTimeout, unfinished I/O, an open outbound connection, a standard WebSocket, or a request in progress (LIFE-04). An idle object that can't hibernate is evicted to Inactive after 70–140 seconds simplified (LIFE-06).

What is kept? Hibernation removes the object from memory and discards its in-memory state; hibernatable WebSockets stay connected, and the next event runs the constructor again (LIFE-05). Anything you stored in storage survives. Ordinary variables don't, so persist what matters.

What is billed? Compute is billed as requests and duration, plus storage (BILL-01). Duration is wall-clock time while the object is active or idle but unable to hibernate. An idle object that is eligible to hibernate isn't billed for duration, even before it hibernates (BILL-02). Duration is charged for the 128 MB each object is allocated, whatever it uses (BILL-03). So duration isn't CPU time: CPU time is active processing only and excludes waiting on I/O (BILL-09), while duration is the wall clock. The meter below shows units, not dollars simplified.

Send a request, then fast-forward. Open a standard socket and watch the meter keep running while the object can't hibernate.

Sources: LIFE-01–LIFE-06, BILL-01–BILL-03, BILL-09, SIMP-07, SIMP-08, SIMP-12

08

WebSocket Hibernation

A Durable Object can be a WebSocket server, which is why chat rooms and multiplayer games fit it so well. There are two APIs: the Hibernation API, which is recommended, and the standard WebSocket API (WS-01).

With the standard API you call ws.accept() and the open socket keeps the object in memory, billed for duration for as long as it is connected (BILL-07, WS-09). With the Hibernation API you call ctx.acceptWebSocket(ws) instead. Messages arrive at webSocketMessage, disconnects at webSocketClose and errors at webSocketError; don't call ws.accept() (WS-02). One object can hold up to 32,768 hibernatable connections, and CPU or memory may limit it sooner (WS-03).

While hibernated, clients stay connected, in-memory state is reset, and the constructor runs when the next event arrives (WS-05). So keep anything per-connection in an attachment: ws.serializeAttachment(value) survives hibernation while the socket is open, up to 16,384 bytes. It is lost when either side closes, and deserializeAttachment() reads it back (WS-06).

Pings shouldn't wake an object. ctx.setWebSocketAutoResponse(pair) answers a fixed request with a fixed response without waking the object or billing duration (WS-07), and the runtime answers protocol ping frames itself (WS-08). Hibernation works only when the object is the WebSocket server; outgoing sockets don't hibernate, and neither do objects with alarms, requests or timers pending (WS-09).

Does an open socket keep my object billed? Only a standard one does. Hibernatable sockets let the object hibernate, so an idle room costs no duration. Incoming messages still count as requests, at 20 messages to one request (BILL-04); outgoing messages are free (BILL-06).

Connect users, send messages and fast-forward. Switch to standard sockets and the object never sleeps.

Sources: WS-01–WS-09, BILL-04, BILL-06, BILL-07, BILL-02

09

Alarms

An alarm lets an object wake itself up later. You call ctx.storage.setAlarm(time), and at that time the runtime calls your alarm() method. It is how you build batching, cleanup jobs and timeouts without a client to poke the object.

Each object has one alarm at a time; calling setAlarm() again replaces it (ALARM-01). getAlarm() returns the scheduled time or null, and deleteAlarm() unsets it (ALARM-05). For many schedules, keep them in storage and let alarm() process the due ones, then set the next alarm (ALARM-10). Only one alarm() runs at a time per object (ALARM-04), for up to 15 minutes of wall time (ALARM-12).

Alarms run usually within a few milliseconds of the set time, though maintenance or failover can delay them by up to a minute. A time in the past runs almost immediately (ALARM-06). An alarm wakes an inactive object, so the constructor runs before alarm() (ALARM-07).

Delivery is at-least-once. If alarm() throws, it is retried automatically with exponential backoff starting at 2 seconds, up to 6 retries, for the most recent setAlarm() only (ALARM-02, ALARM-03). The demo doubles the delay each time simplified. To retry beyond 6 attempts, catch errors and schedule a new alarm (ALARM-09). And because an unexpected error can make the handler run again from the beginning on another machine (ALARM-08), make alarm handlers idempotent (ALARM-11).

The handler charges a customer, then sends a receipt. Fail the receipt and turn idempotency on and off to see who gets charged twice.

Sources: ALARM-01–ALARM-12, SIMP-11

10

Patterns & sharding

Model your objects around your atom of coordination: a chat room, a user, a document, a tenant. One object per atom keeps each object small and gives you parallelism across atoms for free (LIMIT-04). The opposite, a single global object that every request hits, doesn't scale (LIMIT-05).

An object is single-threaded, so it has a ceiling. A soft limit of about 1,000 requests per second is a good rule of thumb, though what one actually sustains depends on the work per request (LIMIT-01). Beyond that, an object queues requests and then returns an overloaded error simplified (LIMIT-02).

When a single atom is hot, split it into shards named like room-42:shard-0, room-42:shard-1 and route each request by a hash of its key. Estimate the shard count as the peak requests per second for the atom divided by the target per shard, rounded up, then load-test (LIMIT-03). A coordinator object can fan work out to the shards and gather the results.

The trade-off: anything that needs a view across shards, such as a total count or a cross-shard read, now has to ask every shard. Shard only when you must.

Press Play and raise the load. A hot object's queue fills and turns red; add shards to calm it down, or switch patterns to compare.

Sources: LIMIT-01–LIMIT-05, ERR-07, SIMP-10

11

DO vs KV vs D1 vs R2

Cloudflare has several places to keep data, and Durable Objects are only one. Each is built for a different job.

  • Durable Objects suit real-time collaboration, per-user or per-tenant databases with logic, and strongly consistent coordination such as bookings and rate limits (CMP-05). Their storage is strictly serializable, which gives a global order of requests and storage operations (CMP-06).
  • Workers KV is an eventually consistent key-value store cached across the network: a change can take 60 seconds or more to show up elsewhere (CMP-01). It suits frequently read, rarely written data such as config and sessions (CMP-02).
  • D1 is a serverless SQL database with SQLite semantics, for relational data and ad-hoc queries, best for read-heavy workloads (CMP-03).
  • R2 is S3-compatible object storage with no egress fees, for large objects, with strong consistency per object (CMP-04).
How Durable Objects, KV, D1 and R2 compare
Durable Objects KV D1 R2
Consistency Strictly serializable (CMP-06) Eventually consistent; 60 s or more (CMP-01) SQLite semantics (CMP-03) Strong, per object (CMP-04)
Latency profile Runs in one place; far callers pay extra (PLACE-02, PLACE-03) Hot keys read in 500 µs–10 ms (CMP-02) Best for read-heavy workloads (CMP-03) Not covered here
Query model SQL or key-value API inside the object (STOR-05) Key-value SQL and ad-hoc queries (CMP-03) S3-compatible object API (CMP-04)
Size profile 10 GB per object on Paid (STOR-17) Config and sessions; 1 write per second per key (CMP-02) Up to 10 GB per database (CMP-03) Large objects (CMP-04)
Best fit Coordination, collaboration, per-tenant logic (CMP-05) Frequently read, rarely written data (CMP-02) Relational data, read-heavy (CMP-03) Large blobs (CMP-04)
Answer the questions. Several answers can apply, so the result may combine products.

Sources: CMP-01–CMP-06, STOR-05, STOR-17, PLACE-02, PLACE-03

12

Classes & failures

Class lifecycle

In your Wrangler config, exports are the declarative way to create, delete, rename and transfer Durable Object classes: the exports field replaces the migrations array, and a Worker uses one or the other (MIG-01). Each entry's state selects the operation: created (the default), deleted, renamed with renamed_to, transferred with transferred_to, or expecting-transfer (MIG-02). Live entries declare storage: "sqlite" for new namespaces; "legacy-kv" is only for existing KV namespaces, and a backend can't change (MIG-03).

{
  "durable_objects": {
    "bindings": [{ "name": "ROOM", "class_name": "ChatRoom" }]
  },
  "exports": {
    // A live class
    "ChatRoom": { "type": "durable-object", "storage": "sqlite" },
    // Renaming moves the data to another class in the same Worker
    "OldRoom": { "type": "durable-object", "state": "renamed", "renamed_to": "ChatRoom" },
    // Deleting removes the namespace and all its data
    "Scratch": { "type": "durable-object", "state": "deleted" }
  }
}

Deleting a class removes its namespace and all stored data permanently (MIG-04). These changes apply only through wrangler deploy; gradual deployments aren't supported for them, and rollbacks can't cross them (MIG-05). The legacy migrations flow, an array of entries with a tag and keys such as new_sqlite_classes, is still fully supported for existing Workers (MIG-06).

When things go wrong

Some events definitely reset an object: a blockConcurrencyWhile callback that throws or runs past its 30 s timeout (CONC-14), a failed storage write behind the output gate (CONC-06), ctx.abort() (ERR-11) and a code update (DEPLOY-01, ERR-12). An ordinary uncaught exception is different: it can leave the object in an unknown state and may cause the runtime to terminate it (ERR-06).

Uncaught exceptions, including infrastructure errors such as overloads, propagate to the caller (ERR-01). Look at the flags: .retryable means transient, so retry only idempotent requests, with backoff (ERR-02); .overloaded means don't retry, since that makes things worse (ERR-03); .remote means the error came from your Durable Object code (ERR-04). Many exceptions leave the stub broken, so create a new one (ERR-05).

The runtime retries a stub call automatically only when the request never reached the object or delivery is unknown, never for errors from your code or overloads (ERR-08). A method runs twice because of a retry only if you mark it with retryable() (ERR-09), and get(id, { retry }) sets per-stub limits (ERR-10). The default code update strategy is deferred: an active object keeps its code until it hibernates or max_delay passes; immediate resets it right away (DEPLOY-01).

Trigger each failure and compare what survives and what the caller sees.

Sources: MIG-01–MIG-06, CONC-06, CONC-14, ERR-01–ERR-11, DEPLOY-01, ERR-12, LIFE-10

13

Playground

Everything from the earlier sections, in one world. Each object has a home chosen by placement, handles one request at a time (gates), keeps rows in storage, moves through the lifecycle, holds WebSockets and can set an alarm. It is the same simulation code as the widgets above, running on a virtual clock.

Try a few experiments:

  • Load Chat room, press +10 s, then send a message: the room wakes from hibernation but keeps its sockets.
  • Load Hot object and compare how long responses take from Sydney and from Ashburn.
  • Load Flaky alarm and fast-forward: the failures back off before the retry succeeds.
  • Open a standard socket and watch the billing meter keep running while the object is idle.
  • Press Share to get a link. Opening it replays your commands and restores the same world.
Click an object on the map, or pick it from the list, to inspect it. Every command works from the keyboard.

Sources: the facts cited in sections 03–09

14

Glossary

Short definitions of the terms used on this page. Each term links here the first time it appears in a section.

Namespace
The set of Durable Objects backed by one class. There is one namespace per class, and it can hold any number of objects (ADDR-01, CORE-09).
Binding
How Worker code reaches a namespace: a name on env, declared under durable_objects.bindings in the Wrangler config (ADDR-02).
ID
The identity of one object: a 64-digit hexadecimal number. idFromName(name) derives one from a name; newUniqueId() makes a random one (ADDR-03, ADDR-04, ADDR-07).
Stub
A client object that refers to one Durable Object and lets you call it with RPC methods or fetch. Creating a stub doesn't create the object (ADDR-11, ADDR-08).
Instance
One running copy of an object. Only one instance of a class with a given ID runs at once, worldwide (CORE-05).
Input gate
While a storage operation runs, no events are delivered except storage completions; other events wait. It protects the object from interleaving during storage I/O, not during other awaits such as fetch() (CONC-02, CONC-04).
Output gate
While a storage write is in progress, new outgoing network messages are held until the write completes. If it fails, they are replaced with errors and the object restarts (CONC-06).
Write coalescing
Writes with no await between them are committed together, atomically (STOR-10).
Transaction
An all-or-nothing unit of storage work. transactionSync(fn) runs a synchronous callback in a transaction and rolls back if it throws (STOR-09).
PITR
Point-in-time recovery: restores an object's whole SQLite database, SQL and key-value data, to any point in the last 30 days (STOR-15).
Hibernation
An idle object that meets the conditions is removed from memory after 10 seconds without events. Its in-memory state is discarded, hibernatable WebSockets stay connected, and the next event runs the constructor again (LIFE-03, LIFE-05).
Eviction
An idle object that can't hibernate is evicted to Inactive after 70–140 seconds without requests or events (LIFE-06).
Inactive
The initial state of every object: not running. The first request or event runs the constructor (LIFE-01, LIFE-02).
Alarm
A timer that wakes an object at a set time to run its alarm() method. An object has one at a time, and delivery is at-least-once (ALARM-01, ALARM-02).
Bookmark
A marker for a point in an object's history, used by PITR. getCurrentBookmark() and getBookmarkForTime(t) return one, and restoring it brings back that state (STOR-16).
Code update strategy
How a new Worker version reaches running objects. deferred (the default) lets an active object keep its code until it hibernates or max_delay passes; immediate resets it right away (DEPLOY-01).
Location hint
A locationHint on the first get() that asks where to create the object. Best effort, and only the first call respects it (PLACE-04).
Jurisdiction
A restriction on where an object runs and stores data, for GDPR or FedRAMP. Workers anywhere can still call it (PLACE-08).
Shard
One of several objects that split the load of a single hot atom. Estimate the count as peak requests per second divided by the target per shard, rounded up, then load-test (LIMIT-03).
RPC
Calling public methods of your class directly on the stub, as if they were local. Every call is asynchronous and must be awaited (RPC-02, RPC-03).
Exports
The Wrangler config field that declaratively creates, deletes, renames and transfers Durable Object classes. It replaces the migrations array (MIG-01).
Migration (legacy)
An entry in the legacy migrations array, with a tag and keys such as new_sqlite_classes. Still supported for existing Workers (MIG-06).

Sources: ADDR-01–ADDR-11, CORE-05, CORE-09, CONC-02, CONC-04, CONC-06, STOR-09, STOR-10, STOR-15, STOR-16, LIFE-01–LIFE-06, ALARM-01, ALARM-02, DEPLOY-01, PLACE-04, PLACE-08, LIMIT-03, RPC-02, RPC-03, MIG-01, MIG-06