services
Get a key

library / Integrations / I0049

Firestore slot-ordered account writes

A Node script reads three busy token accounts, subscribes to them, and prints apply or skip for every push under a slot-then-sequence guard, with counters for repeated and backward slots. The same guard goes inside a Firestore transaction.

By Carbium · Document and key-value stores · I0049 · updated 2026-11-22

01

What a push carries

An accountNotification holds the account's full state at one slot: lamports, owner, data and context.slot. A mirror that stores the newest state it has seen ends up correct, so one Firestore document per account, with the address as its id, is all the mirror needs.

The open question is order. Two things can reach your writer in the wrong order: a push and the read you used to seed the document, or two pushes around a fork switch. Without a check, an older state overwrites a newer one and stays there until the account changes again, which on a quiet account can take a long time.

02

When a slot repeats

On a stock Agave node the notifier sends a push only when the account's last-modified slot differs from the last slot it notified for that subscription. A subscription therefore gets at most one push per slot, carrying the account as it stands at the end of that slot, however many transactions in the slot wrote it. A busy token account changed by ten transactions in one slot produces one push.

An equal or lower slot reaching your writer comes from one of two places.

  • A read meeting a push. getAccountInfo answers with its own context.slot, and a push stamped with that same slot can arrive just after the read. A push for an earlier slot can also arrive after a read at a later one. Pinning a read with minContextSlot keeps a read from answering behind a slot you already hold, and it does nothing about a push in flight.
  • A fork switch. When the node moves to another fork it can notify again for a slot it already notified, or for a lower one, with the state on the new fork.

What the socket you connect to does for your own account is a measurement. The script below counts it, so the answer for your account comes from your own run.

03

The guard

Each document holds the account address as its id, plus slot, seq, the lamports and the data. slot is the context.slot of the stored state. seq counts pushes: your process raises it for each accountNotification, with 0 for the start-up read. A new state applies when its slot is higher than the stored one, or equal with a higher seq. A lower slot is skipped.

Equal slots need the second key because a read and a push stamped with one slot describe the same moment, and the later arrival has seen at least as much as the earlier one. The seq settles that tie by arrival order in your process and says nothing about slots.

In Firestore the check runs inside runTransaction: transaction.get on the account's document, the comparison, then transaction.set only when the state applies. Firestore can run the callback again when two writers contend for a document, so the callback holds no side effects and takes its seq before it starts. The script runs the same comparison against a Map, which keeps it runnable without a Firestore project.

04

The measuring script

Use Node 24 and npm install @solana/[email protected]. The script takes one program address and defaults to an AMM program with constant activity. It lists the 20 newest signatures of that program, fetches each transaction at confirmed commitment with maxSupportedTransactionVersion: 1, counts the token accounts in the transactions' token balances, and keeps the three most common. It reads each with getAccountInfo at confirmed commitment, subscribes to all three on one socket for 15 seconds, and prints apply or skip for each push. It needs CARBIUM_KEY and exits with a message when it is unset. CARBIUM_RPC_URL and CARBIUM_WS_URL are optional. It only reads.

main.ts
// I0049 · Firestore slot-ordered account writes// https://carbium.sh/library/integrate/firestore-slot-ordered-account-writes// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY."); process.exit(1); }const program = process.argv[2] ?? "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);const wsBase = process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh";const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));// The three token accounts that appear most in the program's 20 newest transactions.type Tx = { meta: { postTokenBalances?: { accountIndex: number }[] } | null; transaction: { message: { accountKeys: { pubkey: string }[] } } } | null;const sigs = await rpc.getSignaturesForAddress(address(program), { limit: 20, commitment: "confirmed" }).send();const fetched = await Promise.allSettled(  sigs.map((s) => rpc.getTransaction(s.signature, { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()),);const counts = new Map<string, number>();for (const f of fetched) {  if (f.status === "rejected") {    console.log(`getTransaction failed: ${msg(f.reason)}`);    continue;  }  const tx = f.value as unknown as Tx; // null for a signature below the ledger floor  for (const b of tx?.meta?.postTokenBalances ?? []) {    const k = tx?.transaction.message.accountKeys[b.accountIndex]?.pubkey;    if (k) counts.set(k, (counts.get(k) ?? 0) + 1);  }}const picked = [...counts].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([k]) => k);if (picked.length === 0) { console.error("No token accounts found in the sampled transactions."); process.exit(1); }// A Map stands in for one Firestore document per account. In Firestore, run apply() between// transaction.get and transaction.set, and write only when it returns true.const docs = new Map<string, { slot: number; seq: number }>();const apply = (acct: string, slot: number, seq: number) => {  const cur = docs.get(acct);  const ok = !cur || slot > cur.slot || (slot === cur.slot && seq > cur.seq);  if (ok) docs.set(acct, { slot, seq });  return ok;};const amountOf = (b64: string) => {  const d = Buffer.from(b64, "base64");  return d.length >= 72 ? String(d.readBigUInt64LE(64)) : "n/a";};const reads = await Promise.allSettled(picked.map((a) => rpc.getAccountInfo(address(a), { commitment: "confirmed", encoding: "base64" }).send()));reads.forEach((r, i) => {  const a = String(picked[i]);  if (r.status === "rejected") return console.log(`read ${a.slice(0, 6)} failed: ${msg(r.reason)}`);  const slot = Number(r.value.context.slot);  console.log(`read ${a.slice(0, 6)} slot ${slot} seq 0 ${apply(a, slot, 0) ? "apply" : "skip"}`);});let seq = 0;const lastPush = new Map<string, number>(); // push slots only, apart from the read slotconst tally = { pushes: 0, applied: 0, skipped: 0, repeatedSlot: 0, backwardSlot: 0 };const subs = new Map<number, string>();const ws = new WebSocket(`${wsBase}${wsBase.includes("?") ? "&" : "?"}api-key=${key}`);ws.onopen = () => picked.forEach((a, i) => ws.send(JSON.stringify({ jsonrpc: "2.0", id: i + 1, method: "accountSubscribe", params: [a, { encoding: "base64", commitment: "confirmed" }] })));ws.onerror = () => console.log("socket error");ws.onmessage = (ev) => {  const m = JSON.parse(String(ev.data));  if (m.error) console.log(`subscribe failed: ${m.error.message}`);  if (typeof m.result === "number") subs.set(m.result, String(picked[m.id - 1]));  if (m.method !== "accountNotification") return;  const acct = subs.get(m.params.subscription);  if (!acct) return;  const { context, value } = m.params.result;  const slot = Number(context.slot);  const prev = lastPush.get(acct);  tally.pushes++;  if (prev === slot) tally.repeatedSlot++;  if (prev !== undefined && slot < prev) tally.backwardSlot++;  lastPush.set(acct, slot);  const ok = apply(acct, slot, ++seq);  tally[ok ? "applied" : "skipped"]++;  if (tally.pushes <= 40) console.log(`push ${acct.slice(0, 6)} slot ${slot} seq ${seq} ${ok ? "apply" : "skip"} amount ${amountOf(value.data[0])}`);};setTimeout(() => {  console.log(`pushes ${tally.pushes} applied ${tally.applied} skipped ${tally.skipped} repeated slot ${tally.repeatedSlot} backward slot ${tally.backwardSlot}`);  process.exit(0);}, 15000);

run: node main.ts

A line shows the first characters of the account, the slot, the seq, the decision and the token amount, which sits at byte 64 of a token account's data. The script prints the first 40 pushes and tallies all of them. After 15 seconds it prints the tally and exits, so the last line is always the tally.

The 20 transaction fetches cost 50 cells each, 1,000 together, which fits inside the 1,024-cell burst. The three reads cost 10 cells each. Each account subscription costs 25 credits to open, then 20 credits per MiB sent.

05

Reading the counters

  • pushes: notifications received across the three accounts.
  • applied and skipped: the guard's decisions. A skip is a push that arrived behind the stored state, most often behind the start-up read.
  • repeated slot: a push whose slot equals the previous push for the same account.
  • backward slot: a push whose slot is lower than the previous push for the same account.

The script keeps the last push slot in its own variable, separate from the slot of the read. Both counters therefore compare a push with a push. A start-up read at slot S followed by the first push for S would otherwise count as a repeat that never happened on the socket.

On a stock node both counters stay at 0 outside fork switches. A non-zero value on your account says your writer needs the second key. A zero over 15 seconds describes those 15 seconds, so run it a few times before you drop the tie-break.

06

Where it ends

  • A skipped state is dropped. If a fork switch brings a state at a lower slot than the document holds, the document keeps the higher slot until a newer slot arrives. At confirmed commitment this heals at the next change. A mirror that must never show a dropped fork needs a finalized subscription.
  • seq is local. Two writer processes, or a restart, each count from 0, so an equal-slot tie between them goes to whichever counted higher. Run one writer per account.
  • Firestore's guidance is about one sustained write per second to a single document. An account that changes in most slots needs the writer to coalesce: keep the newest state that passed the guard and write it at most once a second.
  • accountSubscribe sends account state on change for streamed accounts and nothing for a plain SOL wallet. For a wallet use logsSubscribe mentions plus getBalance. An account that never changes prints no push, and a subscription never notified is refunded at close.
  • getSignaturesForAddress reads an address index that keeps up to 30 days, and getTransaction can answer null for an older signature it lists. The script skips a null.
  • The counters describe one socket, three accounts and 15 seconds. The script stores nothing in Firestore: the Map stands in for the documents.
07

When it goes wrong

what goes wrongwhat to do
The tally shows 0 pushes.The three accounts did not change in the window, or the program was quiet. Run it again, or pass the address of a busier program as the argument. A plain SOL wallet sends nothing over accountSubscribe.
Lines starting getTransaction failed appear and the run still finishes.Read the message. A -32015 means maxSupportedTransactionVersion was left out or set to 0, and the script passes 1. A 429 means the 20 fetches landed too soon after an earlier run, so wait and rerun. The script counts the transactions that did arrive.
A document holds an older state than the chain shows.The write happened outside the transaction, or it compared slots only. Write through runTransaction, compare slot then seq against the document you just read, and check the stored slot against a fresh getAccountInfo context.slot.
A line subscribe failed or socket error appears and no pushes follow.Carbium answers 401 for a key it does not recognise. Attach the whole key in the x-api-key header for reads and as ?api-key= on the socket URL, and check the plan's socket cap if the message names a limit. Free carries 5 sockets.
The line No token accounts found in the sampled transactions. appears and the run stops before the reads.Pass a program whose transactions move tokens, such as an AMM, so the token balances name accounts to follow.
08

Questions

Can one slot bring several pushes for the same account?

On a stock Agave node a subscription gets one push per slot with the end-of-slot state. An equal or lower slot comes from a read meeting a push or from a fork switch. Run the script to see what your own account does.

Why not compare slots alone?

A read and a push can carry the same slot, and a slot-only rule must then drop one of them or apply both in an unknown order. The seq makes the later arrival win, with no extra reads.

Does the same guard work for programSubscribe?

Key it per account. A programNotification names the account in value.pubkey, so each account gets its own document and its own slot and seq.

Why sample 20 signatures?

A sample of 20 transactions usually names a few token accounts that recur, and 20 getTransaction calls at 50 cells fit inside the 1,024-cell burst. A larger sample needs spacing between calls.