Skip to content
Auto
English

Scaling past one writer

A workspace starts as one Durable Object, its only writer. When one object is no longer enough, because its SQLite is filling up or it takes more writes than one object commits, the workspace splits into shards: more Durable Objects, each holding part of the rows. The client, the schema and the queries stay the same. The Worker routes each write to the shard that holds its rows and asks each shard a read may touch.

Every shard is its own Durable Object (<workspace id> for the first, <workspace id>.s<n> for the rest) with its own log and snapshots in R2. Which shard holds which rows is a directory stored in R2 with an epoch; a request routed by an older directory is answered moved and sent again, so a split never sends a write to the wrong place.

Rows are placed by a partition key. Without one a model is placed by its id. With partitionBy, rows that share a key share a shard:

import { model, schema, t } from "@tapedb/tapedb/schema";
export default schema({
event: model({ name: t.string() }),
seat: model({ event: t.belongsTo("event"), number: t.number(), heldBy: t.string().optional() }).partitionBy("event"),
message: model({ roomId: t.string(), body: t.string(), at: t.number() }).partitionBy("roomId", { buckets: 16 }),
});

The key is a required string or number field, or a required belongsTo: a model partitioned by a relation lands with its parent, and the parent must then be placed by its id. A key cannot change after a row is created. Single-row writes to a partitioned model name the key in where (for a relation, its foreign key, such as eventId), so the write goes straight to the right shard:

await db.seat.update({ where: { id, eventId }, data: { heldBy: me } });
await db.message.delete({ where: { id, roomId: "lobby" } });

create takes the key from data. The error codes are partition_key_missing and partition_key_immutable.

One key’s rows share one shard, so one key has one shard’s write rate. For a key busier than that, such as a large chat room or a feed, { buckets: n } (2 to 256) spreads the key’s rows over n shard keys by row id. A write still goes to one shard; a read of the key asks each bucket’s shard and merges the rows in order.

Pick the key that keeps a hot path’s rows together: the event a ticket belongs to, the room a message is in, the tenant a record belongs to. A transaction whose rows share a shard is one write; one that spans shards costs more (below).

Shards split on their own when the Worker says so:

defineTapeDB({ schema, shards: { auto: true } });
// or: shards: { auto: { atBytes: 4 * 1024 ** 3, atWritesPerSecond: 400, max: 64 } }

A shard then splits when its SQLite reaches atBytes (4 GB by default, of the 10 GB a Durable Object holds) or when it has committed atWritesPerSecond writes a second for half a minute, at the point that halves its rows, up to max shards. Rows with one partition key are never divided (except a bucketed key), so a shard holding a single key is left alone. It is off by default, and defineTapeDB throws if it is on while the schema has a named SQL query without shards, or a relation between models that are not placed together.

An owner can also split a shard by hand:

Terminal window
npx @tapedb/cli shards --workspace <uuid> # the directory
npx @tapedb/cli shards split --workspace <uuid> # split the first shard in half
npx @tapedb/cli shards split --workspace <uuid> --shard <name> # or a named one

or POST /engine/workspaces/<id>/shards/split with an owner’s claim. The shard keeps taking reads and writes while its rows are copied; rows written meanwhile are sent again as they ended up. Writes wait only for the last step, which costs the same however many rows move (the answer’s fenceMs), and are answered 503 shard_splitting, which clients retry. The old shard then deletes the rows it gave away in the background and leaves them out of reads until they are gone. A split that stops part-way resumes from the shard’s alarm. Moved rows are not changes: webhooks, extensions, /log and the audit log hear nothing, and a row’s history moves with it.

A transaction whose rows land on several shards commits on all of them or on none. Each shard but the last checks its part and holds it; the last shard’s commit decides; the rest then apply. A refusal on any shard refuses the whole transaction. A shard left waiting asks the deciding shard for the outcome, so a Worker that stops mid-commit leaves nothing half-done or locked, and a retry with the same clientTxId applies nothing twice. While it is unresolved the answer is 503 transaction_pending or transaction_aborted, which the client retries.

It costs two more calls between Durable Objects than a write on one shard, and writes to those shards wait for them, so keep a hot path on one shard. A read across shards sees each shard’s part as that shard commits it: for a few milliseconds it can see one part without the other.

The Worker asks every shard a query may touch, or only the key’s shard when where pins the partition key, and merges the answers into what one shard would have given: ordered rows cut to take, counts, aggregate() and groupBy() results (averages from sums and counts). Paging works across shards: a cursor is the values the last row was ordered by, so nextCursor resumes every shard. Live queries subscribe on one socket per shard they may touch and merge the same way.

Not across shards:

  • An include between models that are not placed together: include_across_shards. Place them together, or read them separately.
  • A named SQL query without shards: sql_across_shards. See SQL queries across shards.
  • $users read beside another model at the top level: replicated_across_shards. Include it from the other model instead.

A .unique() field stays unique across shards. Each value also has an entry in an engine index placed by the value, so one shard decides who holds it, wherever the row is. A write that takes or frees a value another shard keeps becomes a transaction across the two, which the Worker builds by itself; a second writer of the value gets unique_violation, as on one shard. If the unique field is the partition key, nothing changes: rows with the same value share a shard.

.index({ global: true }) on a string or number field keeps the same kind of index without the uniqueness:

ticket: model({ eventId: t.string().index({ global: true }), seat: t.number() }),

A read whose where pins the field to one value, such as where: { eventId }, first asks the value’s shard which shards hold matching rows, then asks only those. Past 512 matching rows, or while the directory is changing, it asks every shard; the answer is the same either way. A write to an indexed field also writes its entry, so it usually becomes a transaction across shards.

t.stock() is a whole number that never goes below zero, changed only by increment and decrement: seats, units in stock, credits.

// section: model({ name: t.string(), seats: t.stock() }), order: model({ buyer: t.string(), status: t.string() })
await db.$transaction([
db.order.create({ data: { id: orderId, buyer, status: "held" } }),
db.section.update({ where: { id: "A" }, data: { seats: { decrement: 2, hold: { id: orderId, for: "5m" } } } }),
]);
// Paid in time:
await db.$transaction([
db.order.update({ where: { id: orderId }, data: { status: "paid" } }),
db.section.update({ where: { id: "A" }, data: { seats: { confirm: orderId } } }),
]);
const { left, held } = await db.section.stock({ id: "A" });

With several shards the quantity is kept as one pool per shard, and a change runs on whichever shard the rest of its transaction runs on, so buying is one write on the buyer’s shard. A shard that runs short borrows from the others. The pools together never go below zero, so no unit is sold twice, and one quantity is not limited to one shard’s write rate. The row holds only its own shard’s part; read the whole with stock(), which answers { left, moving, held }.

A hold takes units now and gives them back by itself unless it is confirmed in time (for up to a day). { release: id } gives them back at once. Confirming or releasing a hold that has ended is hold_not_found; a second hold with the same id is hold_exists. Name a hold after the row its transaction writes, as above, and taking the seats and paying for them are each one write on one shard. The end of a hold is in the log, so a shard rebuilt from R2 ends it on time.

For an ordinary number, update can count with bounds: data: { left: { decrement: 1, min: 0 } } refuses the transaction with bound_exceeded rather than going below the bound.

A shard sends each change to every socket it holds, so the sockets on one shard bound how many people watch it live. Past live.relayAt sockets (2,000 by default) the Worker sends new ones to relays: Durable Objects of the same class, <shard>#relay<n>, that need no binding of their own. Viewers on a relay who watch the same query with the same role share one subscription at the shard. Presence and topics still reach the shard as the viewer.

defineTapeDB({ schema, live: { relayAt: 2_000, relays: 16 } });

For a page watched by everyone (a seat map, a scoreboard, a price), a published view is cheaper still: it is served from the edge cache and costs the shard one run per interval.

A split is refused with split_unsupported while a workspace uses files whose rules attach them to rows, or a relation between models that are not placed together. Moving a workspace with several shards to another jurisdiction is refused with move_across_shards. /import, /log, /metrics and the webhook routes answer for one shard and need ?shard=<name> once there are several (shard_required). /export, backup and restore cover every shard.