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?
answer
- an await is a yield point
- each request checked a stale count
- no await means one transaction
- synchronous callback, rollback on throw
- replies wait for durable writes
basics
~20 sThe 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.
solid answer
~50 sA Durable Object runs one event at a time only between yield points. A storage call does not let other requests in, but awaiting a `fetch()` or a timer does, so with the new `await` concurrent bookings all read the same stale count, all saw free seats, and all inserted. The fix is to make the check and the write one synchronous stretch. Writes with no `await` between them are coalesced into a single **implicit transaction**, and `ctx.storage.transactionSync(() => { ... })` makes that explicit: it runs a synchronous callback, returns its value and rolls every statement back if it throws. Durability is handled by the **output gate**: the runtime holds the response until the transaction is on disk, and resets the object if the write fails. Anything slow, such as a payment call, goes after the hold is recorded, followed by a re-check, never inside `blockConcurrencyWhile()`.
code
javascript · 39 linesimport { DurableObject } from "cloudflare:workers";
const HOLD_MS = 15 * 60 * 1000;
export class TicketEvent extends DurableObject {
constructor(ctx, env) {
super(ctx, env);
ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS holds (
seat TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
expires_at INTEGER NOT NULL
)`);
}
hold(seat, userId, capacity) {
// No await inside: the check and the insert commit together or not at all
return this.ctx.storage.transactionSync(() => {
const { taken } = this.ctx.storage.sql
.exec("SELECT COUNT(*) AS taken FROM holds WHERE expires_at > ?", Date.now())
.one();
if (taken >= capacity) return { ok: false, reason: "sold out" };
this.ctx.storage.sql.exec(
"INSERT INTO holds (seat, user_id, expires_at) VALUES (?, ?, ?)",
seat, userId, Date.now() + HOLD_MS,
);
return { ok: true };
});
}
}
export default {
async fetch(request, env) {
const stub = env.TICKETS.getByName("gig-1");
const results = await Promise.all(
["A1", "A2", "A3", "A4", "A5"].map((seat, i) => stub.hold(seat, `u-${i}`, 3)),
);
return Response.json(results);
},
};go deeper
Recall that an await on a fetch or a timer lets another request run inside the same Durable Object, so a check and its write belong together without one.
Explain write coalescing into an implicit transaction, transactionSync() with its synchronous callback and rollback, and what the output gate holds back.
Diagnose the oversell from the yield point, then fix it with one synchronous transaction, a pending hold before external calls, and a check-and-set after them.
Set the team rule that money or inventory changes happen in one synchronous storage step, with external calls after it, and review any allowUnconfirmed or blockConcurrencyWhile() use.
## What the await changed A Durable Object processes one event at a time, but only **between yield points**. While a request is awaiting its own storage, the runtime keeps other events out. While it awaits anything else (a `fetch()`, a timer, another service), the next queued request may start. The original booking method read the seat count and inserted the hold in one synchronous stretch, so it was safe. The new version read the count, awaited something, then inserted. Under load: 1. request A reads "0 of 3 taken" and awaits; 2. requests B to F each start, read the same count, and await; 3. all six resume and insert, leaving six holds for three seats. Six concurrent calls against a three-seat object end with six holds when the await sits between check and insert, and with three when the two stay in one synchronous stretch. ## Implicit transactions and write coalescing The storage layer makes ordinary code transactional without ceremony: - every storage method is atomic and isolated on its own; - a series of writes with **no intervening `await`** is coalesced into one **implicit transaction** that commits as a unit, so a crash leaves all or none of them; - `ctx.storage.sql.exec()` is synchronous, so a read followed by a conditional write is already one uninterrupted, atomic step. On the legacy key-value backend the same idea holds for the async methods, but awaiting each `get()` and `put()` breaks coalescing into separate commits. ## transactionSync() `ctx.storage.transactionSync(callback)` is available on SQLite-backed objects: - it runs `callback` inside a transaction and returns the callback's result; - if `callback` throws, every statement it ran is rolled back and the error propagates to the caller; - the callback must be **synchronous**: not `async`, no returned Promise, only synchronous storage calls such as `sql.exec()` and `ctx.storage.kv`. That makes the check-then-insert explicit and protects multi-statement work (insert the hold, decrement a counter, write an audit row) against a half-applied failure. The asynchronous `ctx.storage.transaction()` still exists, but its `txn` object is obsolete on SQLite-backed objects. Raw `BEGIN TRANSACTION` is refused by `exec()`. ## Output gates: the reply waits for the disk Writes are buffered and flushed asynchronously, so the method can return before the bytes hit disk. The **output gate** makes that safe: - outgoing messages (the response, an outgoing `fetch()`) are held until all earlier writes are confirmed durable; - if a write fails, the object is reset, held messages are discarded and callers receive errors; - so a client never sees "seat held" for a hold that was not stored. The async key-value `put()` and `delete()` accept `allowUnconfirmed: true` to opt out, with `ctx.storage.sync()` to wait for durability selectively. Reservation code should keep the default. ## Fixing the reservation flow 1. Do the availability check and the insert inside one `transactionSync()` callback with no `await`. 2. If a payment or other external call is needed, record the hold first (status `pending`), then call out. 3. After the call returns, re-read the hold and write the outcome only if it is still in the expected state (check-and-set). 4. Let the alarm that expires holds clean up any `pending` hold whose payment never finished. ## Reading the code example The example fires five holds at once against a capacity of three. Each call runs `hold()` inside `transactionSync()`: it counts holds whose `expires_at` is still in the future, so expired holds the alarm has not yet cleaned up do not block new ones, and inserts only if a seat is free. Because nothing in the callback awaits, the five calls run one after another, and the result is three `{ ok: true }` and two `sold out`. The `seat` column is the primary key, so a second hold on the same seat throws a constraint error; `transactionSync()` rolls that call back and the error reaches the calling Worker, which should map it to a "seat taken" reply. ## Fix options compared | Option | Prevents oversell? | Cost | | --- | --- | --- | | Check and insert in one synchronous stretch | Yes | None | | `transactionSync()` around it | Yes, plus rollback on throw | None | | `blockConcurrencyWhile()` around a `fetch()` | Yes | All traffic waits on the remote call | | `allowUnconfirmed` on writes | No; it only drops the output-gate guarantee | Clients may see unstored holds |
- Does the output gate mean every ctx.storage.sql.exec() write must be awaited before returning?No. `exec()` is synchronous and returns no Promise; the write is buffered. The output gate holds the outgoing response until that write is durable, and resets the object, failing the request, if it cannot be stored. Returning immediately after the write is the intended pattern.
- The booking must charge a card through an external API; how do you keep it from overselling?Split it at the yield point. Synchronously insert a `pending` hold, which reserves the seat, then await the payment call. When it returns, re-read the hold and mark it paid only if it is still `pending`; otherwise refund or report. The hold-expiry alarm releases any `pending` hold whose payment never finished, so a crash mid-call cannot leak seats.
- What does allowUnconfirmed: true on ctx.storage.put() change?It exempts that write from the output gate, so outgoing messages can leave before the write is confirmed on disk. If the write later fails, a client may already have been told it succeeded. `ctx.storage.sync()` returns a Promise that resolves once pending writes are durable, for code that wants to release only some messages early.
- A single-threaded Durable Object can never interleave two requests.
- An async callback passed to transactionSync() keeps awaited work inside the transaction.
- By default a Durable Object's reply can reach the client before its write is durable.
- Wrapping the payment fetch() in blockConcurrencyWhile() is the clean fix.
- The output gate stops other requests from reading data mid-transaction.