Part 5 · Blueprint 26
High-Throughput Ledger & Payment Gateway
16 min reading · Sources · Editorial review pending
A network timeout does not tell the ledger whether the provider moved money.
Page details
Published date · Last edited:
Draft edition. Editorial review and supplementary reading recommendations are still being completed.
Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Idempotency Keys & Distributed Retries, Distributed Transactions: 2PC vs. Saga Orchestration, Time, Clocks & Distributed Ordering: Lamport to TrueTime.
Sixty-second mental model
Problem: A network timeout does not tell the ledger whether the provider moved money.
Use: Keep acceptance, provider evidence and reconciliation distinct.
Design boundary: Accept payment intentions, maintain balanced money records and reconcile uncertain provider outcomes. Store integer minor units and currency under a clear money model. A provider timeout is not evidence that a charge failed; a ledger does not make an external service transactional.
Layer 1 · Intuition
Hypothetical scenario: Northwind is designing payment ledgers. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one payment means and which component owns the money-movement ledger.
Think of a journal where every money movement has matching entries. Separate the requester from money-movement ledger, then identify the retained evidence needed after failure.
- Authority
- The entitled state owner.
- Invariant
- A rule preserved across concurrency and failures.
Architecture and worked reasoning
Design boundary: Accept payment intentions, maintain balanced money records and reconcile uncertain provider outcomes. Store integer minor units and currency under a clear money model. A provider timeout is not evidence that a charge failed; a ledger does not make an external service transactional.
Responsibilities on the request path
Domain interface and access patterns
POST /payments with stable operation key → payment_id, state; GET /payments/{id} → evidence-backed outcome
payment_intents(id, tenant_id, operation_key, amount_minor, currency, state); provider_attempts(payment_id, attempt_id, provider_ref, outcome); journal_entries(transfer_id, account_id, signed_amount_minor, currency). Uniqueness binds business intention; balanced entries alone do not deduplicate it.
Workload and limiting resource
A hypothetical transfer of 12,500 cents debits one account by 12,500 and credits another by 12,500, so signed entries sum to zero. A separate fee of 250 cents needs its own specified accounts; silently crediting only 12,250 would lose the fee trail. At 100 transfers/s with four ledger entries/transfer, the store handles 400 entries/s plus indexes and state transitions.
Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.
Mutation or publication path
- Bind request identity to amount, currency and payee.
- Record the intended transition under a guarded state machine.
- Submit or recover the external attempt and append balanced ledger consequences from evidence.
Observation and recovery path
- Read payment state with separate pending/unknown/succeeded/failed meanings.
- Match provider receipts to stable payment and attempt identities.
- Reconcile unresolved attempts without inventing a second customer intention.
Failure that changes the decision
Hypothetical scenario: The provider accepted a charge, but the network response disappeared. Mark the attempt uncertain and query/reconcile its original provider identity. A blind new charge key risks duplicate collection.
Attempt this decision before reading the explanation
Does a balanced ledger prove that no customer was charged twice?
No. Two separately balanced transfers can still represent duplicate business intent. Enforce logical request identity and legal state transitions in addition to balancing entries; compare provider settlement evidence during reconciliation.
Supporting mechanism analysis
Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.
In short. Reconcile external payment evidence before settling local state. Preserve balanced, uniquely identified postings and treat unresolved provider outcomes as work that still has an owner.
The local application owns its order and intended payment operation. The provider owns the evidence about the external payment it processes. A local “failed” value cannot override a provider-confirmed effect, and a provider event does not automatically establish that the correct local order was fulfilled.
Separate requested, authorized, captured, rejected and unresolved states according to the selected provider's actual contract. Authorization and capture may be distinct operations; do not infer one from the other. A timeout is a transport observation, not a final payment state.
Likewise, a refund is another external action with its own identity and outcome. Calling it rollback can conceal that the original charge occurred and that the corrective action can fail or remain pending.
Create a stable payment-operation identity bound to order, actor, amount and currency. Persist intent before invoking the provider, then reuse the provider-supported idempotency identity for attempts of that operation. Reject parameter-changing reuse. Persist confirmed evidence and the corresponding local transition under a suitable transaction.
Use provider events as inputs to a state machine, with authenticated origin, deduplication and object identity checks. A delayed event must not undo a later confirmed state. Where evidence is incomplete, retrieve the provider's documented current status or retain an unresolved case for authorized review.
Stripe's idempotency documentation illustrates why provider details matter: behavior differs across its API versions, and retention and parameter rules constrain reuse. This case does not assume that every provider or version offers the same guarantee.
Northwind chooses Postgres for one local ledger authority. A journal identity names the movement, and its posting rows name the affected accounts and currency. The transaction accepts the complete posting set and its operation identity together. A uniqueness constraint rejects replayed journal identities; the posting procedure verifies the sum before commit. An ordinary per-row CHECK constraint cannot assert a sum across arbitrary rows.
Where spending is bounded by an available balance, the write must coordinate that limit too. Lock the relevant balance rows in a consistent order or use an isolation and retry strategy whose behavior has been tested. Two individually balanced journals can otherwise consume the same available funds. The balance invariant and the spending limit answer different questions, and the service needs both.
Toy concurrent-transfer example. Suppose an account has 100 units available and two workers each propose a 70-unit transfer. Each alone appears affordable because 100 − 70 = 30. Together they require 70 + 70 = 140, exceeding availability by 40. Under the chosen no-overdraft contract, only one can be accepted; after its commit, the other evaluates against 30 and is rejected. Both journals could have summed to zero, so balanced postings alone would not have prevented this conflict.
Preserve a compensating journal rather than editing a completed movement. Keep provider action identity separate from the journal identity, with an explicit link between them. A refund’s payment-provider outcome and its local accounting entry are separate evidence boundaries. Recovery must identify an existing provider effect before deciding whether a missing local journal is safe to create.
Hypothetical scenario. Use a simplified signed-posting convention for one currency: a transfer of 100 units records −100 against one modeled account and +100 against another. Their sum is −100 +100 = 0. The signs define this toy model; they are not a statement about a particular organization's debit/credit chart.
A partial record containing only+100 has sum 100 and violates the chosen balance invariant. Persist both postings and the transaction identity atomically. A row-level amount check alone cannot establish a cross-row sum; PostgreSQL's constraint reference explicitly limits what ordinary check constraints can enforce across rows.
A corrective transfer of 30 units records+30 and−30, again summing to 0. After the original transfer and correction, the first modeled account has−100 +30 = −70 and the second has 100 −30 = 70. Preserving the original and corrective records explains the history more clearly than overwriting 100 with 70.
Choose 1,000 intended purchases. Suppose 900 have confirmed success,80 definite rejection and 20 unresolved outcomes. The counts sum to 1,000. Report 900 confirmed successes and 20 pending cases; do not turn pending into failed or successful to simplify a dashboard.
If reconciliation resolves ten pending cases per minute while two new unresolved cases arrive per minute, net drain is 10 −2 = 8 per minute. A 20-case backlog takes 20 ÷ 8 = 2.5 minutes under constant successful resolution rates. A status query with no conclusive answer does not count as resolution.
Hypothetical scenario. Choose 1,000,000 intended purchases/day. One day contains 24 × 60 × 60 = 86,400 seconds. Average intent arrival is 1,000,000 ÷ 86,400 ≈ 11.57/s. Choose a planning peak of five times that mean: approximately 57.87 intents/s. The multiplier is an assumption to challenge, not a measured traffic profile.
For local sizing, choose a model in which each intent creates one durable intent record. Suppose 900,000 purchases later succeed, and each success creates one confirmation record and two balanced posting records. That is 1,000,000 + 900,000 × (1 + 2) = 3,700,000 logical record insertions/day. Additional updates, indexes, logs, provider observations and outbox rows are excluded. A logical insertion is not one physical I/O operation.
At a chosen 500 bytes of logical retained payload per modeled record, daily growth is 3,700,000 × 500 = 1,850,000,000 bytes, or 1.85 decimal GB. Thirty days retain 55.5 GB; three full payload copies retain 166.5 GB. Actual capacity needs retention rules, log and index overhead, recovery history, backups and measured storage behavior. None of this establishes a hardware TPS figure.
Now choose 2% of all intended purchases as newly unresolved outcomes: 1,000,000 × 0.02 = 20,000/day. Dividing by 24 × 60 = 1,440 minutes/day gives about 13.89/minute on average. If a reconciliation service resolves 30 cases/minute while that arrival rate remains constant, net drain is approximately 30 − 13.89 = 16.11/minute. A 1,000-case backlog drains in about 1,000 ÷ 16.11 = 62.1 minutes. Repeated inconclusive queries do not count as resolved cases, and a peak unresolved arrival above 30/minute reverses this drain.
Layer 3 · Internals
Trade-offs and limits
| Approach | Provides | Requires |
|---|---|---|
| Append-only money-movement journal | Preserves explicit entries and adjustment history. | Balances, reconciliation and account invariants still need enforcement. |
| Materialized account balance | Can make current balance reads inexpensive. | It must remain consistent with accepted movements and cannot replace their evidence. |
Recovery decision
Hypothetical scenario: The provider accepted a charge, but the network response disappeared. Mark the attempt uncertain and query/reconcile its original provider identity. A blind new charge key risks duplicate collection.
No. Two separately balanced transfers can still represent duplicate business intent. Enforce logical request identity and legal state transitions in addition to balancing entries; compare provider settlement evidence during reconciliation.
Write your design before revealing the review
Does a balanced ledger prove that no customer was charged twice?
Drafts and self-review are stored only in this browser. They are separate from reading completion.
Compare your decision
No. Two separately balanced transfers can still represent duplicate business intent. Enforce logical request identity and legal state transitions in addition to balancing entries; compare provider settlement evidence during reconciliation.
The provider accepted a charge, but the network response disappeared. Mark the attempt uncertain and query/reconcile its original provider identity. A blind new charge key risks duplicate collection.
Check your understanding
Does a balanced ledger prove that no customer was charged twice?
No. Two separately balanced transfers can still represent duplicate business intent. Enforce logical request identity and legal state transitions in addition to balancing entries; compare provider settlement evidence during reconciliation.
How would you recover from this failure: The provider accepted a charge, but the network response disappeared. Mark the attempt uncertain and query/reconcile its original provider identity. A blind new charge key risks duplicate collection.
Start with the exact boundary that failed. Bind request identity to amount, currency and payee. Record the intended transition under a guarded state machine. Submit or recover the external attempt and append balanced ledger consequences from evidence. Then recover evidence through the observation path: Read payment state with separate pending/unknown/succeeded/failed meanings. Match provider receipts to stable payment and attempt identities. Reconcile unresolved attempts without inventing a second customer intention. Preserve the distinction between a confirmed state change and an unavailable response.
Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?
A hypothetical transfer of 12,500 cents debits one account by 12,500 and credits another by 12,500, so signed entries sum to zero. A separate fee of 250 cents needs its own specified accounts; silently crediting only 12,250 would lose the fee trail. At 100 transfers/s with four ledger entries/transfer, the store handles 400 entries/s plus indexes and state transitions. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Accept payment intentions, maintain balanced money records and reconcile uncertain provider outcomes. Store integer minor units and currency under a clear money model. A provider timeout is not evidence that a charge failed; a ledger does not make an external service transactional.
Which component in this topology could be removed from a smaller first deployment?
Payment intent, Ledger transaction, Provider adapter, Reconciler name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Bind request identity to amount, currency and payee.
What evidence must a caller have before relying on the observation path?
Read payment state with separate pending/unknown/succeeded/failed meanings. Match provider receipts to stable payment and attempt identities. Reconcile unresolved attempts without inventing a second customer intention. No. Two separately balanced transfers can still represent duplicate business intent. Enforce logical request identity and legal state transitions in addition to balancing entries; compare provider settlement evidence during reconciliation.
45-minute interview rubric
- 00–05: scope payment and money-movement ledger.
- 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
- 12–28: draw money-movement ledger, numbered writes and reads.
- 28–40: challenge recovery: Keep acceptance, provider evidence and reconciliation distinct.
- 40–45: defend payment_id placement, observations and remaining assumptions.
Go deeper
- How Payment Intents and Setup Intents work | Stripe Documentation · Primary document · docs.stripe.com. Keep acceptance, provider evidence and reconciliation distinct. Verified 2026-10-26.
- Books, an immutable double-entry accounting database service · Primary document · developer.squareup.com. Keep acceptance, provider evidence and reconciliation distinct. Verified 2026-10-26.
- Idempotent requests | Stripe API Reference · Primary document · docs.stripe.com. Keep acceptance, provider evidence and reconciliation distinct. Verified 2026-10-26.
- PostgreSQL: Documentation: 17: 5.5. Constraints · Primary document · www.postgresql.org. Keep acceptance, provider evidence and reconciliation distinct. Verified 2026-10-26.
- PostgreSQL: Documentation: 17: 13.2. Transaction Isolation · Primary document · www.postgresql.org. Keep acceptance, provider evidence and reconciliation distinct. Verified 2026-10-26.
Decision log
Keep acceptance, provider evidence and reconciliation distinct.
Preserve payment identity and money-movement ledger ownership.
Revisit changed workload, observations or recovery objectives.