Diffinery

homeflare/celldpublic

celld/docs/services/durable-objects.md
180 lines · 10.4 KBRaw History
1# Durable Objects / Cells
2
3A Durable Object is a single-threaded actor with durable storage, and celld
4calls each running Durable Object a cell. An application uses one when a piece
5of state needs a single consistent owner, such as a chat room, a game match, a
6shopping cart, an agent session, or a rate limiter. The state lives in a SQLite
7database that belongs to that object alone, on the node that serves it, and
8celld replicates the database to the fleet. Read the
9[Cloudflare Durable Objects documentation](https://developers.cloudflare.com/durable-objects/)
10for the standard API behavior.
11
12## Example
13
14The [counter example](../../examples/counter) keeps a counter in the key-value
15storage of a Durable Object, and it uses `idFromName()` to give each name a
16separate counter.
17
18<!-- celld-example: counter -->
19
20## Identity and addressing
21
22A `durable_objects` binding exposes one class as a namespace, and an
23application reaches an object in two steps. `env.COUNTER.idFromName("room-7")`
24returns a `DurableObjectId`, and `env.COUNTER.get(id)` returns a
25`DurableObjectStub`. `getByName("room-7")` performs both steps together. The
26stub is only a handle, so celld creates the object at the first call and not at
27`get()`. Read the
28[Durable Object ID documentation](https://developers.cloudflare.com/durable-objects/api/id/)
29for the complete method list.
30
31`idFromName()` is deterministic. celld derives the id with HMAC-SHA-256 over
32the name, under a key that belongs to the namespace, so one name always gives
33the same 64-digit hexadecimal id. That id always reaches the same object, and
34two Workers on two different nodes that use one name therefore reach one
35object. The name also survives in `ctx.id.name` when it is 1024 UTF-8 bytes or
36less, which is the Cloudflare rule, and a longer name still routes to the
37correct object.
38
39`newUniqueId()` instead draws random bytes, so its object carries no name and
40no later caller can address it again. Keep the `toString()` form of such an id
41if the application must reach the object a second time. `idFromString()` parses
42that hexadecimal form and verifies the HMAC, therefore celld refuses an id that
43belongs to a different namespace instead of creating an unrelated object.
44
45celld builds the key of a namespace from the script name and the class name, so
46a rename of the Worker script changes every id that the namespace derives. The
47objects of the old name keep their storage under the old ids, and the renamed
48script reaches new and empty objects. Keep the script name stable, or migrate
49the data before the rename.
50
51celld implements no jurisdiction, because a celld fleet has only the machines
52that you run. `newUniqueId({ jurisdiction })` and `namespace.jurisdiction()`
53throw an error, so an application learns about the gap at the call site.
54
55## Ownership and the single-threaded model
56
57Cloudflare creates an object near the first request that uses it, and
58Cloudflare can migrate the object afterwards. celld makes no placement,
59migration, or jurisdiction promise, and it makes one narrower promise instead:
60exactly one node serves a cell at a time.
61
62A node claims a cell by writing an ownership record into the fleet bucket with
63a conditional write. The object store accepts only one of two competing
64writers, so two nodes cannot own one cell. Every activation advances a fencing
65epoch, and the epoch appears in the storage prefix, therefore a node that lost
66the cell writes only into a superseded prefix. The
67[guarantees](../guarantees.md) page gives the full mechanism.
68
69A Worker holds its stub on whichever node served the request. celld resolves
70the owner of the cell and forwards the call to that node, so the object code
71runs on the owner and nowhere else. Inside the cell, one synchronous turn runs
72at a time. An event that awaits can overlap another event unless
73`blockConcurrencyWhile()` closes the input gate. celld also
74holds a response until a durability proof covers every write that the response
75can reveal, which is the behavior Cloudflare calls the
76[output gate](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/).
77An application therefore does not have to `await` a `put()`, because a client
78cannot receive the response before the write survives a failure. The same gate
79holds a WebSocket frame, and it holds each frame only for its own proof.
80Therefore a `webSocketMessage()` handler that sends a frame and then awaits
81delivers that frame while it still runs, and an application can stream an
82answer through one handler.
83On one socket, celld starts the message handlers in arrival order, but it does
84not wait for a handler to finish before starting the next handler. Therefore
85an incoming message can cancel work that an earlier handler awaits.
86A hibernatable socket delivers the frames in send order across WebSocket
87handlers and RPC methods, even when the output gate delays an earlier frame.
88
89![Two Workers on different nodes address the name room-7, the owner record in the fleet bucket names one owner node, celld forwards both calls to that node, and the cell replicates through a follower node into an epoch-fenced bucket prefix](durable-objects-flow.svg)
90
91A cell keeps no in-memory state across an eviction. celld removes an idle cell
92from memory, and the cell then hibernates on its node or becomes inactive in
93the bucket, so the constructor runs again at the next event. Ownership can move
94as well, because a node can stop, a node can drain, and idle rebalancing can
95move a hibernated cell to another node. A reader must therefore treat only
96durable storage as persistent. A hibernatable WebSocket survives a hibernation
97on the same node, and it closes when the cell moves to a new owner, so a client
98must reconnect. Cloudflare gives the same rule for
99[in-memory state](https://developers.cloudflare.com/durable-objects/reference/in-memory-state/).
100
101## Durable storage and alarms
102
103`ctx.storage` gives each object its own SQLite database. A class that a
104`new_sqlite_classes` migration declares can use the key-value methods `get()`,
105`put()`, `delete()`, `list()`, and `deleteAll()`, and it can also run SQL
106through `ctx.storage.sql.exec()`. `transaction()` and `transactionSync()` group
107several writes, and `storage.sync()` waits for the durability of the earlier
108committed writes. The `transactionSync()` callback receives no argument, as in
109workerd. Therefore, it writes through `ctx.storage`, and a throw rolls the
110transaction back. A callback can start another transaction, through the
111transaction object or through `ctx.storage` itself, and celld nests the new
112transaction inside the open one. A nested transaction that fails discards only
113its own writes, therefore the enclosing transaction can continue and commit.
114Read the
115[storage documentation](https://developers.cloudflare.com/durable-objects/best-practices/access-durable-objects-storage/)
116for the method signatures.
117
118The synchronous `ctx.storage.kv.list()` iterator reads one entry per step and
119releases its read statement before the step returns. An unfinished iterator
120therefore does not block later writes after a replication checkpoint. Each
121step resumes after the last returned key in the selected direction. A later
122step can observe a change to an entry that the iterator has not returned.
123A new call to `kv.list()` invalidates the previous iterator for that object.
124
125The durability of that database comes from the fleet, not from a managed
126service. celld captures each write as an LTX segment and replicates the segment
127to `cells/<cell>/ltx/e<epoch>/` in the fleet bucket. A fleet of two or more
128nodes is faster, because the owner also sends each write to one or two follower
129nodes and answers as soon as a follower holds the write on its own disk. The
130bucket upload follows afterwards. A single node has no follower, so every write
131on it waits for the object store instead.
132
133`storage.setAlarm()` schedules one alarm per object, `getAlarm()` reads it, and
134`deleteAlarm()` removes it. celld calls the `alarm(alarmInfo)` handler at the
135scheduled time and passes `retryCount` and `isRetry`, as the
136[Alarms API](https://developers.cloudflare.com/durable-objects/api/alarms/)
137describes. celld does not answer a successful response until a durable wake
138entry in the bucket covers the alarm, so a crash cannot lose a schedule that a
139client already saw. A hibernated cell fires its alarm on the node that owns it.
140One node in the fleet holds the waker role, and it wakes only a cell whose
141owner node stopped, so the alarm work of the fleet does not queue on one
142machine.
143
144## Differences from Cloudflare
145
146- celld makes no placement, migration, or jurisdiction promise. A cell runs on
147 a node of your fleet, and `newUniqueId({ jurisdiction })` and
148 `namespace.jurisdiction()` throw.
149- The key of a namespace contains the script name, so a rename of the script
150 changes every id that `idFromName()` derives.
151- A `migrations` entry accepts `tag` and `new_sqlite_classes` only. A class
152 rename, a class delete, and a class transfer stop the deployment.
153- A Durable Object event keeps pending I/O active after the handler returns, so
154 a timer or a subrequest does not require `ctx.waitUntil()`.
155- The imported `waitUntil()` and `ctx.waitUntil()` can add work while previously
156 registered background work remains active.
157- An RPC stub cannot cross an isolate boundary. See
158 [RPC](../cloudflare-compat.md#rpc).
159- An outbound WebSocket does not continue after the object moves to another
160 node.
161- `SqlStorage.Cursor.toArray()` gives a celld-specific error near the V8 heap
162 limit.
163- `storage.sync()` waits for the object store or the fleet ensemble to hold all
164 earlier committed writes. The operation uses the shorter of the 10-second
165 `CELLD_LTX_DURABILITY_TIMEOUT_SECS` default and the 15-second
166 `CELLD_OPERATION_DEADLINE_MS` default.
167- `storage.sync()` rejects during an open transaction and after an object abort.
168 Without an object store, it resolves after the local commit.
169- A transaction and `blockConcurrencyWhile()` have a 30-second limit. A timeout
170 resets the object and rolls back an open transaction.
171- A failed handler still waits for the durability of any value or write that it
172 can expose. A celld-generated failure that exposes no object value returns
173 immediately.
174- Outside an explicit transaction, a SQL write cursor must finish before a
175 response, an outbound effect, or `storage.sync()`. An unfinished `RETURNING`
176 cursor holds uncommitted writes, so celld rejects that output with an error.
177 A read cursor can remain open.
178
179The [Cloudflare compatibility](../cloudflare-compat.md#services) page
180lists the runtime APIs and the unsupported services.