skip to content

SQLite State & Alarms

Each SQLite-backed Durable Object owns a private database written transactionally, plus an alarm to wake it later. Interviewers ask what blockConcurrencyWhile guards and how alarms retry.

on this pageshow

explore

questions

6

In a Cloudflare Durable Object, how do you persist state through ctx.storage, and why is a class field not enough?

level: juniorimportance: must knowfreq 60%

answer

  1. private storage per instance
  2. fields live only in memory
  3. put, get, delete, list
  4. synchronous twins on ctx.storage.kv
  5. eviction, crash and deploy restart

basics

~20 s

A 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 s

Every 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 lines
javascript
import { 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

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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.
open as a page

In a Cloudflare Durable Object, what does ctx.blockConcurrencyWhile() guard, and why call it in the constructor rather than around every request?

level: middleimportance: must knowfreq 50%

basics

~20 s

ctx.blockConcurrencyWhile(callback) stops every other event reaching the object until the async callback settles, even across awaits. That suits one-time setup in the constructor, such as creating tables; wrapping each request serialises all traffic and caps throughput.

open as a page

A Durable Object releases 15-minute ticket holds from its alarm() handler, yet some holds were released twice and others never; how do setAlarm() and alarm retries explain it?

level: seniorimportance: must knowfreq 45%

basics

~20 s

Each Durable Object has a single alarm, so a setAlarm() per hold overwrites earlier wake-ups. alarm() runs at least once and retries a throw only 6 times with backoff, so the handler must be idempotent and reschedule itself.

open as a page

With a SQLite-backed Durable Object, how do you run a parameterised query through ctx.storage.sql.exec(), and what does its cursor give you?

level: middleimportance: should knowfreq 50%

basics

~10 s

ctx.storage.sql.exec(query, ...bindings) runs SQL synchronously, fills each ? placeholder from the extra arguments, and returns a SqlStorageCursor you iterate or read with toArray(), one() or raw(), plus rowsRead and rowsWritten counts.

open as a page

In Wrangler 4, how do you declare a new SQLite-backed Durable Object class, and why can't an existing class change its storage backend?

level: middleimportance: should knowfreq 35%

basics

~20 s

Bind the class under durable_objects.bindings and declare it in the exports map with "type": "durable-object" and "storage": "sqlite"; older Workers use a migrations entry with new_sqlite_classes. The backend is fixed when the namespace is first created.

open as a page

A ticket-reservation Durable Object oversold seats after an await was added between its availability check and its insert; why, and how do implicit transactions and transactionSync() fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The await let other bookings run their own availability checks before any insert landed, so all saw free seats. Keep check and insert synchronous, ideally in ctx.storage.transactionSync(); the output gate holds the reply until the write is durable.

open as a page