Payments
Design a payment system: take a card, charge exactly once, and keep a ledger that always balances.
- 1A timeout is an unknown outcome. Look the key up at the provider before any retry, and send again only with the same key.
- 2The key travels end to end: client to service, service to provider, service to ledger. Each hop has its own unique key.
- 3Replies, webhooks and lookups pass one gate that only moves a payment forward. Order and copies stop mattering.
- 4The ledger hears about money through an outbox, and a nightly match with the settlement file proves it.
"Design a payment system: take a card, charge exactly once, and keep a ledger that always balances."
| question | answer assumed |
|---|---|
| Do we talk to banks? | No. One provider runs the card network. Others can join behind the same interface. |
| How many payments? | 10 million a day, with a sale peak of 10 times the average. |
| One step or two? | Authorize at checkout, capture when the goods ship. |
| Refunds? | Full and partial, from us or from the provider's dashboard. |
| Do we store cards? | No. The provider vaults them. We keep a token and the last 4 digits. |
| How does the provider report? | A reply, webhooks, a lookup by key, and a nightly settlement file. |
| Provider latency? | About 2 s per call, assumed. Use the provider's own figures. |
| requirement | target |
|---|---|
| Double charges | 0, under any fault the provider makes |
| Ledger balance | Every entry sums to 0, always |
| Peak | 1,157 payments a second |
| Unknown outcomes | Resolved without a person |
| Settlement | Every line matched each night, or a case |
| Card data at rest | None in our systems |
| Audit | Every fact from the provider kept, with its source |
I charge each payment once, whatever the provider does, and a ledger that sums to 0 records every cent.
- average
- 10,000,000 ÷ 86,400 s ≈ 116 a second
- peak
- 116 × 10 ≈ 1,157 a second
- in flight
- 1,157 × 2 calls × 2 s ≈ 4,630 calls open at once
- webhooks in
- 1,157 × 2 ≈ 2,315 a second
- ledger writes
- 1 entry per capture: 1,157 a second at peak
- storage
- 10 million × 2.4 kB = 24 GB a day, 8.8 TB a year
Bytes per payment were measured in the lab, with indexes, in both databases.
The peak is about 1,157 payments a second. The hard part is thousands of calls in flight, so I hold no transaction across a call.
| call | result |
|---|---|
| POST /payments | Token, amount. 201, or 200 for the same key. 422 if the key had another body. |
| POST /payments/:id/authorize | 200 authorized or failed. 202 unknown. |
| POST /payments/:id/capture | Amount. 200, or 202 unknown. 409 wrong state. |
| POST /payments/:id/refunds | Amount. 200, or 202 unknown. 409 wrong state, 422 over the capture. |
| GET /payments/:id | State, amounts, refunds. |
| POST /webhooks/provider | 200 after the commit. 401 bad signature. |
The client makes one key per purchase. The header is Idempotency-Key.
Every POST takes an idempotency key. A timeout at the provider is a 202, not an error: the client polls the state.
- money
- bigint cents. Floats never touch an amount.
- facts
- Kept forever: they are the audit of what the provider said.
- growth
- About 2.4 kB per payment. Partition facts and calls by month.
-- Everything the provider told us, by any path. The primary key drops a copy.
CREATE TABLE provider_facts (
id text PRIMARY KEY1, -- webhook event id, reply:<key>, lookup:<key>
seq bigint GENERATED ALWAYS AS IDENTITY,
payment_id bigint NOT NULL REFERENCES payments (id),
source text NOT NULL CHECK (source IN ('reply', 'webhook', 'lookup')),
op text NOT NULL,
outcome text NOT NULL,
call_key text NOT NULL,
ref text NOT NULL,
target text NOT NULL,
amount bigint NOT NULL,
status text NOT NULL DEFAULT 'new'
CHECK (status IN ('new', 'parked', 'applied', 'stale'))
);
CREATE INDEX provider_facts_open ON provider_facts (payment_id)
WHERE status IN ('new', 'parked');
-- Commits with the state change. The relay copies it to the ledger.
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
key text NOT NULL UNIQUE2, -- the ledger entry's key
kind text NOT NULL CHECK (kind IN ('capture', 'refund')),
merchant_id bigint NOT NULL,
amount bigint NOT NULL,
currency char(3) NOT NULL,
external_ref text NOT NULL, -- matched at reconciliation
published_at timestamptz
);
CREATE INDEX outbox_unsent ON outbox (id) WHERE published_at IS NULL;
CREATE TABLE settlement_lines (
ref text PRIMARY KEY,
file text NOT NULL,
amount bigint NOT NULL
);
-- What the nightly match could not explain. A person works these.
CREATE TABLE recon_cases (
ref text PRIMARY KEY,
result text NOT NULL
);- 1A second copy of an event hits this key and is dropped.
- 2The key the relay gives the ledger. The last hop of exactly-once.
-- The card number never reaches these tables. The browser sends it to the
-- provider and gets a token. Amounts are integer minor units (cents).
CREATE TABLE payments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
client_key text NOT NULL UNIQUE1, -- the client's Idempotency-Key
fingerprint text NOT NULL, -- the request it was first used for
merchant_id bigint NOT NULL,
token text NOT NULL, -- the provider's token for the card
card_last4 char(4) NOT NULL, -- enough for a receipt
amount bigint NOT NULL CHECK (amount > 0),
currency char(3) NOT NULL,
state text NOT NULL DEFAULT 'created' CHECK (state IN
('created', 'authorized', 'captured', 'refunded', 'failed')),
auth_ref text, -- the provider's authorization id
capture_ref text, -- the provider's capture id
captured bigint NOT NULL DEFAULT 0,
refunded bigint NOT NULL DEFAULT 0, -- confirmed by the provider
refund_held bigint NOT NULL DEFAULT 0, -- asked for, not confirmed yet
CHECK (captured <= amount),
CONSTRAINT refund_limit CHECK (refunded + refund_held <= captured)2
);
-- One row per provider call, committed before the call. The key comes from
-- our row, so a retry sends the same key and a crash leaves a row to resolve.
CREATE TABLE provider_calls (
key text PRIMARY KEY,
payment_id bigint NOT NULL REFERENCES payments (id),
op text NOT NULL
CHECK (op IN ('authorize', 'capture', 'refund')),
amount bigint NOT NULL,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'done'))3,
attempts int NOT NULL DEFAULT 1,
next_try_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX provider_calls_due ON provider_calls (next_try_at)
WHERE status = 'pending';
CREATE TABLE refunds (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
client_key text UNIQUE, -- NULL when the provider's dashboard started it
call_key text UNIQUE, -- the provider's idempotency key
payment_id bigint NOT NULL REFERENCES payments (id),
amount bigint NOT NULL CHECK (amount > 0),
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'succeeded', 'failed')),
provider_ref text UNIQUE
);- 1The first hop of the key: a copy of the request finds this row.
- 2Confirmed refunds plus asked refunds never pass the capture, whatever the concurrency.
- 3A pending row means a call may have happened. The sweeper reads these.
A payment has one intent row per provider call and one fact row per report. The outbox commits with the state, and the ledger is a separate database.
Step 1: Create
- The browser sends the card to the hosted field and gets a token.
- POST the token, the amount and an Idempotency-Key. The unique client key makes one row.
If it fails
A copy of the request finds the first row and returns it. A card number in the request is refused.
The service calls the provider with no transaction open. Three kinds of report reach one gate, and a relay feeds the ledger.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Postgres | Unique keys and ON CONFLICT DO NOTHING | One payment, one intent, one fact, one outbox event per key. | Idempotent APIs |
| Postgres | SELECT FOR UPDATE on the payment | Facts for one payment apply one at a time. | Per-entity ordering |
| Postgres | A transaction across rows | State, fact and outbox event commit together. | Every multi-row change |
| Postgres | CHECK constraints | Refunds stay within the capture; the state is one of 5 values. | Balances, stock |
| Postgres | FOR UPDATE SKIP LOCKED | N relays share the outbox. | Job queues |
| Postgres | Partial indexes | Pending calls and unsent events stay cheap to find. | Queues, outboxes |
| Postgres | Deferred constraint trigger | Every ledger entry sums to 0 at commit. | Rules across rows |
| Postgres | FULL OUTER JOIN | Matches the settlement file with the ledger, both ways. | Any reconciliation |
| Service | HMAC check in constant time | A forged webhook cannot move a payment. | Signed callbacks |
| Provider | Idempotency keys, for a window | A copy of a call inside the window applies once. | Any external write |
| Provider | Lookup by key | Turns an unknown outcome into a known one. | Any timeout |
| Provider | Tokens, hosted card field | Card data stays out of our systems. | PCI scope |
| Provider | Settlement file | An independent record of the money. | Audit |
Postgres gives me unique keys at every hop, a row lock that orders facts, and an outbox that commits with the state. The provider gives me keys, a lookup and a file.
| fact | from | to | ledger |
|---|---|---|---|
| authorized | created | authorized | nothing |
| declined | created | failed | nothing |
| captured | created, authorized | captured | clearing to merchant |
| capture refused | authorized | failed | nothing |
| refund | captured | captured | merchant to clearing |
| last refund | captured | refunded | merchant to clearing |
| any fact, any other state | any | no change | nothing |
A refund that arrives while the state is created or authorized is parked, not refused.
Authorize places a hold and moves no money. Capture moves money and writes the ledger. A partial refund leaves the state at captured.
| hop | key | stops |
|---|---|---|
| Client to service | Idempotency-Key | Double click, 2 tabs, a retry after a timeout |
| Service to provider | auth:<id>, capture:<id>, refund:<id> | A resend after a timeout, a slow request |
| Provider to service | event id | Webhook copies |
| Service to ledger | capture:<id>, refund:<ref> | A relay that crashed before its mark |
| Provider file to ledger | provider ref | A file loaded twice |
| design without a rule | holds | charges | taken |
|---|---|---|---|
| Client sends no key: 2 tabs make 2 payments | 2 | 2 | $200.00 |
| Service retries a timeout with a new key | 2 | 0 | $0.00 |
| Service retries with the same key after the window, no lookup | 2 | 0 | $0.00 |
Recorded controls against the fake provider. A hold on a card lowers the customer's credit until it expires, so 2 holds are a defect even with 0 charges.
perform(call):
key = derived from our row1 // auth:<payment id>
COMMIT intent row2, status pending
IF the row exists: STOP // a copy of this request3
outcome = provider(call, key) // no transaction open4
IF timeout: answer 202, STOP // the intent stays pending
report(reply) // through the gate- 1Not a random value per attempt. Every retry, from any process, sends the same key.
- 2It commits before the call, so a crash cannot hide a call.
- 3A second tab gets no second call. It reads the state.
- 4At peak about 4,630 calls are open. A transaction per call would hold a connection and a row lock for seconds.
Tested source Go: perform · Go: the provider interface · SQL: intent
// perform commits an intent, calls the provider with no transaction open, and passes the reply
// through the gate. If the intent exists, this request is a copy and sends nothing.
func (s *Service) perform(ctx context.Context, c Call) (Payment, error) {
tag, err := s.DB.Exec(ctx, q["intent"], c.Key, c.Payment, c.Op, c.Amount, s.Grace.String())
if err != nil {
return Payment{}, fmt.Errorf("write intent %s: %w", c.Key, err)
}
if tag.RowsAffected() == 0 {
return s.Get(ctx, c.Payment)
}
if s.CrashAfterIntent {
s.CrashAfterIntent = false
return Payment{}, ErrCrashed
}
if err := s.send(ctx, c); err != nil {
return Payment{}, err
}
return s.Get(ctx, c.Payment)
}
func (s *Service) send(ctx context.Context, c Call) error {
out, err := s.dial(ctx, c)
if errors.Is(err, ErrTimeout) {
return fmt.Errorf("%w: %s", ErrUnknown, c.Key) // the intent stays pending
}
if err != nil {
return fmt.Errorf("call %s: %w", c.Key, err)
}
if s.CrashAfterCall {
s.CrashAfterCall = false
return ErrCrashed
}
_, err = s.Report(ctx, Fact{ID: "reply:" + c.Key, Source: "reply", Outcome: out})
return err
}
// Provider is what the service needs from a card provider. Each call carries a key the provider
// keeps for a limited window. A timeout returns ErrTimeout and says nothing about the outcome.
type Provider interface {
Authorize(ctx context.Context, c Call) (Outcome, error)
Capture(ctx context.Context, c Call) (Outcome, error)
Refund(ctx context.Context, c Call) (Outcome, error)
// Lookup returns the outcome of the call with this key, or ErrNotFound.
Lookup(ctx context.Context, key string) (Outcome, error)
}
-- Commit this before the call. 0 rows: the call was already made or is in flight.
INSERT INTO provider_calls (key, payment_id, op, amount, next_try_at)
VALUES ($1, $2, $3, $4, now() + $5::interval)
ON CONFLICT (key) DO NOTHING;| retry method | status |
|---|---|
| New key per attempt | Not approved |
| Same key, blind retry | Inside the window |
| Key from our row, lookup first | Approved |
The client key makes one payment. A key derived from our row makes one provider call. The entry key makes one ledger entry.
resolve():
FOR each pending call past its lease1:
found = provider.lookup(key)
IF found: report(found) // send nothing2
IF not found: send with the same key3
IF the lookup timed out: try next sweep- 1A lease stops 2 sweepers and a running call from working on the same row.
- 2The provider already acted. The gate records the outcome.
- 3The first copy may still land. The key makes it a copy, not a second call.
Tested source Go: resolve · SQL: claim due calls
// Resolve works every call whose outcome is unknown. It asks the provider first: a key can pass
// out of the provider's window, and a blind retry after that charges again. Only a call the
// provider has no record of is sent again, with the same key, in case the first copy is still
// on its way. It returns how many calls reached a final outcome.
func (s *Service) Resolve(ctx context.Context) (int, error) {
rows, err := s.DB.Query(ctx, q["claim_due"], s.Lease.String())
if err != nil {
return 0, fmt.Errorf("claim calls: %w", err)
}
var due []Call
var c Call
var auth, capture *string
if _, err := pgx.ForEachRow(rows, []any{&c.Key, &c.Op, &c.Payment, &c.Amount, &c.Token, &c.Currency, &auth, &capture}, func() error {
call := c
if c.Op == OpCapture && auth != nil {
call.Target = *auth
}
if c.Op == OpRefund && capture != nil {
call.Target = *capture
}
if c.Op != OpAuthorize {
call.Token = ""
}
due = append(due, call)
return nil
}); err != nil {
return 0, fmt.Errorf("claim calls: %w", err)
}
resolved := 0
for _, c := range due {
out, err := s.Provider.Lookup(ctx, c.Key)
switch {
case errors.Is(err, ErrTimeout):
continue // still unknown: the next sweep tries again
case errors.Is(err, ErrNotFound):
if err := s.send(ctx, c); errors.Is(err, ErrUnknown) {
continue
} else if err != nil {
return resolved, err
}
case err != nil:
return resolved, fmt.Errorf("look up %s: %w", c.Key, err)
default:
if _, err := s.Report(ctx, Fact{ID: "lookup:" + c.Key, Source: "lookup", Outcome: out}); err != nil {
return resolved, err
}
}
resolved++
}
return resolved, nil
}
-- A sweeper claims a call for one lease, so 2 sweepers do not work on the same call.
UPDATE provider_calls c
SET attempts = attempts + 1, next_try_at = now() + $1::interval
FROM payments p
WHERE p.id = c.payment_id AND c.status = 'pending' AND c.next_try_at <= now()
RETURNING c.key, c.op, c.payment_id, c.amount, p.token, p.currency, p.auth_ref, p.capture_ref;| on a timeout | status |
|---|---|
| Mark the payment failed | Not approved |
| Show the customer an error, ask to pay again | Not approved |
| Wait for a webhook only | Not approved |
| Answer 202, then look up, then resend with the same key | Approved |
Tested: each of 3 faults on each of 3 calls, and a crash at 2 points around each call. Each case ends with one effect at the provider.
A timeout does not mean failed. I look the key up first, because the provider may have charged, and I send again only if it has no record.
report(fact):
BEGIN
lock the payment row1
insert fact; id seen: duplicate2, STOP
FOR each open fact, parents first3:
apply: move the state forward, or
stale4: the payment moved past it
parked: its parent has not arrived
a capture or refund writes the outbox
close the provider call5
COMMIT- 1Reports for one payment line up here. Reports for other payments run in parallel.
- 2The id is the primary key of the fact table.
- 3An authorization, then a capture, then refunds. A parked refund runs in the transaction that brings its capture.
- 4The fact is kept for the audit and changes nothing.
- 5A webhook closes a pending call, so the sweeper has less work.
Tested source Go: the gate · Go: webhook · SQL: open facts
// Report is the gate. Replies, webhooks and lookups all pass through it, one at a time per
// payment. It stores the fact, then applies every open fact of the payment, parents first.
func (s *Service) Report(ctx context.Context, f Fact) (verdict string, err error) {
err = pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
var p Payment
if err := tx.QueryRow(ctx, q["lock_payment"], f.Payment).Scan(p.dest()...); err != nil {
return fmt.Errorf("lock payment %d: %w", f.Payment, err)
}
tag, err := tx.Exec(ctx, q["put_fact"], f.ID, f.Payment, f.Source, f.Op, f.Status, f.Key, f.Ref, f.Target, f.Amount)
if err != nil {
return fmt.Errorf("store fact %s: %w", f.ID, err)
}
if tag.RowsAffected() == 0 {
verdict = Duplicate
return nil
}
rows, err := tx.Query(ctx, q["open_facts"], f.Payment)
if err != nil {
return fmt.Errorf("read open facts: %w", err)
}
open, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Fact, error) {
var o Fact
err := r.Scan(&o.ID, &o.Source, &o.Op, &o.Status, &o.Key, &o.Ref, &o.Target, &o.Amount)
o.Payment = f.Payment
return o, err
})
if err != nil {
return fmt.Errorf("read open facts: %w", err)
}
for _, o := range open {
v, err := s.apply(ctx, tx, &p, o)
if err != nil {
return err
}
if _, err := tx.Exec(ctx, q["set_fact"], o.ID, v); err != nil {
return fmt.Errorf("mark fact %s: %w", o.ID, err)
}
if v != Parked {
if _, err := tx.Exec(ctx, q["call_done"], o.Key); err != nil {
return fmt.Errorf("close call %s: %w", o.Key, err)
}
}
if o.ID == f.ID {
verdict = v
}
}
return s.save(ctx, tx, &p)
})
return verdict, err
}
// apply moves the payment forward by one fact, or leaves it alone. No fact moves a payment back.
func (s *Service) apply(ctx context.Context, tx pgx.Tx, p *Payment, f Fact) (string, error) {
switch {
case f.Op == OpAuthorize && f.Status == Succeeded:
p.AuthRef = f.Ref
if p.State != Created {
return Stale, nil
}
p.State = Authorized
case f.Op == OpAuthorize:
if p.State != Created {
return Stale, nil
}
p.State = Failed
case f.Op == OpCapture && f.Status == Succeeded:
if p.State != Created && p.State != Authorized {
return Stale, nil
}
p.State, p.Captured, p.CaptureRef = Captured, f.Amount, f.Ref
return Applied, s.emit(ctx, tx, "capture:"+strconv.FormatInt(p.ID, 10), "capture", p, f)
case f.Op == OpCapture:
if p.State != Authorized {
return Stale, nil
}
p.State = Failed
case f.Op == OpRefund && (p.State == Created || p.State == Authorized):
return Parked, nil // the capture has not reached us yet
case f.Op == OpRefund && p.State == Failed:
return Stale, nil
case f.Op == OpRefund:
return s.applyRefund(ctx, tx, p, f)
}
return Applied, nil
}
// HandleWebhook checks the signature and passes the event through the gate. The caller answers
// 200 only after this returns, so the provider sends it again if the commit failed.
func (s *Service) HandleWebhook(ctx context.Context, body []byte, sig string) (string, error) {
if !hmac.Equal([]byte(sig), []byte(signature(s.Secret, body))) {
return "", ErrBadSignature
}
var e Event
if err := json.Unmarshal(body, &e); err != nil {
return "", fmt.Errorf("decode webhook: %w", err)
}
return s.Report(ctx, Fact{ID: e.ID, Source: "webhook", Outcome: e.Outcome})
}
-- One fact at a time per payment. Replies, webhooks and lookups all queue on this row.
SELECT id, merchant_id, token, amount, currency, state, coalesce(auth_ref, ''),
coalesce(capture_ref, ''), captured, refunded, refund_held
FROM payments WHERE id = $1 FOR UPDATE;
INSERT INTO provider_facts (id, payment_id, source, op, outcome, call_key, ref, target, amount)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (id) DO NOTHING;
-- Parents first: an authorization, then a capture, then refunds, in arrival order.
SELECT id, source, op, outcome, call_key, ref, target, amount
FROM provider_facts
WHERE payment_id = $1 AND status IN ('new', 'parked')
ORDER BY CASE op WHEN 'authorize' THEN 0 WHEN 'capture' THEN 1 ELSE 2 END, seq;| arrival | verdict | effect |
|---|---|---|
| First report of a fact | applied | State moves; outbox if money moved |
| A copy of an event | duplicate | Nothing |
| Reply after the webhook | stale | Nothing |
| Authorized after captured | stale | Stores the auth ref |
| Refund before capture | parked | Applies when the capture arrives |
| Bad signature | refused | 401, no row |
| order handling | status |
|---|---|
| Apply in arrival order | Not approved |
| Trust a sequence number from the provider | If it has one |
| Refuse an early event, so it is sent again | Retries are bounded |
| Store every fact, apply by a fixed rank | Approved |
Tested: all 24 orders of 4 events, then 300 random orders with copies. Each one ended in the same row and the same money.
A webhook is a report, not a command. It passes the same gate as a reply, so a copy is dropped, a late event is stale and an early refund waits.
relay(batch):
BEGIN
events = oldest unsent, SKIP LOCKED1
post each to the ledger, key = event key2
mark them published
COMMIT // a crash sends them again3- 1N relays take different events.
- 2The ledger returns the first entry for a key it has seen.
- 3The post and the mark are in 2 databases, so delivery is at least once. The key gives one effect.
Tested source Go: relay · SQL: outbox
// Relay copies up to n outbox events to the ledger and returns how many it posted. Delivery is at
// least once: a crash before the commit sends the same events again. The entry key makes a copy
// change nothing, so the ledger applies each event once.
func (s *Service) Relay(ctx context.Context, n int) (sent int, err error) {
err = pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
rows, err := tx.Query(ctx, q["next_events"], n)
if err != nil {
return fmt.Errorf("read outbox: %w", err)
}
var ev event
var ids []int64
var entries []ledger.Entry
if _, err := pgx.ForEachRow(rows, []any{&ev.id, &ev.key, &ev.kind, &ev.merchant, &ev.amount, &ev.currency, &ev.ref}, func() error {
ids = append(ids, ev.id)
entries = append(entries, ev.entry(s.clearing(ev.ref)))
return nil
}); err != nil {
return fmt.Errorf("read outbox: %w", err)
}
for _, e := range entries {
if _, err := s.Ledger.Post(ctx, e); err != nil {
return fmt.Errorf("post %s: %w", e.Key, err)
}
}
if s.CrashAfterPost && len(ids) > 0 {
s.CrashAfterPost = false
return ErrRelayCrashed // the marks roll back: the events stay unsent
}
if _, err := tx.Exec(ctx, q["mark_published"], ids); err != nil {
return fmt.Errorf("mark published: %w", err)
}
sent = len(ids)
return nil
})
return sent, err
}
-- The same transaction as the state change: the event exists if and only if the change does.
INSERT INTO outbox (key, kind, merchant_id, amount, currency, external_ref)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (key) DO NOTHING;
SELECT id, key, kind, merchant_id, amount, currency, external_ref
FROM outbox
WHERE published_at IS NULL
ORDER BY id
LIMIT $1
FOR UPDATE SKIP LOCKED;
UPDATE outbox SET published_at = now() WHERE id = ANY($1);nightly(file):
load lines; a seen ref changes nothing
match all files with the ledger, both ways1
IF a line is missing in the ledger:
resolve open calls2, drain the outbox
match again
what is left becomes a case3- 1A full outer join shows lines each side lacks. An inner join hides them.
- 2A lost reply and a lost webhook leave a pending call. The file reveals it, and the sweeper closes it.
- 3A person works it. The job never edits the ledger to force a match.
Tested source Go: reconcile
// Reconcile loads a settlement file and matches every file so far with the ledger, both ways. A
// line missing in the ledger means a fact never reached us, so it resolves open calls, drains
// the outbox and matches again. What is left becomes a case. A capture missing at the provider
// is a timing difference until a later file carries it.
func (s *Service) Reconcile(ctx context.Context, file string, lines []ledger.ReportRow) (ReconReport, error) {
var rep ReconReport
for _, l := range lines {
if _, err := s.DB.Exec(ctx, q["load_line"], l.Ref, file, l.Amount); err != nil {
return rep, fmt.Errorf("load line %s: %w", l.Ref, err)
}
}
var err error
if rep.First, err = s.match(ctx); err != nil {
return rep, err
}
rep.Final = rep.First
if hasResult(rep.First, "missing in the ledger") {
if rep.Healed, err = s.Resolve(ctx); err != nil {
return rep, err
}
if _, err := s.DrainOutbox(ctx); err != nil {
return rep, err
}
if rep.Final, err = s.match(ctx); err != nil {
return rep, err
}
}
if _, err := s.DB.Exec(ctx, q["clear_cases"]); err != nil {
return rep, fmt.Errorf("clear cases: %w", err)
}
for _, r := range rep.Final {
if r.Result == "matched" {
continue
}
rep.Cases++
if _, err := s.DB.Exec(ctx, q["open_case"], r.Ref, r.Result); err != nil {
return rep, fmt.Errorf("open case %s: %w", r.Ref, err)
}
}
return rep, nil
}
| ref | ledger | file | first match | after repair |
|---|---|---|---|---|
| cap_10 | $30.00 | $30.00 | missing in the ledger | matched |
| cap_13 | $15.00 | none | missing at the provider | missing at the provider |
| cap_3 | $40.00 | $40.00 | matched | matched |
| cap_7 | $25.00 | $24.00 | amounts differ | amounts differ |
| re_4 | -$10.00 | -$10.00 | matched | matched |
Recorded: 1 line repaired by a lookup, 2 left. A capture missing at the provider is a capture after the cut-off; it matches on the next file.
| how to reach the ledger | status |
|---|---|
| Write both databases from the service | Not approved |
| Outbox, relay, entry key | Approved |
| Ledger tables in the payments database | Until the ledger needs its own scale |
The outbox event commits with the state, and the entry key makes the relay safe to repeat. Each night the provider's file proves the ledger right.
| method | card data in our systems | status |
|---|---|---|
| Our form posts the card to our servers | Every service and log on the path | Not approved |
| Our own vault, encrypted | The vault and all that reaches it | Only with a dedicated reason |
| Provider's hosted field, then a token | None | Approved |
Tested: after a full payment, a search of every row finds no card number. PCI DSS applies to systems that store, process or transmit card data. Confirm the exact scope with your assessor.
The card goes from the browser to the provider's hosted field. I store a token and the last 4 digits, so my systems stay out of most of PCI scope.
The provider authorized the card, and the reply was lost. Look it up before any retry.
Each side after this step
- created
- authorized
- captured
- refunded
| service | unknown calls | 0 |
|---|---|---|
| outbox, unsent | 0 | |
| provider | authorizations | 0 |
| charges | 0 | |
| captured, refunded | $0.00, $0.00 | |
| ledger | entries | 0 |
| merchant | $0.00 | |
| sum of postings | $0.00 |
The fake provider lost requests and replies, sent copies and reordered webhooks. Every scenario ended with one charge and a ledger sum of 0.
| event | result | why it is safe | saved by |
|---|---|---|---|
| A provider call times out | Client gets 202; the intent stays pending. | The sweeper looks the key up before it sends anything. | Intent row |
| The key window ends first | The same key would charge again. | The lookup reads records, not keys, so nothing is sent. | Lookup |
| A slow request lands after the resend | 2 copies reach the provider. | Both carry one key inside the window. | Provider key |
| The service dies after the provider replied | The reply is gone. | The pending intent leads the sweeper to the result. | Intent row |
| A webhook arrives 3 times | The first applies. | The event id is a primary key. | Fact key |
| A forged webhook arrives | 401, no row. | The HMAC does not match. | Signature |
| The relay dies after posting | The event is sent again. | The entry key returns the first entry. | Entry key |
| Refund and dashboard refund race | The provider refuses the second. | The refused call frees its hold; the first still applies. | Gate |
| The capture misses the file's cut-off | A line is missing at the provider. | It stays a case until the next file matches it. | Match |
| Every webhook is lost | The sweep or the file finds the gap. | Webhooks speed things up; no money depends on them. | Sweeper |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One Postgres, a separate ledger database, one relay. | About 2,000 payments a second through the service, and 1,000 ledger entries. | The outbox backlog grows at peak. |
| 2 | 16 clearing rows and N relays. The ref picks the row. | About 3,000 entries a second. 8 relays on 1 row gained little. | Facts and calls pass memory; vacuum falls behind. |
| 3 | Monthly partitions of facts, calls and postings. | Old months move to cheap storage. A sweep reads the current month. | One primary nears its write limit. |
| 4 | Shards by merchant, with a ledger per shard. | Each shard adds its own rate. A payment never crosses a merchant. | Top of the ladder. |
Demand, derived: 10,000,000 ÷ 86,400 s ≈ 116 a second; 10 times that at peak. The lab provider has no latency, so the path rate bounds the service and Postgres, not the provider.
One clearing row caps the ledger at about 1,000 entries a second, whatever the number of relays. I split that row before I add any database.
| question | answer | deeper |
|---|---|---|
| How does the ledger stay exact under load? | Each entry claims a unique key, locks accounts in id order, and a trigger refuses an entry that does not sum to 0. | T9 |
| Why not a distributed transaction with the provider? | The provider takes part in no protocol of ours. Idempotent calls plus a lookup give the same effect. | T7 |
| The provider has an outage. What then? | A breaker stops new calls, and pending calls wait for the sweeper. A second provider takes only new payments, never a payment already in flight. | O2 |
| How do you protect webhooks and secrets? | Verify an HMAC in constant time, rotate the secret, and keep tokens scoped to one merchant. | O5 |
| What about provider fees? | The settlement file carries them. Post one entry per file: clearing to bank, plus a fee expense. The match runs on the gross lines. | T9 |
| How do you tell the merchant? | Another consumer reads the same outbox and sends signed webhooks, with retries and a dead-letter queue. | B6 |
| How do you shard? | By merchant, because refunds and reports stay inside one merchant. A directory maps each merchant to a shard. | X2 |
| What locks does the gate take? | One row lock on the payment, held for milliseconds. Two payments never wait for each other, except on a hot ledger row. | T4 |
0 of 10 known
A capture times out. Why not retry at once with the same key?
The lookup says not found. Is it safe to send the call again?
Why commit the intent row before the call and not after?
Why not hold a database transaction across the provider call?
A captured webhook arrives for a payment that is still created. What happens?
A refund webhook arrives before its capture. What happens?
Why an outbox and not a ledger post inside the gate?
The relay posts twice. How many entries does the ledger have?
The settlement file has a capture the ledger lacks. What does the job do?
Two refunds of $60 arrive at once for a $100 capture. How is the second refused?
- peak
- About 1,157 payments a second from 10 million a day.
- in flight
- About 4,630 open calls at 2 s each.
- service path
- About 2,000 payments a second, 32 clients.
- ledger
- About 1,000 entries a second on 1 clearing row, 3,000 on 16.
- storage
- About 2.4 kB per payment, 24 GB a day.
- faults
- 13 scenarios, 300 random webhook orders, a storm of 200 payments: one charge each.
Postgres 16 on an 8-core laptop, a fake provider with no latency, other workloads on the machine. Use these as orders of magnitude.