Transaction State Management with External Payment Processors
System DesignModel answerLast updated
Build a service that orchestrates payment transitions through hold, capture, and settlement while handling unreliable gateway responses and ensuring financial correctness.
You're building a service that orchestrates transactions through their full lifecycle: authorizing a hold, capturing funds, and recording settlement. Your service sits between client applications and third-party payment processors that are often slow and unreliable.
What You Need to Support
Your system must handle these state transitions:
CREATED→AUTHORIZING→AUTHORIZED→CAPTURING→CAPTURED→SETTLED- At any point, a transaction can move to
FAILED
Key requirements:
-
Idempotent operations: If a client retries a capture request due to a timeout, the customer must never be charged twice.
-
Audit trail: Every state change must be recorded in an immutable log for compliance and reconciliation.
-
Async gateway communication: Payment processors respond via webhooks or require polling. Gateway calls can take seconds and may return ambiguous "status unknown" responses.
-
Strong consistency for transaction state: While reporting can be eventually consistent, the transaction's own state must be strictly consistent—no lost updates, no phantom charges.
Scale and Constraints
- Peak traffic: 5,000 new transactions per second
- Each transaction involves roughly 3 gateway operations
- Payment processors have p99 latencies of 2–10 seconds and occasionally time out
- Financial accuracy is non-negotiable; prefer blocking over inconsistency
What to Design
-
API contract: Define the endpoints clients use to create and transition payments. How do you enforce idempotency?
-
Data model: Show the schema for transactions and the audit ledger. How do you prevent lost updates when workers race to apply webhook results?
-
Architecture: Sketch the components—API layer, workers, queues, database. How do you ensure that updating transaction state and writing the ledger entry happen atomically?
-
Handling ambiguity: When a gateway returns "unknown" or times out, you don't know if the customer was charged. Walk through your recovery strategy without risking a double charge.
Hints
Hint 1
Record your intent to perform an operation before calling the gateway, so you never lose track of an in-flight request
Hint 2
Use optimistic locking (a version column) to prevent concurrent state transitions from clobbering each other
Hint 3
When a gateway call times out or returns 'unknown,' schedule retries with exponential backoff using the processor's status inquiry endpoint
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Transaction State Management
1. Scope and Scale Analysis
Start by translating requirements into concrete numbers to guide architecture decisions.
Traffic profile:
- 5,000 new payments/s at peak
- Each payment generates ~3 gateway calls (authorize, capture, settle) plus webhook processing
- Total state transitions: ~15,000/s at peak
- Each transition writes to both the transaction table and an append-only ledger (double-entry accounting typically means 2+ ledger rows per transition)
- Ledger write volume: ~30,000 inserts/s at peak
Storage projection:
- At an average 2,000 TPS sustained, that's ~170 million transactions daily
- With ~1 KB per transaction plus associated ledger entries, plan for ~500 GB/day
- Financial records must be retained for years; archive cold data after 90 days
Concurrency:
- With p99 gateway latency of 10 seconds and 15k calls/s, roughly 150,000 requests are in flight concurrently
- Gateway I/O must be fully async and decoupled from client-facing API requests
Consistency requirements:
- Transaction state transitions must be strictly serializable within a single payment
- Downstream reporting and aggregate balances can be eventually consistent
2. API Design
Every state-changing operation requires an Idempotency-Key header (a UUID supplied by the client), scoped per merchant.
POST /v1/transactions
Body: {amount_cents, currency, payment_method_id, merchant_id}
→ 202 Accepted {transaction_id, state: "AUTHORIZING"}
POST /v1/transactions/{id}/capture
Body: {amount_cents?} // optional partial capture
→ 202 Accepted {state: "CAPTURING"}
POST /v1/transactions/{id}/void
→ 202 Accepted {state: "VOIDING"}
GET /v1/transactions/{id}
→ 200 OK {id, state, amount, history[]}
POST /webhooks/{processor_name}
(Signature-verified inbound webhook from processor)
Clients receive events asynchronously via their own registered webhooks: transaction.authorized, transaction.captured, transaction.settled, transaction.failed.
Settlement is typically processor-initiated (batch processing overnight), but if your contract requires explicit settlement requests, use the same idempotent POST pattern.
3. State Machine
States capture both intent and outcome:
Happy path: CREATED → AUTHORIZING → AUTHORIZED → CAPTURING → CAPTURED → SETTLED
Additional states:
AUTHORIZE_UNKNOWN,CAPTURE_UNKNOWN: gateway timed out or returned ambiguous statusFAILED,VOIDED: terminal states
The critical insight is recording intent-first: transition to *_ING states before calling the gateway. Never hold a database transaction open across a network boundary.
Every transition uses a conditional update with optimistic locking:
UPDATE transactions
SET state = $next_state, version = version + 1, updated_at = now()
WHERE id = $id AND state = $expected_state AND version = $current_version
RETURNING *;
If the update affects zero rows, a concurrent transition already occurred; re-read and return the current state to the caller.
State transitions are monotonic. A late webhook delivering AUTHORIZED after the transaction has already moved to CAPTURED is logged but does not change state.
4. Data Model
CREATE TABLE transactions (
id UUID PRIMARY KEY,
merchant_id UUID NOT NULL,
amount_cents BIGINT NOT NULL,
currency CHAR(3) NOT NULL,
state VARCHAR(32) NOT NULL,
version INT NOT NULL DEFAULT 0,
processor VARCHAR(64),
processor_reference VARCHAR(128),
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
-- Shard by id for horizontal scaling
CREATE TABLE processor_operations (
operation_id UUID PRIMARY KEY, -- used as processor-side idempotency key
transaction_id UUID NOT NULL,
operation_type VARCHAR(16) NOT NULL, -- AUTHORIZE, CAPTURE, VOID
status VARCHAR(16) NOT NULL, -- PENDING, SUCCESS, DECLINED, UNKNOWN
request_payload JSONB,
response_payload JSONB,
next_retry_at TIMESTAMPTZ,
retry_count INT DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE idempotency_log (
merchant_id UUID NOT NULL,
idempotency_key VARCHAR(128) NOT NULL,
request_hash VARCHAR(64) NOT NULL,
transaction_id UUID NOT NULL,
response_snapshot JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (merchant_id, idempotency_key)
);
CREATE TABLE ledger_entries (
entry_id BIGSERIAL PRIMARY KEY,
journal_id UUID NOT NULL, -- groups debits and credits
transaction_id UUID NOT NULL,
account_code VARCHAR(32) NOT NULL,
direction VARCHAR(6) NOT NULL, -- DEBIT or CREDIT
amount_cents BIGINT NOT NULL,
currency CHAR(3) NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
-- Append-only: no UPDATE or DELETE privileges
-- Invariant: SUM(debits) = SUM(credits) per journal_id
CREATE TABLE event_outbox (
id BIGSERIAL PRIMARY KEY,
aggregate_id UUID NOT NULL,
event_type VARCHAR(64) NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
published_at TIMESTAMPTZ
);
Ledger semantics:
- Authorization: memo entry or soft reserve (implementation-specific)
- Capture: Debit
accounts_receivable:processor, Creditrevenue:merchant - Settlement: Debit
cash:bank, Creditaccounts_receivable:processor(with separate fee entries) - Corrections are always new reversing journals, never edits
5. Architecture
┌─────────┐ ┌──────────────┐ ┌──────────────┐
│ Clients │───▶│ API Gateway │───▶│ Transaction │
└─────────┘ │ (idempotency)│ │ Service │
└──────────────┘ └───────┬──────┘
│
┌──────────────────────┼────────────────┐
▼ ▼ ▼
┌───────────────┐ ┌──────────┐ ┌────────────┐
│ Transactions │ │ Ledger │ │ Outbox │
│ DB │ │ DB │ │ │
└───────┬───────┘ └──────────┘ └─────┬──────┘
│ │
│ CDC Relay
▼ │
┌───────────────┐ ▼
│ Gateway Worker│◀───────────────────▶ Event Stream
│ Pool │ (Kafka/SQS)
└───────┬───────┘
│
┌───────────┼───────────┐
▼ ▼ ▼
Processor A Processor B Retry Queue
Atomicity pattern:
A single database transaction performs:
- Conditional state update with version check
- Ledger journal insert (same shard as transaction row)
- Event outbox insert (same shard)
- Idempotency response snapshot
By co-locating all related data on the same database shard (partition by transaction_id), you achieve ACID atomicity without distributed transactions.
Capture flow:
- API layer checks the idempotency key. If previously seen with matching request hash, return cached response. If hash differs (client bug), return 422.
- Start transaction: update state
AUTHORIZED → CAPTURING, insertprocessor_operationsrow with statusPENDING, write to outbox. - Commit. Return 202 to client.
- Async worker picks up operation, calls processor with
operation_idas the processor's idempotency key. - Worker receives response and applies it via the same conditional state update logic:
- Success →
CAPTURED+ ledger journal - Decline →
FAILED - Timeout/Unknown →
CAPTURE_UNKNOWN
- Success →
Scaling:
- Database: 16 shards handling ~1,000 writes/s each leaves 2x headroom
- Workers: horizontally scaled, stateless, with bulkheads and circuit breakers per processor
6. Handling "Unknown" Responses
Golden rule: unknown ≠ failure. Never retry with a new idempotency key; never assume failure. Either mistake risks a double charge.
Recovery strategy:
- Persist the
CAPTURE_UNKNOWNstate and insert a retry task withnext_retry_at. - Use exponential backoff with jitter: 5s, 30s, 2min, 10min, 1hr, etc.
- Status inquiry: call the processor's GET status endpoint using the original
operation_idorprocessor_reference. Many processors also accept idempotent replay of the original request. - Webhooks and polling can race; both go through the same conditional update, so the second arrival is a no-op.
- Manual escalation: if the state remains unresolved after 24 hours (or before authorization expiry), escalate to a manual review queue. The client continues to see
CAPTURING; operations staff reconcile during daily settlement. - Monitoring: alert on elevated unknown-rate per processor; spikes indicate outages.
7. Key Trade-offs
- Latency vs. correctness: Intent-first writes add an extra database round trip but guarantee no money is ever moved without a durable record.
- Single-shard colocation vs. global queries: Aggregate account balances become eventually consistent views, rebuilt from the ledger stream. This is acceptable for financial systems where the source of truth is the immutable ledger.
- Optimistic locking vs. pessimistic locks: Optimistic locking (version column) scales better under contention than row-level locks, especially with async workers racing to apply results.
- Sync vs. async client responses: Returning 202 immediately and delivering results via webhooks improves client-facing latency and decouples you from gateway tail latencies.
Common Mistakes
- Retrying with a new idempotency key after timeout: causes double charges
- Updating transaction state without writing ledger atomically: creates reconciliation gaps
- Treating "unknown" as failure: leads to incorrectly declined payments
- Using distributed transactions across services: kills throughput and availability; co-locate related data instead
- Forgetting webhook replay protection: processors often retry webhooks; must dedupe on
processor_referenceand state version