# Single-Writer Concurrency: Durable Objects for Exactly-Once Booking

> How we sell each leg of a bus seat once: one Durable Object per trip, synchronous SQLite transactions, leg bitmasks, expiry on read and idempotent confirms.

- URL: https://weaveward.com/blog/durable-objects-single-writer-booking
- Published: 2026-11-01
- Updated: 2026-11-12
- Category: Web Development
- Tags: cloudflare-workers, durable-objects, concurrency
- Author: Weaveward Team

Every booking system eventually meets the same bug: two riders tap "hold" on the same seat within a few milliseconds, both requests read "free", both write "held", and the operator finds out at the terminal. The usual fixes (row locks, version columns, retries) work until peak day, which is exactly when they start to hurt.

Our thesis is that a contended resource deserves exactly one writer, and that Cloudflare Durable Objects make that writer cheap if you respect one rule: never `await` between the check and the write. This article shows how we applied it in Trayek, our intercity bus booking prototype, where seats are sold leg by leg on multi-stop routes: the concurrency model, a working hold method on SQLite-backed storage, expiry and confirmation that survive misbehaving timers and webhooks, and the limits to plan around.

Trayek is a prototype running on synthetic routes and bookings. Every behaviour described here comes from its code and tests; we have not load tested it at Lebaran scale, and we say where that matters.

## Why booking needs one writer per contended resource

A double sale is a read, check, write race. The question is where you serialise. The table compares the options we considered for segment inventory, where a seat can be sold from Jakarta to Cikampek and again from Cikampek to Semarang.

| Approach | How it prevents a double sale | Where it hurts for leg-by-leg inventory |
| --- | --- | --- |
| Row locks in a shared database | Lock every seat row, check, write, commit | Multi-seat holds lock several rows; lock order and lock hold time across network round trips become your problem |
| Optimistic version column | Write only if the version is unchanged, retry otherwise | Retries cluster on the hottest trip at the busiest minute |
| Unique constraint per seat and leg | The database rejects the second row | Works, but a lapsed hold keeps blocking until a sweeper deletes it, so correctness depends on a timer |
| One writer per trip | Requests for a trip run one at a time in one thread | One object has a throughput ceiling, so you must shard |

We chose the last row. Trayek runs one `TripInventory` Durable Object per trip, addressed with `idFromName(tripId)`, and it is the only code that writes that trip's seats. D1 remains the system of record for the catalogue, bookings, passengers, tickets, payments and webhook events. Operator seat blocks go through the same object, so a hold and a block race like two holds. Traffic for one trip never touches another trip's object, so contention is bounded by the demand for one departure, not the whole network.

## Input gates, output gates and the no-await rule

A Durable Object runs in a single thread, but JavaScript is still event-driven, so two requests can interleave at every `await`. Cloudflare's runtime closes most of that gap with two rules. The input gate defers new events while a storage operation is in flight, so a request that awaits a storage read cannot be overtaken. The output gate holds back responses and outgoing requests until pending writes are durable, so a client never sees "held" for a write that later fails; if the write fails, the caller gets an error instead.

The gates protect storage operations. They do not make an `await` on other I/O safe: if your hold method awaited a D1 query, a `fetch` or an RPC call to another object between reading occupancy and inserting the hold, other requests could run in that gap and read the same "free" seat. That is the whole bug, reintroduced inside the object meant to prevent it.

So the rule in Trayek is structural. Every operation runs inside `ctx.storage.transactionSync`, whose callback must be synchronous. SQL on SQLite-backed objects (`ctx.storage.sql.exec`) completes synchronously, so the read, the overlap check and the insert happen in one callback with no `await`, and a throw rolls the transaction back. A reviewer only has to ask one question: is the check inside the closure?

One more detail from the storage documentation matters: a SQL cursor held across an `await` has no snapshot isolation. Trayek consumes every cursor with `.toArray()` before anything else happens.

## Seats as leg bitmasks inside a synchronous transaction

Number a trip's stops 0 to n; leg i runs from stop i to stop i + 1. A segment from stop `f` to stop `t` is the integer with bits `f` to `t - 1` set. Every sale and every live hold stores its mask, so "does this request collide with that booking?" is a single AND. A seat sold from stop 0 to stop 1 has mask `0b00001`, a request from stop 1 to stop 5 has mask `0b11110`, and their AND is zero, so the seat is resold for the rest of the trip without any special case.

JavaScript bitwise operators work on 32-bit signed integers, so Trayek caps trips at 30 legs and finishes each mask with `>>> 0`, keeping every mask a positive integer that SQLite stores and returns exactly.

This is a simplified version of the hold path. The real engine also rejects unknown seat labels and blocked seats, and returns the leg loads it saw so the Worker can lock the fare into the booking; the schema creation in the constructor is omitted here.

```ts
import { DurableObject } from "cloudflare:workers";

type Env = { DB: D1Database };
type HoldRequest = { holdId: string; seats: string[]; fromSeq: number; toSeq: number; now: number; ttlMs: number };
type HoldResult = { ok: true; expiresAt: number } | { ok: false; conflicts: string[] };

// Legs fromSeq to toSeq - 1 as bits: stops 1 to 3 on a five-leg trip is 0b00110.
const segmentMask = (fromSeq: number, toSeq: number): number => (((1 << (toSeq - fromSeq)) - 1) << fromSeq) >>> 0;

export class TripInventory extends DurableObject<Env> {
  async hold(req: HoldRequest): Promise<HoldResult> {
    const sql = this.ctx.storage.sql;
    const want = segmentMask(req.fromSeq, req.toSeq);
    const result = this.ctx.storage.transactionSync((): HoldResult => {
      const rows = sql
        .exec<{ label: string; leg_mask: number }>(
          `SELECT label, leg_mask FROM sales
           UNION ALL
           SELECT hs.label, h.leg_mask FROM holds h JOIN hold_seats hs ON hs.hold_id = h.hold_id
           WHERE h.status = 'ACTIVE' AND h.expires_at > ?`,
          req.now,
        )
        .toArray();
      const taken = new Map<string, number>();
      for (const row of rows) taken.set(row.label, (taken.get(row.label) ?? 0) | row.leg_mask);
      const conflicts = req.seats.filter((label) => ((taken.get(label) ?? 0) & want) !== 0);
      if (conflicts.length > 0) return { ok: false, conflicts };
      const expiresAt = req.now + req.ttlMs;
      sql.exec("INSERT INTO holds VALUES (?, ?, 'ACTIVE', ?)", req.holdId, want, expiresAt);
      for (const label of req.seats) sql.exec("INSERT INTO hold_seats VALUES (?, ?)", req.holdId, label);
      return { ok: true, expiresAt };
    });
    await this.scheduleSweep(); // after the commit: nothing above could interleave
    return result;
  }
}
```

The `WHERE h.expires_at > ?` clause means a lapsed hold simply stops counting. A multi-seat hold is all or nothing, because any conflict returns before the first insert. The only `await` comes after the commit, when nothing can change the decision. The Worker then writes the booking to D1 and releases the hold if that write fails.

## Holds that expire on read, alarms that only tidy

A rider's seats are held for 10 minutes while they pay (`HOLD_TTL_SECONDS` is 600). The tempting design is a timer that frees the seats at minute ten. We rejected it because Cloudflare documents alarms as at-least-once, retried with exponential backoff from 2 seconds for up to 6 retries, and occasionally delayed by up to a minute during failover. Correctness that depends on that timer will, on a bad day, keep a seat off sale too long or free it twice.

Trayek enforces expiry on read instead. Every availability query counts only holds whose `expires_at` is in the future, so a lapsed hold frees its seats the instant it lapses. D1 does the same: the booking view reports an open booking past its expiry as expired. Each object has a single alarm, re-armed after every change to the earliest pending expiry, and its only job is housekeeping.

```ts
  override async alarm(): Promise<void> {
    const now = Date.now();
    const expired = this.ctx.storage.transactionSync(() =>
      this.ctx.storage.sql
        .exec<{ hold_id: string }>(
          "UPDATE holds SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND expires_at <= ? RETURNING hold_id",
          now,
        )
        .toArray()
        .map((row) => row.hold_id),
    );
    if (expired.length > 0) {
      const update = this.env.DB.prepare(
        "UPDATE bookings SET status = 'EXPIRED', updated_at = ? WHERE hold_id = ? AND status IN ('HELD', 'PENDING_PAYMENT')",
      );
      try {
        await this.env.DB.batch(expired.map((holdId) => update.bind(now, holdId)));
      } catch (error) {
        console.error("alarm_d1_update_failed", { count: expired.length, error });
      }
    }
    await this.scheduleSweep();
  }

  private async scheduleSweep(): Promise<void> {
    const { next } = this.ctx.storage.sql
      .exec<{ next: number | null }>("SELECT MIN(expires_at) AS next FROM holds WHERE status = 'ACTIVE'")
      .one();
    if (next === null) await this.ctx.storage.deleteAlarm();
    else await this.ctx.storage.setAlarm(next);
  }
```

Both updates are guarded by the current status, so a late or repeated alarm changes nothing already settled. The repository selects due holds and then updates them; `RETURNING` is a shortcut for this article. The D1 failure is logged rather than thrown on purpose: the object has already committed, a retried alarm would find nothing left to expire, and because both stores enforce expiry on read, a missed tidy-up leaves a stale status, never a sellable double booking.

## Confirming across two stores without a distributed transaction

The paid webhook touches two stores: the trip object, which owns the seats, and D1, which owns the booking, passengers, tickets and payment. No transaction spans both, so the order and idempotency of each step carry the design.

Trayek confirms in the Durable Object first, then writes the booking status, passengers, tickets, payment status and the processed event in one D1 batch, which D1 runs as a single SQL transaction. Consider the failure in each order:

- **D1 first, then the object.** If the object call fails, D1 says confirmed while the object still treats the seat as a hold. Once the hold lapses, the seat is sold again: a double sale
- **Object first, then D1.** If the batch fails, the seat is sold in the object but the booking is not confirmed and the event is not marked processed. The provider retries, the object's confirm is idempotent (a confirmed hold returns the same seats) and the batch runs again. If the provider never retries, a seat is held back from sale: a revenue leak, not two passengers in one seat

We prefer the failure that loses a sale. The D1 side is idempotent too: the booking update is guarded by `status IN (...)`, tickets are unique on booking and seat with `ON CONFLICT DO NOTHING`, and each event ID is recorded once. For production we would add a reconciliation pass comparing object sales with confirmed bookings, because the orphaned-sale window is real even if rare.

Late money is the other edge. The payment request expires 60 seconds before the hold, so a normal payment cannot land after the seats are released. When one does, confirmation tries the same seats, then other free seats on the same legs (preferring one row), and otherwise marks the booking for a refund.

### A payment state machine that converges

Providers redeliver and reorder webhooks, so Trayek never applies events in arrival order. Each status has a precedence, and an event applies only if it raises it.

| Status | Precedence | Reachable from |
| --- | --- | --- |
| `PENDING` | 0 | Initial state |
| `FAILED`, `EXPIRED` | 1 | `PENDING` |
| `PAID` | 2 | `PENDING`, `FAILED`, `EXPIRED` |
| `REFUNDED` | 3 | `PAID` only |

A late `expired` after `paid` is ignored, while money that lands after an expiry is still accepted. The SQL update repeats the rule (`WHERE status IN (allowedSources(target))`), so two deliveries processed at once still converge. For pushing more invariants into the database itself, see our article on [double-entry ledger invariants](/blog/double-entry-ledger-database-invariants).

## A waiting room built from a lazy token bucket

One trip object is one thread, with a documented soft limit of 1,000 requests per second per object. On peak days the operator can switch on a waiting room for a route and service date: a second Durable Object, `WaitingRoom`, that meters riders through a token bucket and a first-in, first-out queue in SQLite.

There is no timer. Every call, whether a rider joining, a rider polling or the operator reading stats, refills the bucket for the elapsed time and admits queue heads inside one `transactionSync`.

```ts
type Rate = { ratePerMinute: number; burst: number };
type Bucket = { tokens: number; refilledAt: number };
const MINUTE_MS = 60_000;

// No timer: the bucket is brought up to date from elapsed time on every call.
export const refill = (bucket: Bucket, rate: Rate, now: number): Bucket => ({
  tokens: Math.min(rate.burst, bucket.tokens + (Math.max(0, now - bucket.refilledAt) * rate.ratePerMinute) / MINUTE_MS),
  refilledAt: Math.max(now, bucket.refilledAt), // a clock that steps back never mints tokens
});

// Runs inside transactionSync on the WaitingRoom object, on every join, poll or stats call.
export const admit = (bucket: Bucket, rate: Rate, waiting: number, now: number) => {
  const fresh = refill(bucket, rate, now);
  const admitted = Math.min(Math.floor(fresh.tokens), waiting); // queue heads, in arrival order
  return { bucket: { ...fresh, tokens: fresh.tokens - admitted }, admitted };
};

// A newcomer gets in at once only when nobody is already waiting.
export const join = (bucket: Bucket, rate: Rate, waiting: number, now: number) => {
  const { bucket: after, admitted } = admit(bucket, rate, waiting, now);
  const stillWaiting = waiting - admitted;
  if (stillWaiting === 0 && after.tokens >= 1) {
    return { bucket: { ...after, tokens: after.tokens - 1 }, position: 0 };
  }
  return { bucket: after, position: stillWaiting + 1 };
};
```

The ordering in `join` is the fairness guarantee: a freshly refilled token goes to the head of the queue, never to whoever asked last, and a quiet room costs nothing. Once admitted, a rider gets an HMAC-signed pass, 15 minutes by default, that the Worker verifies on each hold without calling the room again.

## How we tested the races

Trayek's integration tests run inside the Workers runtime and fire real concurrent calls at real objects:

- 30 concurrent holds on one seat over the same legs: exactly one succeeds
- 40 concurrent holds over overlapping segments of a five-leg trip: the winners never overlap
- A hold and an operator block racing on each of ten seats: on every seat exactly one succeeds
- 25 concurrent arrivals at a waiting room with a burst of 5: exactly 5 are admitted and the other 20 hold positions 1 to 20
- Five concurrent deliveries of one paid webhook event: the tickets are issued once

We also ran this article's simplified hold and alarm code in a local Workers runtime: 30 racing holds on one seat produced one winner, and a lapsed hold was freed on read and its booking marked expired by the alarm. None of this is a load test. It proves that conflicting writes cannot both succeed, not how latency behaves at thousands of riders a minute, which the prototype's documentation lists as production work.

## Limits, and where we would shard next

Single-writer design trades parallelism for simplicity, so be explicit about the ceiling:

- **One object is one thread.** Keep transactions short and free of I/O; a slow callback delays every rider on that trip. Shard by the unit of contention, which for Trayek is the trip, not the route or the operator
- **Cross-trip operations are not atomic.** Two connecting trips mean two objects, which needs a saga with compensations, not a bigger object
- **Search fans out.** Each search asks every candidate trip's object for a segment summary; at scale we would cache summaries and accept a few seconds of staleness on search while the hold path stays authoritative
- **Mask width.** Thirty legs suits intercity buses; a rail line with more stops would need two integers or a `BigInt` mask

## Checklist

- Give each contended resource exactly one writer, and shard by the unit of contention
- Put the check and the write in one `transactionSync` callback, with no `await` between them
- Consume SQL cursors before any `await`
- Encode segments as bitmasks so overlap is one AND and resale needs no special case
- Enforce expiry on read; let alarms only tidy up, idempotently
- Across stores, write first where a failure loses a sale rather than duplicating one, and make both steps idempotent
- Apply payment events by precedence, and repeat the rule in the SQL guard
- Prove races with concurrent integration tests, then load test separately

## Primary references

- [Cloudflare Durable Objects: SQLite-backed storage API, including `transactionSync` and cursor behaviour](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/)
- [Cloudflare Durable Objects: Alarms, at-least-once execution and retry policy](https://developers.cloudflare.com/durable-objects/api/alarms/)
- [Cloudflare blog: Durable Objects: Easy, Fast, Correct, Choose three (input and output gates)](https://blog.cloudflare.com/durable-objects-easy-fast-correct-choose-three/)
- [Cloudflare Durable Objects: Limits, including the per-object request soft limit](https://developers.cloudflare.com/durable-objects/platform/limits/)
- [Cloudflare D1: Worker API, `batch()` as a SQL transaction](https://developers.cloudflare.com/d1/worker-api/d1-database/)

## Related reading

- [Booking Software Features That Prevent Scheduling Errors](/blog/booking-reservation-system-features)
- [Next.js on Cloudflare Workers: A Deployment Checklist](/blog/cloudflare-workers-nextjs-deployment)

The full prototype is described in our [Trayek intercity bus booking case study](/work/trayek-intercity-bus-booking), and our [web application services](/services/web-apps) cover building systems like it.
