In a Cloudflare Durable Object, how do you persist state through ctx.storage, and why is a class field not enough?
answer
- private storage per instance
- fields live only in memory
- put, get, delete, list
- synchronous twins on ctx.storage.kv
- eviction, crash and deploy restart
basics
~20 sA Durable Object persists state by writing to its private ctx.storage, with put() and get() for key-value pairs or ctx.storage.sql.exec() for tables. Class fields live only in memory and are lost when the object is evicted, reset or redeployed.
solid answer
~40 sEvery Durable Object instance gets its own storage through `ctx.storage`, and no other object can read it. On a SQLite-backed class, the backend Cloudflare recommends for every new class, you can call the key-value methods (`await ctx.storage.put(key, value)`, `get()`, `delete()`, `list()`) or their synchronous versions on `ctx.storage.kv`, or run SQL with `ctx.storage.sql.exec()`. Both land in the same embedded SQLite database, and a value can be anything the structured clone algorithm copies, not just a string. A class field such as `this.seatsLeft` is only a cache. An idle object is evicted, an uncaught exception resets it, and a deploy restarts it; each time the constructor runs again with empty fields. So write the truth to storage first and treat fields as a copy you can rebuild.
code
javascript · 29 linesimport { DurableObject } from "cloudflare:workers";
export class TicketEvent extends DurableObject {
async setCapacity(seats) {
await this.ctx.storage.put("capacity", seats);
}
async capacity() {
return (await this.ctx.storage.get("capacity")) ?? 0;
}
capacitySync() {
return this.ctx.storage.kv.get("capacity") ?? 0;
}
}
export default {
async fetch(request, env) {
const url = new URL(request.url);
const stub = env.TICKETS.getByName(url.searchParams.get("event") ?? "gig-1");
if (request.method === "PUT") {
await stub.setCapacity(Number(url.searchParams.get("seats")));
}
return Response.json({
capacity: await stub.capacity(),
sync: await stub.capacitySync(),
});
},
};go deeper
Recall that each Durable Object has private storage on ctx.storage, name put, get, delete and list, and explain why a class field disappears after eviction or a deploy.
Explain the async methods versus the synchronous ctx.storage.kv and sql.exec on SQLite-backed classes, structured-clone values, and why you write to storage before updating a cached field.
Show you plan for restarts: what is durable versus cached, how state is rebuilt in the constructor, list() with a prefix on large objects, and handling SQLITE_FULL at the 10 GB per-object limit.
Frame storage as part of the object's contract: which data an object owns, how large one object may grow before the design needs more objects, and how teams clean up finished objects with deleteAll().
## What a Durable Object's storage is A **Durable Object** is an instance of a JavaScript class that Cloudflare runs in exactly one place at a time, with its own **attached storage**. The storage is reached through `ctx.storage`, where `ctx` is the `DurableObjectState` passed to the constructor (and kept as `this.ctx` by the `DurableObject` base class from `cloudflare:workers`). That storage is: - **private** to the one instance: another object of the same class has its own, and nothing outside the object can query it; - **transactional and strongly consistent**: a read after a write in the same object always sees the write; - **durable**: it is written to disk and survives the object leaving memory. Cloudflare recommends the **SQLite storage backend** for every new class, so each object carries a small embedded SQLite database. Older namespaces may still use the legacy key-value backend, which offers the asynchronous key-value methods and alarms but no SQL. ## Two ways into the same storage | API | Call style | Available on | | --- | --- | --- | | `ctx.storage.get()`, `put()`, `delete()`, `list()` | asynchronous, returns a Promise | SQLite-backed and legacy key-value-backed classes | | `ctx.storage.kv.get()`, `put()`, `delete()`, `list()` | synchronous, no Promise | SQLite-backed classes only | | `ctx.storage.sql.exec()` | synchronous SQL with `?` bindings | SQLite-backed classes only | On a SQLite-backed object the key-value methods are stored inside the same database as your tables, so a key written with `ctx.storage.put("capacity", 250)` can be read back with `ctx.storage.kv.get("capacity")`. Values go through the **structured clone algorithm**, so numbers, objects, arrays, `Date`s and `ArrayBuffer`s round-trip without hand-written serialisation. ## Why a class field is not storage A field on the class (`this.seatsLeft = 100`) lives in the isolate's memory. It survives between requests only while the object stays loaded, and several ordinary events end that: - **eviction**: an object with no traffic is removed from memory after a while; - **an uncaught exception** that resets the object; - **a deploy** of new Worker code, which restarts running objects; - a machine failure that moves the object elsewhere. Each time, the next request runs the constructor again and every field starts from its initial value. If a ticket-reservation object kept its seat count only in a field, a routine deploy would hand out the whole venue a second time. The rule is: **write to storage first, then update any in-memory copy**, so a crash between the two leaves the durable copy correct. ## A ticket-reservation example For an object that represents one event, the capacity is a single value, so the key-value methods are the natural fit: `setCapacity(n)` calls `await this.ctx.storage.put("capacity", n)`, and `capacity()` returns `(await this.ctx.storage.get("capacity")) ?? 0`. The `?? 0` matters because `get()` returns `undefined` for a key that was never written. The seat holds themselves, with a seat, a user and an expiry each, are better as rows in a table queried with `ctx.storage.sql.exec()`, the subject of the SQL material in this lesson. ## Choosing key-value calls or SQL Both shapes share one database and one transaction model, so the choice is about the data: - **single values and small settings** (capacity, an event's opening time, a feature switch) read best as key-value pairs; - **collections you filter, sort or count** (holds, bookings, a waiting list) belong in tables queried with `sql.exec()`; - the key-value pairs live in a hidden internal table that you may see when listing tables but cannot read through the SQL API, so do not plan to join against them; - mixing both in one object is normal, and both kinds of data are covered by the object's point-in-time recovery. ## Limits and housekeeping - On a SQLite-backed object a key and its value together may not exceed **2 MB**. - The asynchronous `get()`, `put()` and `delete()` accept up to **128 keys** in one call. - One SQLite-backed object may hold up to **10 GB** on the Workers Paid plan; beyond that, writes fail with `database or disk is full: SQLITE_FULL` while reads and deletes keep working. - An object whose storage is empty when it shuts down simply ceases to exist. Once it has written anything, including an alarm, remove it with `ctx.storage.deleteAll()`; deleting individual keys or dropping tables can leave metadata behind. ## Habits that keep state safe 1. Decide what must survive a restart and keep exactly that in `ctx.storage`. 2. Load it lazily or in the constructor, and keep fields as a rebuildable cache. 3. Never assume a field still holds what the last request left there. 4. Use `list()` with `prefix` or `limit` on large objects, because a bare `list()` loads every pair into memory.
- On a SQLite-backed Durable Object, when would you pick ctx.storage.kv.get() over await ctx.storage.get()?Both read the same stored pair. `ctx.storage.kv.get()` returns the value directly, so there is no `await` and no point where the method yields. That fits code that also runs synchronous `ctx.storage.sql.exec()` calls, for example inside `ctx.storage.transactionSync()`. The asynchronous `get()` is the one that also exists on legacy key-value-backed classes.
- Does a Durable Object that never writes to storage keep existing after it shuts down?No. An object whose storage is empty when it shuts down ceases to exist, and the next call to the same name starts a fresh, empty instance. Once an object has written anything, including setting an alarm, it persists until you clear it with `ctx.storage.deleteAll()`, which also stops it being billed for storage.
- What happens when a SQLite-backed Durable Object hits its storage limit?At the per-object limit (10 GB on Workers Paid), writes through `put()` or `ctx.storage.sql.exec()` throw `database or disk is full: SQLITE_FULL`. Reads such as `get()`, `list()` and `SELECT` still work, and `DELETE` statements still succeed, so the object can free space. Catch the error and answer the caller instead of failing silently.
- A Durable Object's class fields persist between requests indefinitely, so storage is optional.
- Every object of one Durable Object class shares a single storage database.
- ctx.storage values must be strings, as in Workers KV.
- ctx.storage.kv is a binding to a Workers KV namespace.
- Deleting each key one by one fully removes a Durable Object's storage.