Building a Two-Phase Transaction Processing Platform
System DesignModel answerLast updated
Design a service that processes both instant payments and deferred-settlement transactions with reserved funds, ensuring correctness under failures.
Building a Two-Phase Transaction Processing Platform
You need to architect a transaction processing service supporting two payment patterns: instant transactions and two-phase reserved-then-settled transactions.
The service manages an internal credit system where merchants can reserve customer funds first, then finalize those reservations later—either individually or in bulk at day's end. Reservations that aren't finalized must be cancelable.
Core Operations
Your API must provide:
charge(user_id, amount): Execute an immediate fund transferauthorize_hold(user_id, amount): Lock funds without transferring them yetcapture_hold(hold_id): Complete a previously reserved transactionrelease_hold(hold_id): Cancel a reservation and return funds
System Properties
- Idempotency: Duplicate requests must not create multiple charges or reservations
- Consistency: User balances must accurately distinguish between spendable and locked funds
- Reliability: Every financial operation must be traceable; the system must recover correctly from mid-operation crashes
- Throughput: Handle 1,000 operations per second with daily batch jobs processing millions of items
What to Design
- Storage Schema: Tables and fields for tracking transactions, reservations, and state progressions
- Service Architecture: Component responsibilities and interaction patterns (synchronous vs. asynchronous)
- Batch Processing: The mechanism for end-of-day settlement ensuring every item is processed exactly once
- Uncertainty Handling: Your approach when an external payment provider call times out with unknown outcome
Hints
Hint 1
Think about how to prevent the same reservation from being both captured and released simultaneously
Hint 2
Consider what happens if your settlement batch crashes halfway through—how do you resume without double-processing?
Hint 3
A timeout from an external service means you don't know if the operation succeeded or failed; treating it as either could lose money
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Two-Phase Transaction Processing Platform
The core challenge is maintaining monetary correctness during failures—ensuring locked and available balances stay accurate, preventing duplicate operations on retry, and handling ambiguous outcomes from external systems. Performance is secondary to correctness.
1. Requirements Clarification
Start by establishing boundaries:
- Fund source: Internal credit balances (prepaid accounts). External gateways are used for account funding, not for individual holds.
- Reservation expiration: Unreleased holds expire after a defined period (e.g., 7 days) and automatically free the funds.
- Partial settlement: Allow capturing less than the full reserved amount, releasing the difference.
- Volume: 1,000 peak requests/second translates to roughly 30-40M daily operations. A single well-tuned relational database can handle this; horizontal sharding by
user_idis deferred until actually needed. - Consistency model: Strong consistency per user account; eventual consistency acceptable for analytics and reporting.
2. API Design
All state-changing endpoints require an Idempotency-Key header:
POST /charges {user_id, amount, currency}
POST /reservations {user_id, amount, currency, expires_hours}
POST /reservations/{id}/settle {amount?}
POST /reservations/{id}/void
GET /reservations/{id}
GET /accounts/{user_id}
Settlement via the /settle endpoint is asynchronous—it marks the reservation for processing, with actual fund transfer occurring during batch execution.
3. Storage Schema
accounts(
user_id PRIMARY KEY,
available_balance BIGINT NOT NULL CHECK (available_balance >= 0),
locked_balance BIGINT NOT NULL CHECK (locked_balance >= 0),
currency CHAR(3),
version INT
)
reservations(
reservation_id PRIMARY KEY,
user_id NOT NULL,
reserved_amount BIGINT NOT NULL,
settled_amount BIGINT DEFAULT 0,
state VARCHAR(20) NOT NULL, -- ACTIVE, SETTLE_PENDING, SETTLING, COMPLETED, VOIDED, EXPIRED
expires_at TIMESTAMP,
batch_id UUID NULL,
created_at TIMESTAMP,
modified_at TIMESTAMP
)
audit_log(
log_id PRIMARY KEY,
transaction_id UUID NOT NULL,
user_id NOT NULL,
operation_type VARCHAR(20), -- CHARGE, RESERVE, SETTLE, VOID, TOPUP
amount BIGINT,
reservation_id UUID NULL,
external_reference VARCHAR(100) NULL,
timestamp TIMESTAMP
)
double_entry_ledger(
entry_id PRIMARY KEY,
transaction_id UUID NOT NULL,
account_name VARCHAR(50),
debit_amount BIGINT,
credit_amount BIGINT,
timestamp TIMESTAMP
)
request_deduplication(
idempotency_key VARCHAR(100),
merchant_id VARCHAR(50),
request_fingerprint CHAR(64),
processing_state VARCHAR(20), -- PROCESSING, COMPLETED
result_payload TEXT,
created_at TIMESTAMP,
PRIMARY KEY (merchant_id, idempotency_key)
)
batch_runs(
batch_id PRIMARY KEY,
cutoff_timestamp TIMESTAMP,
execution_state VARCHAR(20),
item_count INT,
last_checkpoint_id UUID,
started_at TIMESTAMP,
finished_at TIMESTAMP
)
The double-entry ledger is authoritative for auditing. The balance columns in accounts are derived views, updated atomically with ledger entries.
4. Architecture Components
API Layer: Manages authentication, throttling, and idempotency checking before routing to services.
Transaction Service (synchronous): Owns accounts, reservations, and ledger. Each operation is a single ACID transaction:
authorize_hold: ExecuteUPDATE accounts SET available_balance = available_balance - :amt, locked_balance = locked_balance + :amt WHERE user_id = :id AND available_balance >= :amt. If zero rows update, reject with insufficient funds. Then insert reservation record and ledger entries.release_hold:UPDATE reservations SET state = 'VOIDED' WHERE reservation_id = :id AND state = 'ACTIVE'. Only if exactly one row changed, transfer locked back to available.charge: Conditional debit of available balance with corresponding ledger entries.
Event Stream: Changes are written to an outbox table in the same transaction, then relayed to a message broker for notifications and analytics. This prevents dual-write inconsistencies.
Batch Settlement Worker: Processes end-of-day settlements (detailed below).
Expiration Task: Periodically scans for reservations past their expiration time and transitions them from ACTIVE to EXPIRED, unlocking funds.
External Gateway Wrapper: Encapsulates calls to payment providers with retry logic, circuit breakers, and idempotency key management.
Idempotency Protocol:
- Attempt
INSERT INTO request_deduplication ... (state = PROCESSING). - On unique constraint violation:
- If state is
COMPLETED, return cached response. - If state is
PROCESSING, return HTTP 409 for client retry. - If request fingerprint differs, return HTTP 422.
- If state is
- Execute business logic and update idempotency record to
COMPLETEDwith response—both in one transaction.
State transitions use optimistic locking: UPDATE ... WHERE state = :expected_state ensures only valid transitions succeed, making concurrent capture and void operations mutually exclusive.
5. Batch Settlement Design
Goal: Process every marked reservation exactly once, even across failures and restarts.
Phase 1 - Batch Initialization:
Create a batch_runs record with the cutoff timestamp (end of business day).
Phase 2 - Chunked Claiming: Workers claim reservations in batches of 5,000-10,000 using:
UPDATE reservations
SET state = 'SETTLING', batch_id = :batch_id
WHERE reservation_id IN (
SELECT reservation_id
FROM reservations
WHERE state = 'SETTLE_PENDING'
AND modified_at < :cutoff
ORDER BY reservation_id
LIMIT 10000
FOR UPDATE SKIP LOCKED
)
Using SKIP LOCKED enables parallel workers without conflicts. Reservations submitted after cutoff naturally flow to the next batch.
Phase 3 - Settlement Execution: For each chunk, in one transaction:
- Generate ledger entries: debit locked balance, credit merchant account.
- Release any unspent portion of the reservation.
- Transition state to
COMPLETEDwithWHERE state = 'SETTLING' AND batch_id = :batch_id. - Update checkpoint pointer.
Phase 4 - External Reconciliation:
Aggregate totals by merchant and submit payout instructions to external systems, using batch_id + merchant_id as the idempotency key.
Phase 5 - Batch Closure:
Mark batch as COMPLETED after verifying processed item counts match ledger totals.
Recovery from crashes: Workers resume from the last checkpoint, re-attempting only items in SETTLING state for the current batch. The state machine prevents double-settlement.
6. Handling Gateway Timeouts
A timeout represents unknown outcome, not failure. Incorrect handling causes either duplicate charges or lost revenue.
Protocol:
- Before calling external gateway, persist transaction as
PENDING_EXTERNALwith a deterministic idempotency key (derived from transaction ID). - On timeout, mark transaction as
OUTCOME_UNKNOWNand keep funds reserved. Return HTTP 202 (processing) to the client. - Background resolver service:
- Queries gateway's status API using the idempotency key.
- If gateway has no record after several attempts, execute circuit-breaker logic (manual review queue).
- Once outcome is determined, finalize the transaction and notify the client.
Never retry the original payment call after a timeout—the gateway may have already processed it. Only query status.
7. Key Design Decisions
Why separate available vs. locked balances? Prevents overselling reserved inventory or double-spending reserved funds while maintaining fast balance checks.
Why ledger + materialized balances? The append-only ledger provides audit trail and point-in-time reconstruction. Materialized balances enable low-latency queries without scanning history.
Why asynchronous settlement? Decouples merchant operations from batch processing windows, allowing reservations to be marked during business hours and settled efficiently in bulk.
Why per-user strong consistency? Financial correctness requires seeing all balance changes in order. Cross-user operations can be eventually consistent.
8. Common Mistakes
- Treating timeouts as failures and automatically voiding the transaction, potentially losing completed payments.
- Not using idempotency keys for external calls, causing duplicate charges when clients retry.
- Updating balances and ledger in separate transactions, breaking atomicity and causing drift.
- Batch processing without checkpointing, making recovery from mid-batch crashes impossible without manual reconciliation.
- Allowing concurrent state transitions without optimistic locking, enabling invalid states like capturing an already-voided reservation.
9. Scaling Considerations
At 10x scale (10,000 ops/sec):
- Read replicas for balance queries
- Partition accounts by
user_idhash across database shards - Horizontal scaling of batch workers (already supported via parallel chunk processing)
- Cache frequently accessed account balances with write-through invalidation
The architecture supports these scaling patterns without fundamental redesign.