Skip to content

Case: Payments and a Balanced Ledger

12 min reading

Separate intended payment, external effect and atomic local accounting under partial failure.

Page details

Work through a complete architecture · Lesson 18

Published · Sources · 12 min reading · Last edited:

Know first: Databases in Ten Minutes: Tables, Indexes, and Transactions.

Editorial correction:

Earlier design notes used unsupported universal performance or reliability claims. This revision explains conditional mechanisms and explicitly hypothetical examples; no author-run benchmark or production incident is asserted.

More
20px

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.

A status column hides several authorities

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.

Keep intent, effects and postings connected

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.

Local intent and external evidence meet at reconciliationThe application records a stable payment intent before an adapter calls the provider. Uncertain results enter a durable unresolved queue. Reconciliation queries provider evidence and applies a legal local state and balanced posting transition. Fulfillment consumes separate durable notification intent and deduplicates its effects.Order + durable intentoperation identityProvider adapterrepeat same intentPayment providerexternal evidenceUnresolved queuereconcile + validateLocal transactionstate + postingsStatus + eventsdeduplicated inputsConfirmed evidence may resolve a pending intention.Fulfillment follows durable intent with its own deduplication.

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.

Derive balanced records and recovery work

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.

Choose the resolution boundary before scaling provider calls. A worker reads the durable unresolved queue, checks the provider's documented evidence and applies a legal local transition with the matching postings. A delivery process then publishes fulfillment intent under its own deduplication contract. The storage-engine chapter explains why logical records alone cannot predict the write bandwidth consumed by maintenance and recovery.

In the wild: Square’s Books models immutable movements

Łukasz Strzałkowski’s report on Square’s Books describes a double-entry service built on Google Cloud Spanner. Journal and book entries preserve movements; corrections add entries instead of overwriting the prior movement. The report distinguishes that history from the mutable current balance of a book.

The transferable idea is the accounting model and its enforcement boundary. It is not evidence that Northwind needs Spanner, that balance alone proves authorization, or that either system can treat a lost provider reply as a failed payment. Priya still needs a view separating confirmed money movement, local postings and unresolved observations.

Balance does not establish business correctness

Two balanced postings can still use the wrong customer, amount or account. Validate identity, currency, authority and the business transition as well as the algebra. Keep currencies separate unless an explicit conversion model and its accounting rules are supplied.

Concurrent reservations or captures need a coordinated limit. Two workers reading the same available amount can each accept work that exceeds it in aggregate. Select the transaction and isolation behavior deliberately; the PostgreSQL isolation chapter is a concrete example of why “uses transactions” is not the entire concurrency argument.

A local outbox can coordinate a recorded state change with intent to notify fulfillment. It cannot atomically include an arbitrary provider. Fulfillment must also deduplicate its effect and understand whether the event represents authorization, capture or another explicitly defined state.

An old webhook arrives after a refund

Hypothetical scenario. A refund completes, then a delayed earlier payment-success event reaches the consumer. A handler that simply assigns the event's status can return the order to paid and trigger fulfillment again.

Apply legal transitions against current state and recorded operation evidence. Preserve event identity and distinguish provider event order from local arrival order. When an event conflicts with known state, investigate or reconcile through the documented provider object rather than choosing the last network arrival as truth.

Use a durable unresolved-work queue with ownership and audit evidence. Sensitive payment material should not be copied into generic logs. A provider-hosted payment interface can reduce some application handling, but does not automatically establish the application's complete security or compliance posture.

Three payment shortcuts to reject

“The request failed, so no charge happened.” Only the relevant operation evidence can establish the effect; a missing response leaves uncertainty.

“Balanced means correct.” Balance is one invariant. Identity, authorization, amount, currency and permitted state transitions remain necessary.

“Webhooks arrive once and in business order.” Design from the provider's actual delivery contract. Repeated or delayed observations must not repeat fulfillment or reverse newer state.

Choose a small authoritative boundary

Keep the internal transaction record, postings and local state transition within one transactional authority when feasible. Separate provider communication and reconciliation as explicit workflow stages. Use stable operation identities at every external effect boundary.

Monitor pending age, mismatched provider/local outcomes, duplicate observations and reconciliation capacity. Test restoration against known transaction identities and invariant checks. A restored database that forgets completed external effects can cause duplicate actions after restart.

Reject a distributed rewrite before the invariant fits a clear local model. Reject universal “exactly once charged” language unless the entire provider and retry contract supports the precise claim. The design review should expose what remains unknown and who may resolve it.

Boundaries of the ledger exercise

Signed posting examples use one currency and a simplified account model, not an organization’s complete chart of accounts or compliance program. A local transaction cannot include an arbitrary provider, and retries depend on that provider’s documented identity and retention rules. Capacity arithmetic excludes physical storage overhead, while restoration must preserve operation identities as well as account totals.

Check yourself: review the payment state machine

The provider call timed out. Should a new payment identity be created?

No automatic new identity follows. Reconcile or retry the same intended operation under the provider's supported contract; preserve unresolved state where the effect cannot be established.

Every transaction sums to zero, but a customer's funds moved to the wrong account. Did the invariant suffice?

No. The algebra did not validate account identity or business authority. Keep those checks alongside atomic balanced posting.

A delayed success event arrives after a confirmed refund. What decides the result?

The legal state machine and operation evidence, not arrival order. Reconcile contradictions and prevent repeated fulfillment.

Two balanced transfers each pass a stale 100-unit balance check and spend 70 units. What else must be enforced?

A coordinated no-overdraft decision. Serialize or conditionally update the relevant available balance as part of the accepted journal transition.

Restored totals match the backup, but provider action references are missing. Is recovery complete?

No. Missing effect identities can cause duplicate provider actions or local journals during replay. Reconcile known actions before resuming writes.

Northwind decision log

Record balanced entries and reconcile external movement.

Persist balanced entries before reporting ledger completion.

Match provider movement with the original action identity.

Go deeper: transaction boundaries and immutable journals