Design a Payment Authorization, Capture, and Settlement Engine
System DesignModel answerLast updated
Architect a resilient payment platform handling two-phase auth/capture flows, double-entry financial ledgering, and batch settlement reconciliation with downstream gateways.
Scenario
Design the core backend services for a payment processing gateway. The platform must handle pay-as-you-go and subscription transactions. This involves reserving funds synchronously (authorizations), processing deferred claims (captures), recording all balance movements in an immutable financial ledger, and assembling daily batch files for settlement and external bank reconciliation.
Requirements
Functional Requirements
- Authorization API (
/v1/payments/authorize): Synchronously validate card details and place a temporary hold on funds for up to 7 days. - Capture API (
/v1/payments/capture): Claim previously authorized funds. Must support full captures, partial captures, and voids (cancellations). - Batch Settlement Generation: Aggregate captured funds into deterministic, bounded settlement files (e.g., ISO 20022 or processor-specific flat files) sent to acquiring institutions.
- Bank Reconciliation: Ingest daily clearing reports from acquirers, matching external settled entries against internal ledger postings and highlighting discrepancies.
- Immutable Double-Entry Ledger: Every balance movement must maintain debits-equal-credits consistency and store a complete audit history.
Non-Functional Requirements
- Strict Idempotency: Duplicate API requests, retries, or worker crashes must never double-charge or double-capture funds.
- Latency:
p99latency under 250ms for authorizations (excluding external processor round-trip time). - Availability & Consistency:
99.999%availability for payment ingestion; strict serializability / strong consistency for balance and ledger states. - Fault Recovery: Robust handling of ambiguous states (e.g., network drop after sending a request to the payment network before receiving a response).
Capacity & Constraints
- Peak authorization throughput: 10,000 transactions per second.
- Daily volume: 50 million total operations (authorizations + captures).
- Settlement window: Daily settlement generation must complete within a 2-hour window, with each file capped at 500,000 records.
Key Focus Areas
- Data Model & Ledger Schemas: Show how transaction states, idempotency keys, and debits/credits are modeled.
- State Machine: Map out the exact payment states (
AUTH_PENDING,AUTHORIZED,CAPTURE_PENDING,CAPTURED,VOIDED,SETTLED,DISCREPANCY). - Failure Handling: Explain how network timeouts and partial failure responses are safely resolved without duplicate charges or lost updates.
- Settlement & Reconciliation Architecture: Describe the batch creation pipeline and report matching logic.
Hints
Hint 1
Ensure idempotency keys are stored in the same database transaction as the initial payment record creation to guarantee shared fate.
Hint 2
Model authorization as a memo hold rather than a cash movement, reserving true double-entry ledger postings for captures and settlements.
Hint 3
Use monotonically increasing sequence numbers per processor to construct deterministic batch settlement files.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Architectural Overview & Scale Analysis
Capacity Calculations
- Throughput: 10,000 peak authorizations/sec. Average throughput for 50M ops/day is ~580 ops/sec, representing a peak-to-average ratio of ~17x.
- Storage (Ledger): Each capture yields 1 double-entry journal entry containing at least 2 ledger lines. At ~200 bytes per record: $$\text{Daily Volume} = 50\text{M captures} \times 2 \text{ lines} \times 200 \text{ bytes} \approx 20\text{ GB/day}$$ Annual storage grows by ~7.3 TB for ledger postings alone.
- Settlement Chunking: 50M daily transactions (assuming ~25M captures) broken into 500k-record files require 50 batch files. Processing 25M records inside a 2-hour window demands a throughput of ~3,472 items/second during the settlement run.
2. System Architecture & Component Design
+-------------------+
| Client App |
+---------+---------+
|
v
+-------------------+
| API Gateway |
+---------+---------+
|
v
+-------------------+
| Payment Service |
+----+----+----+----+
| | |
+------------------+ | +-------------------+
| v |
+------+------+ +-------------------+ +-------+-------+
| Idempotency | | Payments DB | | Processor |
| Engine | | & Ledger | | Adapter |
+-------------+ +-------------------+ +-------+-------+
^ |
| (Outbox Poller) v
+---------+---------+ +---------------+
| Kafka Outbox | | Ext Payment |
+----+----+----+----+ | Network/Bank |
| | | +---------------+
+-------------+ | +-------------+
v v v
+---------------+ +---------------+ +---------------+
| Settlement | | State Resolver| | Auth Expiry |
| Builder | | Worker | | Sweeper |
+-------+-------+ +---------------+ +---------------+
|
v
+---------------+
| Reconciler |
+---------------+
- Payment Service: Stateless worker handling HTTP routing, payload validation, and transaction orchestration.
- Payments Database & Ledger: Sharded OLTP datastore (e.g., PostgreSQL or CockroachDB) enforcing ACID constraints over payment states and ledger tables.
- Idempotency Engine: Integrated directly within the Payment DB to guarantee atomic execution of business logic alongside lock creation.
- Processor Adapter: Translates generic payment requests into bank-/gateway-specific formats (e.g., ISO 8583, Stripe API) using circuit breakers and connection pools.
- State Resolver Worker: Asynchronously polls acquiring networks for payment operations stuck in an ambiguous (
UNKNOWN) state. - Settlement Builder & Reconciler: Asynchronous pipeline that groups captured transactions into signed batch files and matches downstream clearing reports against the internal ledger.
3. Data Model & Double-Entry Ledger Schema
To enforce financial auditability, monetary changes are tracked using an immutable double-entry ledger. Authorizations represent non-monetary holds, while Captures and Settlements reflect actual balance transfers.
-- Payment state projection (Mutable, sharded by payment_id)
CREATE TABLE payments (
payment_id UUID PRIMARY KEY,
merchant_id UUID NOT NULL,
status VARCHAR(32) NOT NULL, -- AUTHORIZED, CAPTURED, VOIDED, etc.
currency VARCHAR(3) NOT NULL,
authorized_minor BIGINT NOT NULL,
captured_minor BIGINT NOT NULL DEFAULT 0,
version INT NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Deduplication table (Co-located on same DB node as payment)
CREATE TABLE idempotency_records (
merchant_id UUID NOT NULL,
endpoint VARCHAR(64) NOT NULL,
idempotency_key VARCHAR(128) NOT NULL,
request_hash CHAR(64) NOT NULL,
status VARCHAR(16) NOT NULL, -- IN_PROGRESS, COMPLETED
response_payload JSONB,
payment_id UUID,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (merchant_id, endpoint, idempotency_key)
);
-- Ledger Header (Immutable)
CREATE TABLE ledger_journals (
journal_id UUID PRIMARY KEY,
payment_id UUID NOT NULL REFERENCES payments(payment_id),
entry_type VARCHAR(32) NOT NULL, -- CAPTURE, SETTLEMENT, REFUND
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Ledger Lines (Immutable)
CREATE TABLE ledger_lines (
line_id UUID PRIMARY KEY,
journal_id UUID NOT NULL REFERENCES ledger_journals(journal_id),
account_id VARCHAR(64) NOT NULL,
direction VARCHAR(2) NOT NULL CHECK (direction IN ('DR', 'CR')),
amount_minor BIGINT NOT NULL CHECK (amount_minor > 0),
currency VARCHAR(3) NOT NULL
);
-- Sequential queue for settlement grouping
CREATE TABLE settlement_items (
settlement_seq BIGSERIAL PRIMARY KEY,
processor_id VARCHAR(32) NOT NULL,
payment_id UUID NOT NULL,
capture_amount BIGINT NOT NULL,
batch_id UUID NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Financial Postings Map
| Event | Debit (DR) | Credit (CR) | Notes |
|---|---|---|---|
| Auth Hold | customer_auth_hold | auth_hold_liability | Memo posting; no cash movement. |
| Capture | processor_receivable | merchant_revenue | Releases auth hold; records formal claim. |
| Settlement | bank_cash <br> processing_fees | processor_receivable | Cash lands in bank; acquiring fees deducted. |
4. Lifecycle State Machine
+--------------+
| (Start Auth) |
+------+-------+
|
v
+--------------+
+---->| AUTH_PENDING |<----+
| +------+-------+ |
| | |
(Retry | v | (Network Drop)
Timeout)| +--------------+ |
+-----| AUTH_UNKNOWN |-----+
+------+-------+
|
+-------------+-------------+
| (Approved) | (Declined)
v v
+--------------+ +--------------+
| AUTHORIZED | | DECLINED |
+------+-------+ +--------------+
|
+-----+-----+
| |
v v
+----+----+ +----+----+
| VOIDED | | EXPIRED |
+---------+ +---------+
|
v (Capture Request)
+------------------+
| CAPTURE_PENDING |
+--------+---------+
|
v
+------------------+
| CAPTURED |
+--------+---------+
|
v (Batch Processing)
+------------------+
| SETTLED |
+--------+---------+
|
v (Reconciliation Check)
+------------------------------------+
| DISCREPANCY / RECONCILED OK |
+------------------------------------+
5. Deep Dives: Reliability & Failure Modes
Robust Idempotency Execution
To handle concurrent API calls and network failures cleanly, state mutations run inside single-database transactions:
- Request Intake: Client passes an
Idempotency-Keyheader. - Transaction Start:
- Attempt insertion into
idempotency_recordswith statusIN_PROGRESS. - If a record exists with state
IN_PROGRESS, return409 Conflict. - If a record exists with state
COMPLETEDand matchingrequest_hash, return savedresponse_payload. - If
request_hashdiffers, return422 Unprocessable Entity.
- Attempt insertion into
- External Action: Execute external API request to acquiring bank using a deterministic gateway key derived as
sha256(payment_id + attempt_seq). - Transaction Finish:
- On success, update
paymentstable status toAUTHORIZED(with optimistic locking checkversion = version + 1). - Write outbox entry for events.
- Update
idempotency_recordsstatus toCOMPLETEDwith response payload. - Commit transaction.
- On success, update
Managing Indeterminate Gateway Outcomes (AUTH_UNKNOWN)
If a call to the acquiring processor hits a read timeout or socket reset:
- Update internal state to
AUTH_UNKNOWNand write an outbox event. - Return a HTTP
202 Acceptedresponse with statusPENDINGto the calling application. - An asynchronous State Resolver worker picks up
AUTH_UNKNOWNrecords:- Queries the gateway's status endpoint using the deterministic request key.
- If approved externally: transition state to
AUTHORIZEDand emit success event. - If absent externally: execute explicit
REVERSALto clean up any latent processor state, then transition internal state toDECLINED.
6. Batch Settlement & Reconciliation Architecture
[ Captured Items Queue ]
|
v
+-------------------------------------------------------+
| Settlement Builder Worker |
| 1. Read unbatched items WHERE settlement_seq <= MAX |
| 2. Group into chunks of 500,000 records |
| 3. Compute SHA-256 header signature |
| 4. Write deterministic batch files |
+-------------------------------------------------------+
|
v
[ Encrypted Storage / SFTP Output ]
|
v (Next Day Ingestion)
+-------------------------------------------------------+
| Reconciliation Engine |
| 1. Parse external bank clearing file (e.g. ISO 20022) |
| 2. Pair external reference IDs to ledger journals |
| 3. Compare amounts, fees, and currency values |
+-------------------------------------------------------+
/ \
/ (Match) \ (Mismatch)
v v
[ Post Cash Journal ] [ Raise Discrepancy Alert ]
Deterministic Settlement Generation
- At the daily cutoff time, capture the maximum sequence ID: $$\text{cutoff_seq} = \max(\text{settlement_seq})$$
- Fetch unassigned items where
settlement_seq <= cutoff_seqordered bysettlement_seq ASC. - Split items into files bounded by 500,000 rows.
- Calculate a file-level hash: $$\text{batch_hash} = \text{HMAC-SHA256}(\text{ProcessorID} + \text{Date} + \text{StartSeq} + \text{EndSeq})$$
- Transmit the resulting settlement file to the processor via secure channel (SFTP / mTLS API). Because ordering is tied to
settlement_seq, regenerating a batch file yields an exact byte-for-byte match.
Bank Reconciliation Pipeline
- Ingestion: Parse bank clearing file (e.g., ISO 20022
camt.053or NACHA settlement reports). - Matching Engine: Match entries using
(processor_ref, amount, currency).- Exact Match: Debit
bank_cash, Debitprocessing_fees, Creditprocessor_receivable. Mark ledger status asRECONCILED. - Amount Mismatch (Fee discrepancy or chargeback): Route to
DISCREPANCYqueue and trigger an operations review alert. - Unmatched External Item: Create an
UNRECONCILED_SUSPENSEledger entry to track untracked money movements safely.
- Exact Match: Debit
7. Core Trade-offs & Operational Considerations
- Single Database vs. Separate Ledger Database: Storing payments and financial ledger entries in the same database guarantees strict transactional safety, but introduces high write amplification.
- Trade-off: We accept higher write volume in the main transactional database to prioritize strong consistency and avoid dual-write inconsistencies. Older ledger entries can be safely archived to cold storage based on partition dates.
- Fail-Open vs. Fail-Closed on Auth Timeouts:
- Fail-Closed (Default): Treats ambiguous network timeouts as declines and reverses downstream holds automatically. Reduces exposure to uncollected merchant balances.
- Fail-Open: Temporarily approves transactions during gateway outages. Useful for high-throughput, low-risk models (e.g., transit cards), but increases risk of unpaid balances.
- Two-Phase Commit (2PC) Avoidance: External bank gateways cannot participate in distributed XA transactions. The architecture relies on durable local transactional outboxes combined with compensating operations (reversals/refunds) to reach eventual consistency across system boundaries.