Store
Store saves data one key at a time. It is the storage to use for
multiplayer decks: two players writing different keys no longer
overwrite each other, a counter can be added to safely from several
places at once, and a deck can hold much more than Storage allows and
read back a slice of it rather than the whole thing.
Values can be anything that converts to JSON, the same as Storage.
Scopes decide who owns a key:
Store.deck— shared by everyone playing. If the deck publishes a session server, the server owns these keys and players read them.Store.me— the current player's data, which other players can read.Store.user(userId)— another player's public data. Anyone can read it; only that player, or the deck's session server, can write it.Store.private— the current player's own data. Nobody else can read it, and a session server never sees it.
Store.<scope>.get<T>(keys): Promise<Record<string, T>>
Reads several keys at once. Keys with nothing stored are missing from
the result rather than present as null.
const { level = 1, name } = await Store.deck.get(["level", "name"]);
Store.<scope>.set(values): Promise<void>
Writes several keys. Nearby writes are grouped, so saving on every change costs one request per burst. The promise resolves once the platform has the write, so a deck can tell whether saving worked.
await Store.deck.set({ level: 7, name: "Ada" });
Store.<scope>.remove(keys): Promise<void>
Removes keys.
Store.<scope>.increment(key, delta?): Promise<number>
Adds delta (default 1) to a number and returns the new total,
starting the key at delta if it was not set. Two players incrementing
at the same moment both count, which is the thing a read, add and write
back cannot promise.
const plays = await Store.deck.increment("plays");
Store.<scope>.list(options?): Promise<{ entries, cursor }>
Reads a page of keys in order, optionally only those starting with
prefix. Pass the cursor from one page to get the next.
let cursor = null;
const world = [];
do {
const page = await Store.deck.list({ prefix: "block:", cursor });
world.push(...page.entries);
cursor = page.cursor;
} while (cursor);
Keep reading until cursor is null. A page can come back shorter than
you asked for because it reached its size limit, not because the keys
ran out, so the cursor is the only reliable end signal.
A paged read is not a snapshot: something written while you are paging may land in no page or in two. Treat the result as a starting point and apply live updates on top, which a multiplayer deck is doing anyway.
Store.board(name)
A leaderboard, separate from the keys above so that reading the top scores stays fast no matter how many players there are.
await Store.board("highscores").submit(score);
const top = await Store.board("highscores").top(10);
const mine = await Store.board("highscores").get();
submit(score)records the current player's score. A later submission replaces an earlier one, so compare first if you only want to keep a personal best.top(limit?)returns the highest scores, best first.get(userId?)returns one player's score, defaulting to the current player, ornullif they have none.
A deck's session server can submit any player's score, which is how a leaderboard becomes something a player cannot fake. See the multiplayer guide.
Store.usage(): Promise<StoreUsage>
How much the current player and the deck have stored, against the limits below, so a deck can warn a player or clear out old saves before a write is refused instead of after.
const { player, shared } = await Store.usage();
if (player.byteCount > player.byteLimit * 0.9) {
// Nearly full: offer to delete old saves.
}
playeris the current player's own allowance in this deck: theirStore.meandStore.privatekeys, and their board scores.sharedisStore.deck, one allowance for every player together.
Each has byteCount, byteLimit, keyCount and keyLimit. A board
score counts as a key. The answer includes the set and remove calls
the page made before calling it, even ones still being batched; await an
increment or a board submit first if the answer should include it. A player can only ever see their own usage, not
another player's.
rate says how much of the per-second rate limits (the last two rows of
the table below) is spent right now, so a deck that writes often can back
off before a call is refused rather than after:
const { rate } = await Store.usage();
if (rate && rate.caller.opsUsed > rate.caller.opsLimit * 0.8) {
// Close to this player's calls-per-second limit: batch or slow down.
}
rate.calleris the current player's own limit, andrate.deckis the one every player of the deck shares.- Each has
opsUsed,opsLimit,bytesUsedandbytesLimit, counted over the current one-second window, and theusagecall itself is counted in them. rate.callerClassnames which limitcalleris:"client"for a page.
rate is missing when the app is older than it, so check for it before
reading it.
An app too old to know usage rejects with a CastleError whose code
is UNKNOWN_COMMAND.
Limits
The platform caps key length, value size, how many keys one read may
name, and how much each player may store, and it limits how fast a
player may read and write. Going over one of these rejects with a
CastleError whose code says which, so a deck can tell a player it is
saving too fast apart from a player who is out of space:
| limit | value |
|---|---|
| key | 128 bytes |
| value | 256 KB |
keys in one get | 32 |
| one player's data in a deck | 50 MB, 50,000 keys |
the deck's shared data (Store.deck) | 500 MB, 1,000,000 keys |
| one player's calls | 20 a second, 512 KB a second |
| every player of a deck together | 500 calls a second, 8 MB a second |
These do not reject. set and remove with more than 32 keys are split
into several calls by the SDK (each still counts against the rate above).
A list page holds at most 1,000 entries (a larger limit is lowered to
it) and ends early once it reaches 1 MB; take the next page with its
cursor.
A player's data is everything stored for them: their Store.private
keys, their Store.user(id) keys, and their scores on every board.
Each player has their own allowance, so a deck with more
players can hold more, and one player filling theirs does not stop
anyone else. A write that shrinks what a player stores always succeeds,
so a player who is full can always free space.
A value is JSON, so binary data such as a picture or a video clip costs about a third more once encoded, and a clip of more than a few seconds does not fit in one. Ship media with the deck instead.
Atomic saves
Store exposes typed save methods:
snapshot({ targets: [{ target, select? }] })reads every selected target at one consistent point.selectis{ prefix }or{ keys }within the target; omitted selection reads its whole prefix. The result hasaccessandtargets: [{ target, revision, rows, complete }].completedescribes coverage of the entire target. A successfulnullrevision means absent; an initialized empty target has a revision. A failed read never means absent.transaction({ operationId, expectedAccess, checks?, changes })commits all changes together. Each change hastarget,expectedRevision(string ornull), optionalwriter, and eitherput/removeorreplace.replaceremoves omitted rows within the prefix. Each target appears once. Anullexpected revision creates only an absent target; an explicitreplacealso supports importing unregistered legacy rows.checksare read-only target checks with an expected revision and/or writer; they leave revisions intact.claim({ operationId, expectedAccess?, target, initial?, load? })explicitly takes ownership of a target and returns{ writer, receipt, snapshot }.initial: [{ target, rows }]initializes absent targets only. An absent claimed target initializes empty if defaults were omitted. Claiming an existing target leaves its data revision unchanged. The latest committed claim wins; claimed targets require the current writer on every change.initialize({ operationId, expectedAccess?, initial, load? })initializes only absent targets and returns{ receipt, snapshot }. Concurrent defaults are applied once. It never claims ownership or replaces existing data.operation(operationId)returns{ state: "committed", receipt }or{ state: "unknown" }. Unknown does not cancel a delayed request. Settle it by replaying the original input and ID.
A target is { scope: "deck" | "user" | "private", subject?, prefix }.
The prefix must be nonempty, and registered prefixes in a bucket cannot
intersect. All row keys stay inside their target. subject is only for user
scope; omitted subject means the current player. Session servers must name a
user and cannot access private targets. Permissions and quotas are unchanged:
deck-scoped bags remain publicly readable and share the deck allowance.
rows, put and replace are maps of keys to JSON values, validated through
the same JSON handling as ordinary Store writes.
A receipt contains operationId, access, revisions: [{ target, revision }]
and, for claims, writer. Access and revisions are opaque. Use snapshot access
as expectedAccess; reset and undo invalidate old access, revisions and writer
tokens. Claim/initialize may omit expected access for a deliberate first open.
When load is omitted, the SDK requests the claimed/initial targets. Supply
an explicit load to choose other targets or smaller projections.
Every bucket also has target(prefix) and the same methods with a prefix
wherever the root takes a target: snapshot({ prefix, select? }),
transaction({ changes: [{ prefix, ... }], checks?: [{ prefix, ... }] }),
claim({ prefix, initial?: [{ prefix, rows }], load?: [{ prefix, select? }] }),
initialize({ initial: [{ prefix, rows }], load? }) and operation(id).
Root methods can combine buckets atomically:
const room = Store.deck.target(`room:${roomId}:`);
const bag = Store.deck.target(`bag:${roomId}:${userId}:`);
const opened = await Store.claim({
operationId: crypto.randomUUID(),
target: room,
initial: [{ target: room, rows: roomDefaults }, { target: bag, rows: starterBag }],
load: [{ target: room }, { target: bag }],
});
const receipt = await Store.transaction({
operationId: actionId,
expectedAccess: opened.snapshot.access,
changes: [
{ target: room, expectedRevision: opened.snapshot.targets[0].revision,
writer: opened.writer, put: changedRoomRows, remove: deletedRoomKeys },
{ target: bag, expectedRevision: opened.snapshot.targets[1].revision,
put: changedBagRows },
],
});
// Acknowledge the gameplay action only after this receipt.
Atomic saves bypass ordinary coalescing and 32-key splitting. They are never
split into partial writes or retried as ordinary SETs. A request or snapshot
that exceeds a transport or single-charge byte allowance fails with
CAULDRON_STORAGE_TOO_LARGE; narrow the selection or reduce the atomic payload.
Ordinary set, remove and increment reject keys inside registered targets
with CAULDRON_STORAGE_MANAGED_TARGET.
Save methods reject with SaveError, exported from the client and server SDK.
It carries code, message, operationId, retryable,
committed: false | true | "unknown", and optional receipt, retryAfterMs
and target. Extra platform details remain in extensions. Conflicts, writer
loss and stale access require explicit reload/rebuild. A replayed historical
claim can fail with writer loss while committed === true and its original
receipt; it never takes ownership again. Transport ambiguity keeps the outcome
unknown until receipt lookup or identical replay settles it.
Save coordinator
createSaveCoordinator, from castle-web-sdk or castle-web-sdk/server,
sends a deck's transactions in order and keeps each one until it settles:
const saves = createSaveCoordinator(Store, opened.snapshot, [
{ target: room, writer: opened.writer },
]);
const receipt = await saves.submit({
operationId: actionId,
checks: [{ target: room, writer: opened.writer }],
changes: [{ target: bag, put: changedBagRows }],
});
await saves.flush();
// saves.status is "pending", "saved" or "blocked".
submit copies the save and resolves with its receipt once it commits. A
change without expectedRevision takes the target's revision from the latest
receipt, filled in when the save is first sent; a change without writer
takes the one passed in for its target. Saves are sent one at a time, in
order. A save whose reply was lost is looked up by its id and, when the
platform has no receipt for it, sent again unchanged.
A failure that cannot be settled that way sets status to "blocked" and
holds back every save behind it. When the outcome is unknown or the error is
retryable, the save's promise stays pending and retry() sends the same
request again. When the save definitely did not commit (a conflict, a lost
writer), its promise rejects and the coordinator stays blocked: reload a
snapshot and start a new coordinator. It never claims or rebuilds a save on
its own. error, pendingOperationIds and revision(target) show its state.
flush() resolves once every save submitted before it has committed, and
rejects if the queue blocks first. Saves submitted after it do not hold it up,
and an earlier receipt never marks a later save saved. For start-over, call
discardUnsent() and submit the replacement: saves already sent still settle
first, and the replacement goes out at the revision they leave.
Keep the coordinator in the page when a private worker is replaced. A page or process that dies loses the saves it had not sent and the ids of those it had; reopening restores the last committed snapshot.
During castle-web serve, the serve answers the save API itself, from one
in-memory store per project shared by its pages and named sessions. Its rows,
receipts and writers survive a runtime restart and are lost when the serve
exits. Ordinary get, set and list still use the deck's real storage, and
the two do not see each other's rows.