Architecting a Payment Gateway with Real-Time Authorization and Batch Settlement
System DesignModel answerLast updated
Design a robust payment architecture that handles real-time authorization holds, deferred batch captures, and safe retries without double-charging users.
Design a payment system that executes two main money movement stages: placing a real-time authorization hold on a payer's funds at order placement, and settling (capturing) held funds later in batch jobs.
Your architecture must address:
- Real-time Hold & Batch Capture: End-to-end lifecycle, API flow, data model, and batch generation.
- Idempotency & Safe Retries: Ensuring network retries, client double-clicks, and background job execution never duplicate authorizations or captures.
- Consistency & Failure Recovery: Handling edge cases like network timeouts mid-flight, processor outages, orphan holds, and asynchronous reconciliation.
Clarifications & Scope Assumptions
- Scale: Assume 2,000 peak authorization requests/sec and daily/event-driven batch settlements processing 5M events per night.
- Model: Assume integration with external acquirers/processors (e.g., Stripe, Adyen) via API, while maintaining an internal double-entry ledger.
- Holds: Authorizations expire after 7 days unless captured or explicitly released. Partial captures are allowed.
Hints
Hint 1
Differentiate between authorization holds (reserving credit limit/funds) and capture/settlement (actual money movement).
Hint 2
Use database unique constraints on idempotency keys to handle concurrent duplicate API requests safely.
Hint 3
Implement a double-entry ledger pattern to make money state changes immutable and auditable.
Hint 4
Handle network timeouts with an asynchronous polling or reconciliation daemon rather than assuming failure.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & System Boundary
Functional Requirements
- Authorize (Hold): Reserve funds on a user's payment instrument synchronously (< 500ms latency target).
- Capture (Settlement): Execute batch capturing of authorized holds once orders are fulfilled.
- Release/Void: Explicitly cancel active authorizations if an order is canceled early.
- Reconciliation: Automatically detect and correct discrepancies between local state and the external payment processor's ledger.
Non-Functional Requirements
- Strict Idempotency: Zero tolerance for double-charging or duplicate authorizations under any failure scenario.
- High Availability & Auditability: System must remain operational even during processor degradation, maintaining an append-only audit log for all financial events.
2. High-Level Architecture & Core Data Model
+---------------+ +------------------+ +-------------------+ +--------------------+
| Client App / | --> | API Gateway / | --> | Payment Service | --> | Database (Postgres |
| Checkout | | Idempotency Layer| | (State Machine) | | + Ledger Engine) |
+---------------+ +------------------+ +-------------------+ +--------------------+
| |
v v
+-------------------+ +-------------------+
| External Payment | | Message Queue / |
| Processor (Adyen) | | Outbox Worker |
+-------------------+ +-------------------+
Core Database Schema
-
Payments Table (State Tracker)
id: UUID (Primary Key)user_id: UUIDamount: BIGINT (stored in minor currency units, e.g., cents)currency: VARCHAR(3)status: ENUM (AUTHORIZED,CAPTURE_PENDING,CAPTURED,RELEASED,EXPIRED,FAILED)processor_ref: VARCHAR(255) (External authorization ID)version: INT (for optimistic locking)created_at,updated_at: TIMESTAMP
-
Idempotency Records Table
idempotency_key: VARCHAR(255) (Primary Key)request_hash: VARCHAR(64) (SHA-256 of request payload)status: ENUM (PROCESSING,COMPLETED)response_body: JSONBcreated_at: TIMESTAMP
-
Double-Entry Ledger Entries (Immutable Audit Log)
id: UUID (Primary Key)transaction_id: UUIDaccount_id: UUID (e.g.,USER_CREDIT_HOLD,MERCHANT_RECEIVABLE,PROCESSOR_CLEARING)entry_type: ENUM (DEBIT,CREDIT)amount: BIGINTcreated_at: TIMESTAMP
3. Payment Lifecycle & Flow Mechanics
[START] --> PENDING_AUTH --> AUTHORIZED --> CAPTURE_PENDING --> CAPTURED [END]
| |
v v
FAILED RELEASED / EXPIRED
Real-Time Authorization Path (Synchronous)
- Client Order Submission: Client sends payload with a unique
idempotency_key(e.g., headerIdempotency-Key: idempotency_order_12345). - Idempotency Gatekeeper:
- Begin DB Transaction.
- Insert key into
idempotency_records. If key exists:- If status is
COMPLETED, return stored response. - If status is
PROCESSING, return409 Conflict(or HTTP429).
- If status is
- Processor Call: Payment Service issues a synchronous authorization request to the external processor.
- State & Ledger Update:
- Update payment status to
AUTHORIZED. - Record ledger entries: Credit
USER_ACCOUNT, DebitHOLD_RESERVE_ACCOUNT. - Commit DB Transaction and return success to client.
- Update payment status to
Batch Capture Path (Asynchronous)
- Order Fulfillment Event: When orders ship, items are tagged as ready for capture.
- Batch Job Aggregation: A nightly background worker selects payments where
status = AUTHORIZEDandfulfillment_status = SHIPPED. - Optimistic Lock Batch:
- Update matching payments to
CAPTURE_PENDINGwherestatus = AUTHORIZED. This prevents double-inclusion across concurrent batch runners.
- Update matching payments to
- Processor Submission: Send bulk capture file or parallel API commands to external payment gateway.
- State Finalization: Upon receiving gateway acknowledgment, update payment status to
CAPTUREDand append completion events to ledger.
4. Safe Retries & Idempotency Strategy
Preventing duplicate charges across network errors or system restarts requires defense-in-depth across multiple boundaries:
Layer 1: Incoming API Request (Client to Gateway)
- Database Unique Constraints: Relying on application memory for deduplication fails during node restarts. Inserting the
idempotency_keyinto a relational database table with aPRIMARY KEYconstraint guarantees atomicity. - Payload Matching: Store
request_hash. If a request arrives with the sameidempotency_keybut a different payload (e.g., different dollar amount), reject immediately with400 Bad Request.
Layer 2: Payment Service to External Processor
- Processor-Level Idempotency Keys: Forward deterministic keys to the payment processor (e.g., passing
auth_idempotency_keyin API headers to Stripe/Adyen). If the network drops after the gateway processes funds but before returning HTTP 200 to us, retrying with the identical key returns the original authorization result instead of re-charging.
Layer 3: Background Worker Idempotency
- Transactional Outbox Pattern: Instead of emitting domain events directly over network queues within a DB transaction, write the event to an
outboxdatabase table inside the same transaction. An asynchronous daemon reads the outbox and publishes events to Kafka/RabbitMQ. - State Machine Guardrails: State transition queries must explicitly include current state preconditions:
UPDATE payments SET status = 'CAPTURED', updated_at = NOW() WHERE id = $1 AND status = 'CAPTURE_PENDING';
5. Consistency & Failure Recovery
| Scenario | Risk | Mitigation Architecture |
|---|---|---|
| Timeout during Authorization API call | System is uncertain if processor held funds or rejected request. | Transition local state to AUTH_UNKNOWN. A background worker queries processor API via GET /authorizations/{id} or relies on webhook reconciliation. Never retry blind without status lookup. |
| Processor Outage during Batch Capture | Batch execution fails midway. | Operations are broken into micro-batches. Retries pick up only rows still stuck in CAPTURE_PENDING past a specific threshold timestamp. |
| Expired Holds | Customer hold expires (e.g., past 7-day limit) before fulfillment. | A scheduled sweeper flags holds nearing expiration (created_at > 6 days). If unfulfilled, issue automatic authorization renewal or release notification to customer. |
| Ledger Mismatch (Internal vs External) | Processor settled $100, but internal DB shows $90 due to bug. | Daily Reconciliation Engine: Ingest daily settlement CSV logs from processor. Compute checksum matching against internal ledger tables (DEBIT vs CREDIT sum). Flag anomalies automatically into an audit table for manual resolution. |
Key Takeaways & System Trade-Offs
- Synchronous Authorization vs Asynchronous Settlement: Authorization prioritizes low latency and user confirmation, whereas settlement favors throughput, efficiency, and batch processing resilience.
- Double-Entry Bookkeeping: Storing balances as derived aggregations of immutable
DEBIT/CREDITentries prevents data corruption and provides audit trails necessary for financial compliance. - At-Least-Once Delivery + Idempotency: Distributed components accept that messages will deliver multiple times; idempotency guarantees execution effects happen exactly once.