Digital wallet
Design a wallet that moves money between users, exactly once, at thousands of transfers a second.
- 1Shard by user, and expect almost every transfer to cross shards. With 16 shards, 15 of 16 do.
- 2A cross-shard transfer is a saga of 5 commits: a hold, a credit, a capture. Each step has a key, and a row on the source shard drives recovery.
- 3The journal is the truth and the balance is a cached projection. Replay proves one against the other.
- 4A hot account is one row. Split it into sub-accounts; shards do not help it. Transit accounts need the same split.
"Design a wallet that moves money between users, exactly once, at thousands of transfers a second."
| question | answer assumed |
|---|---|
| How many users? | 50 million, 5 transfers each a day. |
| Peak? | 3 times the average. |
| Money in and out? | Deposits and payouts run through a provider, as on the payments sheet. |
| Currencies? | One. An FX account handles the others later. |
| Merchants? | Yes. A large merchant takes thousands of credits a second. |
| Daily limits? | Per sender, per UTC day, exact. |
| How long do we keep history? | Years, for audit. A reader must see any past balance. |
| requirement | target |
|---|---|
| Peak transfers | 8,681 a second |
| Each transfer applies | Once, under any retry or crash |
| Total money | Conserved, checked across shards |
| Overdraft | Never, under concurrency |
| Hot merchant | 3,000 credits a second |
| Crash between shards | Finishes without a person |
| Past balances | Readable as of any entry |
Every transfer moves money once, money is never created or lost, and a crash between 2 shards finishes without a person.
- per day
- 50 million × 5 = 250 million transfers
- average
- 250,000,000 ÷ 86,400 s ≈ 2,894 a second
- peak
- 2,894 × 3 ≈ 8,681 a second
- cross share
- 16 shards: 1 - 1/16 = 93.8%
- per shard
- 2,677 a second on 2 shards ≈ 1,339 each
- shards
- 8,681 ÷ 1,339 ≈ 7; take 16, or 21,416 a second
- storage
- 250 million × 1.4 kB ≈ 362 GB a day
Rates and bytes per transfer were measured in the lab: 593 B inside a shard, 1,507 B across, with indexes.
Peak is about 8,700 transfers a second. Almost all cross shards, so I size for the cross-shard rate.
| call | result |
|---|---|
| POST /transfers | To, amount. 200 settled, 202 open, 402 no funds, 403 over the limit, 422 key reused. |
| GET /transfers/:id | State: open, settled, refused, cancelled. |
| GET /users/:id/balance | Balance and available, from the cache. |
| GET /users/:id/entries | History, by cursor. Takes an as-of entry. |
| POST /merchants/:id/payouts | From the main account, after a sweep. |
POST calls take an Idempotency-Key header, unique per sender, kept with the transfer.
A transfer takes an idempotency key per sender. It returns 202 if the saga is still open, and the client polls.
- placement
- Shard by user id. A directory maps ranges to shards.
- transit
- 16 rows on each shard, picked by key. The rows of all shards net to 0.
- money
- bigint cents, one currency per account.
-- A balance per account as of one entry. Replay starts here.
CREATE TABLE snapshots (
upto bigint NOT NULL,
account bigint NOT NULL,
balance bigint NOT NULL,
PRIMARY KEY (upto, account)
);
-- Balance reads and replay walk one account's postings in entry order.
CREATE INDEX postings_by_account ON postings (account_id, entry_id)1;
-- The journal records what happened. No code path may change it.
CREATE FUNCTION journal_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'the journal is append only'
USING ERRCODE = 'restrict_violation';
END $$;
CREATE TRIGGER journal_append_only BEFORE UPDATE OR DELETE ON journal_entries
FOR EACH ROW EXECUTE FUNCTION journal_append_only();
CREATE TRIGGER postings_append_only2 BEFORE UPDATE OR DELETE ON postings
FOR EACH ROW EXECUTE FUNCTION journal_append_only();- 1A history page and a derived balance walk one account in entry order.
- 2The database refuses UPDATE and DELETE, so no code path can rewrite history.
-- These tables sit beside the ledger tables on every shard. A cross-shard
-- transfer has its row on the source shard: the row is the saga log.
CREATE TABLE transfers (
key text PRIMARY KEY, -- <sender>:<client key>
from_user bigint NOT NULL,
to_user bigint NOT NULL,
amount bigint NOT NULL CHECK (amount > 0),
currency char(3) NOT NULL,
state text NOT NULL DEFAULT 'open'
CHECK (state IN ('open', 'settled', 'refused', 'cancelled'))1,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX transfers_open ON transfers (created_at) WHERE state = 'open'2;
-- One row per sender and day. The UPDATE refuses to pass the limit.
CREATE TABLE daily_spend (
user_id bigint NOT NULL,
day date NOT NULL,
spent bigint NOT NULL CHECK (spent >= 0),
PRIMARY KEY (user_id, day)
);
-- One row per transfer that counted, so a retry never counts twice.
CREATE TABLE limit_claims (
key text PRIMARY KEY,3
user_id bigint NOT NULL,
day date NOT NULL,
amount bigint NOT NULL
);- 1Recovery reads the open rows. The steps have their own keys, so the row needs only these 4 states.
- 2A partial index keeps recovery cheap when billions of rows are closed.
- 3A claim per transfer, so a retry never counts twice.
Each shard runs the same ledger. I add a transfer row as the saga log, a daily counter, and snapshots. The journal takes only inserts.
Step 1: Same shard
- Hash the sender and the receiver. Both land on one shard.
- Claim the daily limit, then post one ledger entry.
If it fails
No funds: the CHECK refuses, and the limit comes back. A retry finds the entry key.
The service routes by user. A transfer on one shard is one entry. A transfer across shards is a saga, and recovery finishes any that stop.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Postgres | Unique keys and ON CONFLICT DO NOTHING | Each saga step and each limit claim applies once. | Idempotent APIs |
| Postgres | CHECK balance - held >= 0 | No overdraft and no double spend, under any concurrency. | Stock, seats |
| Postgres | Row locks in id order | Transfers on one shard never deadlock. | Multi-row updates |
| Postgres | Deferred constraint trigger | Every entry sums to 0 at commit. | Rules across rows |
| Postgres | BEFORE UPDATE OR DELETE trigger | An append-only journal. | Audit tables |
| Postgres | Conditional upsert | A daily counter that refuses to pass the limit. | Quotas |
| Postgres | LOCK TABLE IN SHARE MODE, briefly | A snapshot mark that no late commit can pass. | Consistent cuts |
| Postgres | Rollback when a connection ends | A crash inside a step leaves nothing. | Every transaction |
| Postgres | Partial index on open rows | Recovery reads few rows. | Queues, outboxes |
| Service | A stable hash of the key | A retry picks the same sub-account and the same transit row. | Routing |
Postgres gives me balanced entries, unique keys per step, a CHECK that refuses an overdraft, and row locks that order each account.
| balance | read, 100,000 postings | can it drift? | status |
|---|---|---|---|
| Column only | 63 µs | Yes, and nothing notices | Not approved |
| Sum of postings only | 14.8 ms | No | Small histories |
| Both, in one transaction, audited | 63 µs | The audit catches it | Approved |
Median of 101 reads on the lab Postgres. The derived read costs 235 times the cached read, and it grows with history.
cached(account):
read one row // constant cost1
derived(account):
sum every posting of the account // grows with history2- 1The ledger updates this column in the same transaction as the postings, so a reader never sees a half-applied transfer.
- 2An index helps, but each read still visits every posting of the account.
Tested source SQL: both reads
SELECT balance FROM accounts WHERE id = $1;
SELECT coalesce(sum(amount), 0) FROM postings WHERE account_id = $1;I keep both. The journal is the truth. The cached balance reads in about 63 µs at any history, and the audit compares them.
| method | a crash in the middle | status |
|---|---|---|
| Debit, then credit, no log | The money stays in transit, unnoticed | Not approved |
| 2-phase commit | Locks stay until the coordinator returns | Low rate, same operator |
| Saga: debit, credit, refund on failure | The sender sees a debit that reverses | If a reversal is acceptable |
| Saga: hold, credit, capture | No debit until the credit landed | Approved |
| Move the 2 users to one shard | No saga, if they stay together | Closed groups only |
single(key, from, to, amount):
COMMIT claim the daily limit
COMMIT one entry, key = client key1
no funds: give the limit back2, refused- 1The whole money movement is one transaction, so no saga and no transit.
- 2A crash between the 2 commits counts against the limit until the client retries: the safe side.
Tested source Go: single
// single is one ledger entry on one shard. The limit commits first; if the post then fails for a
// business reason, the limit is given back. A crash between the two counts against the limit
// until the client retries, which is the safe side.
func (c *Cluster) single(ctx context.Context, key string, r Req) (string, error) {
s := c.shard(r.From)
err := pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error { return c.claimLimit(ctx, tx, key, r) })
if err != nil {
return "", err
}
e := ledger.Entry{Key: key, Kind: "transfer", Currency: "USD", Legs: []ledger.Leg{
{Account: r.From, Amount: -r.Amount}, {Account: c.payee(r.To, key), Amount: r.Amount}}}
_, err = s.Post(ctx, e)
if errors.Is(err, ledger.ErrInsufficientFunds) || errors.Is(err, ledger.ErrNoAccount) {
if _, gbErr := s.DB.Exec(ctx, q["give_back"], key); gbErr != nil {
return "", fmt.Errorf("give back limit: %w", gbErr)
}
return Refused, nil
}
if errors.Is(err, ledger.ErrKeyReused) {
return "", fmt.Errorf("%w: %q", ErrKeyReused, r.Key)
}
if err != nil {
return "", err
}
return Settled, nil
}
run(transfer): // start and resume are one call1
hold on the sender, key hold:<k>2
no funds: close refused, STOP
IF the other shard is silent: STOP // stays open3
post credit, key credit:<k>
no such account4: release, cancelled, STOP
capture the hold, key debit:<k>5
close settled- 1Recovery needs no special path, so the common path tests it every day.
- 2The hold key comes from the transfer key. A rerun finds the hold.
- 3A timeout says nothing about the credit. Cancelling on silence could create money.
- 4A refusal is an answer. The hold is released, and no entry exists on either shard.
- 5The capture moves the money into transit on shard A, opposite to the transit credit on shard B.
Tested source Go: the saga · Go: capture, from the money sheet · SQL: the transfer row
// run takes a transfer forward from wherever it stands. Every step has its own key, so a step
// that already committed changes nothing. A refusal is final and ends the saga. A timeout is not
// a refusal: the transfer stays open and recovery tries again, because the credit may have
// landed. Only an answer from the other shard may cancel.
func (c *Cluster) run(ctx context.Context, t transfer, crashAt string, inCredit ledger.Fault) (string, error) {
a, b := c.shard(t.from), c.shard(t.to)
holdID, err := a.Hold(ctx, t.from, t.amount, "hold:"+t.key)
if errors.Is(err, ledger.ErrInsufficientFunds) {
return c.finish(ctx, t, Refused)
}
if err != nil {
return "", fmt.Errorf("hold %s: %w", t.key, err)
}
c.saw(t, AfterHold)
if crashAt == AfterHold {
return "", ErrCrashed
}
if c.Down[c.ShardOf(t.to)] {
return "", fmt.Errorf("%w: credit %s", ErrShardDown, t.key)
}
_, err = b.Post(ctx, ledger.Entry{Key: "credit:" + t.key, Kind: "credit", Currency: t.currency, Fault: inCredit, Legs: []ledger.Leg{
{Account: c.transit(t.key), Amount: -t.amount}, {Account: c.payee(t.to, t.key), Amount: t.amount}}})
if errors.Is(err, ledger.ErrNoAccount) {
if _, err := a.Release(ctx, holdID); err != nil {
return "", fmt.Errorf("release %s: %w", t.key, err)
}
c.saw(t, Released)
return c.finish(ctx, t, Cancelled)
}
if err != nil {
return "", fmt.Errorf("credit %s: %w", t.key, err)
}
c.saw(t, AfterCredit)
if crashAt == AfterCredit {
return "", ErrCrashed
}
if _, err := a.Capture(ctx, holdID, c.transit(t.key), t.amount, "debit:"+t.key, t.currency); err != nil {
return "", fmt.Errorf("capture %s: %w", t.key, err)
}
c.saw(t, AfterCapture)
if crashAt == AfterCapture {
return "", ErrCrashed
}
return c.finish(ctx, t, Settled)
}
// finish closes the transfer. A refused or cancelled transfer gives its limit back.
func (c *Cluster) finish(ctx context.Context, t transfer, state string) (string, error) {
err := pgx.BeginFunc(ctx, c.shard(t.from).DB, func(tx pgx.Tx) error {
tag, err := tx.Exec(ctx, q["close_transfer"], t.key, state)
if err != nil {
return fmt.Errorf("close transfer: %w", err)
}
if tag.RowsAffected() == 1 && state != Settled {
if _, err := tx.Exec(ctx, q["give_back"], t.key); err != nil {
return fmt.Errorf("give back limit: %w", err)
}
}
return nil
})
c.saw(t, state)
return state, err
}
// Capture closes a hold and moves amount, at most the held amount, to another account. The rest
// of the hold returns to the available balance.
func (l *Ledger) Capture(ctx context.Context, holdID, to, amount int64, key, currency string) (Result, error) {
return l.run(ctx, NoFault, func(tx pgx.Tx) (Result, error) {
var from, held int64
if err := tx.QueryRow(ctx, q["read_hold"], holdID).Scan(&from, &held); err != nil {
return Result{}, fmt.Errorf("read hold %d: %w", holdID, err)
}
if amount <= 0 || amount > held {
return Result{}, fmt.Errorf("%w: %d of %d", ErrOverCapture, amount, held)
}
e := Entry{Key: key, Kind: "capture", Currency: currency, Legs: []Leg{{from, -amount}, {to, amount}}}
res, err := claim(ctx, tx, e)
if err != nil || res.Replayed {
return res, err
}
if err := l.lock(ctx, tx, e); err != nil {
return Result{}, err
}
if err := tx.QueryRow(ctx, q["close_hold"], holdID, "captured").Scan(&from, &held); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return Result{}, fmt.Errorf("%w: hold %d", ErrHoldClosed, holdID)
}
return Result{}, fmt.Errorf("close hold %d: %w", holdID, err)
}
if _, err := tx.Exec(ctx, q["set_held"], from, -held); err != nil {
return Result{}, fmt.Errorf("lift hold on account %d: %w", from, err)
}
return res, apply(ctx, tx, res.EntryID, e)
})
}
-- 0 rows: a retry or a copy of this transfer.
INSERT INTO transfers (key, from_user, to_user, amount, currency) VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (key) DO NOTHING;
-- Recovery reads these. A grace period leaves a transfer that is still running alone.
SELECT key, from_user, to_user, amount, currency, state FROM transfers
WHERE state = 'open' AND created_at < now() - $1::interval
ORDER BY created_at;
-- 0 rows: another runner closed it first.
UPDATE transfers SET state = $2 WHERE key = $1 AND state = 'open';recover():
FOR each shard:
FOR each open row past the grace period1:
run(transfer)- 1A running transfer stays alone. If 2 runners do meet, the keys make that safe.
Tested source Go: recover
// Recover runs every open transfer older than grace, on every shard. A shard that is still down
// leaves its transfers open for the next pass. It returns how many transfers it closed.
func (c *Cluster) Recover(ctx context.Context, grace time.Duration) (int, error) {
closed := 0
for _, s := range c.Shards {
rows, err := s.DB.Query(ctx, q["open_transfers"], grace.String())
if err != nil {
return closed, fmt.Errorf("read open transfers: %w", err)
}
var t transfer
var open []transfer
if _, err := pgx.ForEachRow(rows, t.dest(), func() error {
open = append(open, t)
return nil
}); err != nil {
return closed, fmt.Errorf("read open transfers: %w", err)
}
for _, t := range open {
_, err := c.run(ctx, t, "", ledger.NoFault)
if errors.Is(err, ErrShardDown) {
continue
}
if err != nil {
return closed, err
}
closed++
}
}
return closed, nil
}
Tested: 6 crash points, each through recovery and through a client retry; 8 recoveries racing; 16 copies at once; a shard down, then back.
I place a hold, credit the other shard, then capture the hold. A row on the source shard lets recovery finish, and only a refusal may cancel.
payee(user, key):
n = sub-accounts of user
IF n = 0: RETURN user
RETURN sub-account hash(key) % n1 // a retry lands on the same one
sweep(user):
one entry2: every sub-account -> main- 1From the key, not at random, so a retry lands on the same sub-account.
- 2The sweep is one balanced entry. Payouts read only the main account.
Tested source Go: pick a sub-account · Go: sweep
// payee picks the account a credit lands on. A hot account has sub-accounts, and the key picks
// one, so a retry lands on the same one.
func (c *Cluster) payee(user int64, key string) int64 {
if n := c.Hot[user]; n > 1 {
return subAccount(user, int(hash(key))%n, len(c.Shards))
}
return user
}
// subAccount stays on the owner's shard: it adds a multiple of the shard count.
func subAccount(user int64, i, shards int) int64 {
return user + int64(shards)*1_000_000*int64(i+1)
}
// Sweep moves each sub-account's balance to the main account in one entry. A payout reads the
// main account, so payouts need no lock on the sub-accounts that take credits.
func (c *Cluster) Sweep(ctx context.Context, user int64, key string) (int64, error) {
s := c.shard(user)
var moved int64
legs := []ledger.Leg{{Account: user}}
for i := range c.Hot[user] {
id := subAccount(user, i, len(c.Shards))
var bal int64
if err := s.DB.QueryRow(ctx, q["cached_balance"], id).Scan(&bal); err != nil {
return 0, fmt.Errorf("read sub-account: %w", err)
}
if bal > 0 {
legs = append(legs, ledger.Leg{Account: id, Amount: -bal})
moved += bal
}
}
if moved == 0 {
return 0, nil
}
legs[0].Amount = moved
if _, err := s.Post(ctx, ledger.Entry{Key: key, Kind: "sweep", Currency: "USD", Legs: legs}); err != nil {
return 0, err
}
return moved, nil
}
| method | rate | status |
|---|---|---|
| One row | 1,300 a second | Not approved |
| 8 sub-accounts, sum for the balance | 5,300 a second | Approved |
| Queue credits, apply in batches | not measured | If the balance may lag |
| Skip row locks with an eventual counter | not measured | Not approved |
| transit accounts | cross-shard rate |
|---|---|
| 1 row on each shard | 940 a second |
| 16 rows, picked by key | 2,700 a second |
Each account row takes one writer at a time, for one commit. The commit time sets the rate of a row.
One row took about 1,300 credits a second and 8 sub-accounts took about 5,300. The transit accounts needed the same split.
snapshot():
BEGIN; lock the journal in SHARE mode1 // waits for writers in flight
mark = newest entry id
COMMIT
store sum of postings up to mark
replay():
balances = latest snapshot
add every posting after the mark2- 1A lower id can commit after a higher id. The lock ends when every writer in flight has finished.
- 2Everything at or below the mark is final, so the tail misses nothing.
Tested source Go: snapshot and replay · SQL: snapshot
// Snapshot stores every balance as of the newest entry and returns that entry's id. Ids come from
// a sequence, so a lower id can commit after a higher one. The brief SHARE lock waits for writers
// in flight, which makes every id at or below the mark final. The sum runs after the lock ends.
func Snapshot(ctx context.Context, s *ledger.Ledger) (int64, error) {
var upto int64
err := pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, q["lock_journal"]); err != nil {
return fmt.Errorf("lock journal: %w", err)
}
return tx.QueryRow(ctx, q["last_entry"]).Scan(&upto)
})
if err != nil {
return 0, fmt.Errorf("mark snapshot: %w", err)
}
if _, err := s.DB.Exec(ctx, q["take_snapshot"], upto); err != nil {
return 0, fmt.Errorf("take snapshot: %w", err)
}
return upto, nil
}
// Replay folds the log into balances: the latest snapshot, then every posting after it. It also
// returns how many postings it read from the tail.
func Replay(ctx context.Context, s *ledger.Ledger) (balances map[int64]int64, tail int, err error) {
var upto int64
if err := s.DB.QueryRow(ctx, q["latest_snapshot"]).Scan(&upto); err != nil {
return nil, 0, fmt.Errorf("find snapshot: %w", err)
}
balances = map[int64]int64{}
var account, amount int64
rows, err := s.DB.Query(ctx, q["read_snapshot"], upto)
if err != nil {
return nil, 0, fmt.Errorf("read snapshot: %w", err)
}
if _, err := pgx.ForEachRow(rows, []any{&account, &amount}, func() error {
balances[account] = amount
return nil
}); err != nil {
return nil, 0, fmt.Errorf("read snapshot: %w", err)
}
rows, err = s.DB.Query(ctx, q["read_tail"], upto)
if err != nil {
return nil, 0, fmt.Errorf("read tail: %w", err)
}
if _, err := pgx.ForEachRow(rows, []any{&account, &amount}, func() error {
balances[account] += amount
tail++
return nil
}); err != nil {
return nil, 0, fmt.Errorf("read tail: %w", err)
}
return balances, tail, nil
}
-- Waits for every writer in flight. A lower id can commit after a higher one, so a max(id) read
-- without this lock can miss an entry that later lands below the snapshot.
LOCK TABLE journal_entries IN SHARE MODE;
SELECT coalesce(max(id), 0) FROM journal_entries;
INSERT INTO snapshots (upto, account, balance)
SELECT $1, account_id, sum(amount) FROM postings WHERE entry_id <= $1 GROUP BY account_id
ON CONFLICT (upto, account) DO NOTHING;| replay | time |
|---|---|
| From the start, 200,000 postings | 87 ms |
| From a snapshot, 1,000 postings in the tail | 0.6 ms |
| Fold rate | 2,300,000 postings a second |
audit():
each shard: entries sum to 0, cache = journal1
users + transit, all shards2 = money funded
no open transfer: transit nets to 03, no holds
each settled row: 1 debit and 1 credit
each refused or cancelled row: no entries- 1A test added $0.01 to a cached balance. The audit reported 1 drifted account, and a rebuild repaired it.
- 2No single shard can see this rule. It needs a read of every shard.
- 3The control below fails here: its money stays in transit with no open row.
Tested source Go: audit
// Audit checks each shard's ledger, then the rules no single shard can check: transit rows net to
// 0, money in user accounts plus transit equals money funded, and each closed transfer has
// exactly the entries its state promises, on both shards.
func (c *Cluster) Audit(ctx context.Context) (Report, error) {
var rep Report
for _, s := range c.Shards {
a, err := s.RunAudit(ctx)
if err != nil {
return rep, err
}
rep.Shards = append(rep.Shards, a)
var transit, funding, owned, held int64
if err := s.DB.QueryRow(ctx, `SELECT
coalesce(sum(balance) FILTER (WHERE id <= $1), 0),
coalesce(sum(balance) FILTER (WHERE id = $2), 0),
coalesce(sum(balance) FILTER (WHERE id >= $3), 0),
coalesce(sum(held), 0) FROM accounts`, TransitRows, Funding, FirstUser).Scan(&transit, &funding, &owned, &held); err != nil {
return rep, fmt.Errorf("sum accounts: %w", err)
}
rep.Transit += transit
rep.Funded -= funding
rep.Owned += owned
rep.OnHold += held
rows, err := s.DB.Query(ctx, "SELECT key, from_user, to_user, amount, currency, state FROM transfers")
if err != nil {
return rep, fmt.Errorf("read transfers: %w", err)
}
var t transfer
var all []transfer
if _, err := pgx.ForEachRow(rows, t.dest(), func() error {
all = append(all, t)
return nil
}); err != nil {
return rep, fmt.Errorf("read transfers: %w", err)
}
for _, t := range all {
rep.Checked++
if t.state == Open {
rep.Open++
continue
}
debit, credit, err := c.entries(ctx, t)
if err != nil {
return rep, err
}
want := 0
if t.state == Settled {
want = 1
}
if debit != want || credit != want {
rep.Mismatched++
}
}
}
return rep, nil
}
Every balance is a fold over the journal. A snapshot makes the replay short, and an audit across shards proves that money is conserved.
claim_limit(key, user, day, amount):
insert claim for key; row exists: STOP // a retry counts once1
add amount to spent for user and day
WHERE spent + amount <= limit2
0 rows: refuse, over the limit- 1The claim key is the transfer key.
- 2The upsert locks the row, so concurrent sends line up and the sum stays exact.
Tested source Go: claim the limit · SQL: spend, give back
// claimLimit counts a transfer against the sender's day, once per key.
func (c *Cluster) claimLimit(ctx context.Context, tx pgx.Tx, key string, r Req) error {
day := r.Day.UTC().Format(time.DateOnly)
tag, err := tx.Exec(ctx, q["claim_limit"], key, r.From, day, r.Amount)
if err != nil {
return fmt.Errorf("claim limit: %w", err)
}
if tag.RowsAffected() == 0 {
return nil // a retry: this key already counted
}
if r.Amount > c.DailyLimit {
return fmt.Errorf("%w: %d over %d", ErrDailyLimit, r.Amount, c.DailyLimit)
}
var spent int64
err = tx.QueryRow(ctx, q["spend"], r.From, day, r.Amount, c.DailyLimit).Scan(&spent)
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%w: user %d", ErrDailyLimit, r.From)
}
if err != nil {
return fmt.Errorf("spend: %w", err)
}
return nil
}
INSERT INTO limit_claims (key, user_id, day, amount) VALUES ($1, $2, $3, $4)
ON CONFLICT (key) DO NOTHING;
-- The WHERE clause refuses a sum over the limit, and the row lock orders concurrent spends.
INSERT INTO daily_spend (user_id, day, spent) VALUES ($1, $2, $3)
ON CONFLICT (user_id, day) DO UPDATE SET spent = daily_spend.spent + $3
WHERE daily_spend.spent + $3 <= $4
RETURNING spent;
-- A refused or cancelled transfer returns its share of the limit, once.
WITH gone AS (DELETE FROM limit_claims WHERE key = $1 RETURNING user_id, day, amount)
UPDATE daily_spend d SET spent = d.spent - g.amount
FROM gone g WHERE d.user_id = g.user_id AND d.day = g.day;| copies come from | stopped by |
|---|---|
| Client retry, double tap | Key per sender: transfer row or entry key |
| Recovery reruns a step | hold:, credit: and debit: keys |
| 2 runners on one transfer | Same keys, and a conditional close |
| A retry after the limit is full | Claim row: this key already counted |
| A key reused for another amount | Compared with the first request: 422 |
Tested: 16 sends of $10 against a $50 limit let exactly 5 through, on one shard and across shards.
The daily counter is a row with a conditional upsert. A claim per transfer means a retry counts once, and a cancelled transfer gives its share back.
Bob has the money and alice's debit is not posted. The hold keeps alice from spending it.
Both shards after this step
shard A
- alice
- $100.00
- on hold
- $0.00
- transit
- $0.00
shard B
- bob
- $100.00
- transit
- $0.00
- transfer row
- none
- spendable
- $200.00
- total
- $200.00
In all 9 recorded runs the total stayed at $200.00 and the audit ended clean. The control with no saga row left $40.00 stuck in transit.
| event | result | why it is safe | saved by |
|---|---|---|---|
| The runner dies after the hold | Money on hold; receiver has nothing. | The open row leads recovery to finish the saga. | Transfer row |
| The runner dies after the credit | Receiver paid; sender not debited. | The hold keeps the sender from spending it; the capture follows. | Hold |
| A crash inside the credit | The connection ends. | Postgres rolls the entry back, and the retry posts it. | Transaction |
| The credit commits, the reply is lost | The runner does not know. | The retry finds the key and posts nothing. | Entry key |
| A shard is down | Transfers wait, open. | Silence never cancels; the hold stays until the shard returns. | Recovery |
| The receiver does not exist | Shard B refuses. | The hold is released, and the limit comes back. | Hold |
| 8 sends spend the same balance | 2 pass, 6 refused. | The CHECK counts holds against the balance. | CHECK |
| A cached balance drifts | The audit reports it. | Rebuild from the journal, which no code path can edit. | Trigger |
| A snapshot runs during writes | It waits for writers in flight. | No entry can commit below its mark afterward. | SHARE lock |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One Postgres ledger. Every transfer is one entry. | About 7,500 transfers a second, spread over many accounts. | Lock waits on one account. |
| 2 | Sub-accounts for hot accounts. | A merchant went from about 1,300 to 5,300 credits a second. | History slows vacuum and backups. |
| 3 | Monthly partitions and snapshots. | Old months move to cheap storage. A replay starts at the snapshot. | The primary nears its write limit. |
| 4 | Shards by user, with the saga and recovery. | About 1,300 cross-shard transfers a second per shard. | Cross-shard rate stalls near 940: lock waits on transit. |
| 5 | 16 transit rows per shard. | 2,700 a second on 2 shards; 21,000 on 16, derived. | Top of the ladder. |
The 2 lab shards are 2 databases on one Postgres server, so they share a disk. The 16-shard figure assumes the rate grows with shards; read it as an order of magnitude.
One shard does about 7,500 transfers a second. Sharding costs a saga, so I split hot rows first and size shards on the cross-shard rate.
| question | answer | deeper |
|---|---|---|
| How does one entry stay exact? | A unique key, accounts locked in id order, and a trigger that refuses an entry that does not sum to 0. | T9 |
| Why not 2-phase commit? | The participants hold locks until the coordinator decides, so a crash blocks hot rows. The saga holds no lock between steps. | T7 |
| How do you move a user to another shard? | Block new transfers for that user, drain open sagas, copy the journal, then flip the directory entry. | X2 |
| Why row locks and not optimistic checks? | A hot row conflicts on nearly every attempt, so retries waste the work. A lock queue is the cheaper order. | T5 |
| How do deposits and payouts work? | Through a provider, as a payment that credits or debits the funding account when it settles. | C19 |
| Can a user read their own transfer right after? | Read balances from the primary of the user's shard. A replica can lag, and a balance must not. | X3 |
| How do you serve statements? | Stream journal entries through an outbox into a read store. The journal stays the truth. | B6 |
0 of 10 known
With 16 shards and users placed at random, what share of transfers cross shards?
Why hold, and not debit first?
A crash comes after the credit and before the capture. What does each user see?
The credit call to shard B times out. May the saga release the hold?
Why does each step need its own key?
What did one transit row cost, and why?
A merchant receives 3,000 credits a second. Why not just add shards?
Why does a snapshot lock the journal?
A cached balance disagrees with the sum of postings. Which one is right?
A transfer is refused after it claimed the daily limit. What happens to the limit?
- peak
- About 8,700 transfers a second.
- cross share
- 93.8% with 16 shards.
- one shard
- About 7,500 transfers a second, 2 commits each.
- 2 shards
- About 2,700 a second, 5 commits each.
- hot row
- About 1,300 a second; 5,300 with 8 sub-accounts.
- balance
- 63 µs cached, 14.8 ms derived at 100,000 postings.
- replay
- About 2,300,000 postings a second.
- bytes
- 593 B inside a shard, 1,507 B across.
Postgres 16 on an 8-core laptop, 32 clients, median of 3 runs of 1 s. Other workloads shared the machine, so use these as orders of magnitude.