Skip to the workspace
Pebellslearn by building
Durable Objects  ›  Capstone Project

Transactional Operations — All of It or None of It

Transactional Operations 15 minDurable Object storage calls hold other requests out through input gates while outside awaits let them in, and transactions make a group of changes succeed or fail together.

cloudflare / Transactional Operations — All of It or None of It

Explore each scene at your own pace.

01 · The rule

The rule

Transactional Operations — All of It or None of It

Hoplink gives each free user 50 links. Creating a link inside the user's Durable Object does two things: add the link and decrease the remaining allowance. If the first succeeds and the second fails, the user gets a free link. If two creations interleave, both might see "1 left" and both succeed. Transactions and the object's built-in gates stop both problems.

The rule

Storage calls hold the door; an outside await opens it.

A Durable Object runs one event at a time, but an async method can pause at an await. What happens during that pause decides whether your code is safe:

  • Input gate. While the object is waiting on its own storage (get, put, sql.exec), no other request is let in. So a read followed by a write, with only storage calls between them, cannot be interrupted.
  • Output gate. Anything the object sends out — a response, a WebSocket message — is held back until the writes before it are safely stored. Nobody hears "done" about a write that could still be lost.
  • The open door. Awaiting something outside storage, such as fetch() to another service, lets other requests run in the meantime. State you read before that await may be stale afterwards.

For changes that must succeed or fail together, wrap them in a transaction:

async createLink(code, url) {
  return this.ctx.storage.transactionSync(() => {
    const [{ remaining }] = this.ctx.storage.sql
      .exec("SELECT remaining FROM quota").toArray();
    if (remaining <= 0) throw new Error("No links left");
    this.ctx.storage.sql.exec("INSERT INTO links (code, url) VALUES (?, ?)", code, url);
    this.ctx.storage.sql.exec("UPDATE quota SET remaining = remaining - 1");
    return remaining - 1;
  });
}

If anything inside throws, every change in the block is rolled back. (transactionSync is for SQLite-backed objects; the key-value API offers ctx.storage.transaction(async (txn) => ...).)

When an object starts and must load or prepare state before handling anything, ctx.blockConcurrencyWhile(async () => { ... }) in the constructor keeps every request waiting until setup finishes.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.