Interactive Learning Platform Nuxt layer

Isolated learning atmosphere · v4.x

← Back to writing
Step 4 of 9D1 holds + queue

D1 Holds and the Queue: Pick the Right Store

Give drivers a fifteen-minute bay hold and a charging queue backed by D1. Compare KV and D1, use a small state adapter, and see why the demo chooses D1 for live state.

Stage 3 could tell you a bay was free. Stage 4 lets a driver claim it for fifteen minutes, join a queue when nothing is free, and release the hold when plans change.

ampyard / preview / 4
Live stage Open app ↗
Ampyard · live stageStage 4 / 9

What it is#

Two pieces of live state:

  1. A hold. One driver, one bay, fifteen minutes, one state record and one stall status.
  2. A queue. A JSON array under one key, ordered by join time.

Ampyard stores both in D1, in a small demo_state table keyed by name. The durable reservation also goes into the reservations table for the ledger. The live lease and the history share a database, but not a shape.

sql
CREATE TABLE demo_state (
  key TEXT PRIMARY KEY,
  value TEXT NOT NULL,
  updated_at TEXT NOT NULL
);

The keys are the same names the KV version used: stall:<id>, queue, reservation:<id>. A thin adapter (stateGet, stateSet, stateRemove) chooses the backend.

Why D1, not KV#

I originally used KV because the lesson was about Nitro's KV surface. That was the wrong default for this app. The difference matters:

Cloudflare KVCloudflare D1
ShapeKey-valueServerless SQLite
ReadsVery fast at the edgeSQL queries, indexed rows
ConsistencyEventually consistentStrongly consistent
Free writes1,000/day100,000 row writes/day
Best forTokens, flags, small cached blobsHolds, queues, ledgers, anything you query

The demo is write-heavy relative to KV's free tier: a hold is two writes, a queue join is one, a manual tick is up to four. That is fine for a reader, but a one-minute simulator burned 1,000 writes in under two hours. D1 gives the same demo 100× the write budget and a query model that fits the queue and the ledger.

KV is still a good tool. It is the right place for a read-through cache, a session token, a feature flag, or a tiny edge value. It is not the right primary store for a demo clock.

The deployed demo uses D1. The code keeps the KV path behind AMPYARD_STATE_STORE=kv so you can compare them. The board shows the active store as store d1 or store kv.

What we're building#

  • A demo_state table in D1.
  • A stateStore() switch: D1 by default, KV with AMPYARD_STATE_STORE=kv.
  • stall:<id> records for live bay state.
  • reservation:<id> records for holds.
  • queue for the waiting list.
  • reserveStall, cancelReservation, expireReservations, joinQueue, and leaveQueue.
  • The hold and queue buttons in the UI, gated at stage 4.

The adapter#

Every read and write goes through three functions. The rest of the depot does not care which backend is active:

server/utils/depot.ts
type StateStore = "kv" | "d1";

function stateStore(): StateStore {
  return process.env.AMPYARD_STATE_STORE === "kv" ? "kv" : "d1";
}

async function stateGet<T>(key: string): Promise<T | null> {
  if (stateStore() === "kv") {
    return (await kv().getItem<T>(key)) ?? null;
  }

  await setupDatabase();
  const db = useDatabase();
  const { rows } = await db.sql`SELECT value FROM demo_state WHERE key = ${key}`;
  if (!rows[0]) return null;
  return JSON.parse(String(rows[0].value)) as T;
}

async function stateSet(key: string, value: StorageValue): Promise<void> {
  if (stateStore() === "kv") {
    await kv().setItem(key, value);
    return;
  }

  await setupDatabase();
  const db = useDatabase();
  await db.sql`INSERT OR REPLACE INTO demo_state (key, value, updated_at)
    VALUES (${key}, ${JSON.stringify(value)}, ${new Date().toISOString()})`;
}

stateRemove is the same idea with DELETE FROM demo_state or kv().removeItem.

The hold flow#

A hold is one state write plus one ledger row:

server/utils/depot.ts
const id = `hold-${crypto.randomUUID()}`;
const expiresAt = new Date(Date.now() + minutes * 60_000);

await db.sql`INSERT INTO reservations (...)
  VALUES (${id}, ${stallId}, ${driver}, ..., 'held')`;

await stateSet(`reservation:${id}`, {
  id,
  stallId,
  driver,
  startsAt: new Date().toISOString(),
  expiresAt: expiresAt.toISOString(),
  status: "held",
});

await writeStallLive(stallId, {
  status: "reserved",
  reservationId: id,
  driver,
  expiresAt: expiresAt.toISOString(),
});

The board reads all eight bays in one query, not eight:

server/utils/depot.ts
const { rows } = await db.sql`
  SELECT key, value FROM demo_state WHERE key LIKE 'stall:%'
`;
const map = new Map<string, StallLiveState>();
for (const row of rows) {
  const id = String(row.key).slice("stall:".length);
  map.set(id, JSON.parse(String(row.value)) as StallLiveState);
}

That bulk read is the "make it faster with what we have" part: D1 is fast when you ask one question, not eight.

The expiry path#

A hold that never expires is a bug. Two mechanisms keep it honest:

  1. The state record carries expiresAt. The board can render the deadline before the task runs.
  2. The reservations:expire task scans D1 for held reservations whose deadline has passed, flips the bay back to available, removes the state record, and writes an event.

The task runs in the nightly maintenance pass, not every minute. Expiry is eventual by nature; a fifteen-minute hold does not need a per-second enforcer. Stage 6 takes the clock apart.

Do it yourself#

Run the app and open /preview/4:

bash
pnpm --filter ampyard dev
  1. Find an open bay. Click Hold 15m.
  2. Refresh the page. The bay should still be held, with the deadline in the card.
  3. Click Release. The bay returns to open.
  4. Join the queue. The queue panel shows your position.
  5. Open Ops and click Advance depot clock. The simulator may promote the queue or settle a session.
  6. Check the store badge: store d1 is the default.

To compare the KV path:

bash
AMPYARD_STATE_STORE=kv pnpm --filter ampyard dev

The board now shows store kv. The same UI, the same adapter, a different backend.

The live stage#

The preview above is /preview/4. The queue panel, hold buttons, and release buttons are live. Stage 3 is still available at /preview/3 with no hold controls. The old stage does not receive later features.

Gotchas#

  • D1 is still a database. A write is a row write, not free. Keep the manual simulator and the nightly maintenance pass; do not put a one-minute loop on it.
  • JSON in a text column. demo_state.value is TEXT. Serialize on write, parse on read, and handle malformed rows by falling back to available.
  • The queue is one row. A read-modify-write race can drop an entry. For a real depot, use a transaction or a dedicated queue table with an ordered index.
  • A hold is not auth. Anyone who can call the route can hold a bay. In a real app, the hold belongs to an authenticated driver.
  • KV is eventually consistent. If you opt into AMPYARD_STATE_STORE=kv, two tabs can overwrite each other at the same instant. D1 is strongly consistent, which is another reason it is the default.
  • The deployed demo has a KV binding. It is there for the optional KV path and for the lesson. The default D1 path does not write to it.

Recap#

Ampyard now has live state: D1-backed holds, a D1-backed queue, a bulk stall read, and a nightly expiry pass. The KV path is still available behind an env flag, so you can compare the two stores without rewriting the app. Stage 5 takes the ledger apart.

Next: The D1 Ledger.