Card authorization with deferred tips and batch settlement
System DesignModel answerLast updated
Build a payment platform for retail terminals that authorizes transactions, accepts post-authorization tip adjustments, and settles batches nightly.
You're building a payment platform for retail businesses that accept card payments through point-of-sale terminals. The flow works as follows: when a customer pays, the terminal requests an authorization for the purchase amount. After the authorization succeeds, the customer may add a gratuity, which adjusts the final charge. At the end of each business day, all finalized transactions are packaged and sent to the payment processor for settlement.
Your platform sits between the terminals and the external payment processor. The processor handles communication with card networks and banks; your job is to orchestrate authorization requests, manage tip adjustments, batch transactions for settlement, and verify that everything was processed correctly.
Focus on three areas:
Authorization and tip adjustment: Terminals operate on unreliable networks and will retry failed requests. Design the data model and API contracts so that duplicate authorization attempts don't result in multiple holds, and tip changes are applied correctly even when messages arrive out of order.
Nightly batch settlement: Each evening, gather all completed transactions and submit them to the processor. As transaction volume grows, design a system that distributes this work to finish within the available time window, handles partial failures gracefully, and guarantees each transaction is submitted exactly once.
Settlement reconciliation: After submission, the processor sends back a report of what actually settled. Design how you match these reports against your records, detect discrepancies, and resolve them.
Consider questions like: How many locations and transactions must you support? Do all locations close their day at the same time? When does the deadline for tip entry pass? What format does the processor expect for batch submission? How do you ensure money amounts are represented accurately throughout the pipeline?
Hints
Hint 1
Model transaction states explicitly—from pending authorization through settlement—and make state transitions atomic
Hint 2
Use idempotency keys for every external call and store the processor's response alongside the key to handle retries safely
Hint 3
Partition settlement work by merchant or time window, track progress per partition, and use deterministic job assignment to avoid double-submission on retry
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Approach
This system bridges retail terminals and a payment processor, managing three phases: real-time authorization with tip adjustment, bulk nightly settlement, and post-settlement reconciliation. Each phase has distinct failure modes and correctness requirements.
Key principles: Represent money as integers in the smallest currency unit (cents) to avoid floating-point errors. Model transaction lifecycle as explicit states with atomic transitions. Make every external call idempotent. Build an append-only ledger of state changes for audit and debugging.
Part 1: Authorization and Tip Flow
Data Model
A Transaction record tracks:
transaction_id(UUID, primary key)merchant_id,terminal_idamount_authorized(integer, in cents)amount_tip(integer, in cents, default 0)amount_final(integer, in cents, computed as authorized + tip)state(enum:PENDING,AUTHORIZED,TIP_ADJUSTED,SUBMITTED,SETTLED,FAILED)idempotency_key_auth(from terminal)idempotency_key_tip(from terminal, nullable)processor_auth_code(from processor response)created_at,updated_at
An AuditLog table records every state transition with timestamp, old/new state, and triggering event.
Authorization API
POST /v1/transactions/authorize
{
"idempotency_key": "term_123_20250115_001",
"merchant_id": "merch_456",
"terminal_id": "term_123",
"amount": 850, // $8.50
"card_token": "tok_abc..."
}
Idempotency logic: Before calling the processor, check if this idempotency key exists. If found and state is AUTHORIZED, return the cached response immediately. If found and state is PENDING, the previous request may still be in flight—wait or return 409 Conflict. If not found, create a PENDING transaction, call the processor, then atomically update to AUTHORIZED with the processor's auth code.
Processor timeout handling: If the processor call times out, the transaction stays in PENDING. The terminal will retry with the same idempotency key. On retry, re-check with the processor using a "get authorization status" call if available, or mark as FAILED after a threshold and let reconciliation catch it later. Never send a duplicate authorization request to the processor for the same idempotency key.
Tip Adjustment API
POST /v1/transactions/{transaction_id}/tip
{
"idempotency_key": "term_123_20250115_001_tip",
"amount_tip": 150 // $1.50
}
Check idempotency key. If already applied, return success. Otherwise, atomically update amount_tip and amount_final, transition state to TIP_ADJUSTED, and record in audit log. Reject if transaction is already SUBMITTED or later.
Part 2: Nightly Batch Settlement
Scale Assumptions
Assume 50,000 merchants, average 200 transactions per merchant per day = 10 million transactions nightly. Processor accepts batches of up to 1,000 transactions per API call. Settlement window is 4 hours (2 AM–6 AM). Target throughput: 10M / 4 hours = ~700 transactions/second, or 700 API calls/second if batched.
Partitioning Strategy
Partition by merchant: Each merchant's transactions for the day form one settlement batch. This aligns with how merchants review their reports and simplifies per-merchant reconciliation.
Job scheduling: At the day's cutoff (merchant's local midnight or a configured time), mark the merchant's day as "ready for settlement." A distributed job scheduler (e.g., a queue with multiple workers, or a framework like Temporal) picks up each merchant's batch.
Deterministic assignment: Use consistent hashing or a partition key (merchant_id + date) to assign each batch to a worker. If a worker crashes, another worker picking up the same partition key will see the same state and resume safely.
Exactly-Once Submission
Each batch has a unique settlement_batch_id (e.g., merch_456_20250115). Before submission:
- Mark all transactions in the batch as
SUBMITTEDin a single database transaction. - Record a
SettlementBatchrow withbatch_id,merchant_id,date,transaction_ids[],state=PENDING. - Submit to processor with
batch_idas idempotency key. - On success, update
SettlementBatch.state=SUBMITTED, store processor's batch reference. - On failure (timeout, throttle, rejection), update
state=FAILEDand log the error.
If the worker crashes after step 1 but before step 4, the next worker sees state=PENDING and retries submission with the same batch_id. The processor deduplicates by batch_id, so the transactions are submitted exactly once.
Handling Processor Throttling and Slowness
Rate limiting: Track submission rate per worker. If the processor returns 429 or is slow to respond, back off exponentially and spread retries over the remaining window.
Progress monitoring: Each worker reports metrics (batches submitted, pending, failed) to a central dashboard. If projected completion time exceeds the window, alert operators to add workers or request a processor rate limit increase.
Partial batch rejection: If the processor rejects some transactions in a batch (e.g., one has an invalid auth code), mark those transactions as FAILED, resubmit the rest in a new batch with a new batch_id, and flag for manual review.
Part 3: Reconciliation
Report Ingestion
The processor sends a settlement report (CSV or API) listing each transaction, final amount, fees, and settlement status. Parse and store this in a ProcessorReport table with report_id, transaction_id, amount_settled, fee, status.
Idempotency: Use report_id to ensure each report is ingested once. If a report arrives twice, skip duplicate rows.
Matching Logic
For each transaction_id in the report:
- Look up the transaction in your database.
- Compare
amount_settled(from report) toamount_final(your record). - Compare
status(from report) to your expected state (SUBMITTED).
Match: Amounts agree and status is success → mark transaction as SETTLED.
Amount mismatch: Report shows a different amount → flag as MISMATCH_AMOUNT, alert for investigation. Common causes: tip was adjusted after batch submission, processor applied an unexpected fee.
Missing transaction: Your record shows SUBMITTED, but it's not in the report → flag as MISSING_FROM_REPORT. Possible causes: processor batch was partially lost, or report is delayed.
Extra transaction: Report contains a transaction you don't recognize → flag as UNKNOWN_TRANSACTION. Possible data corruption or report sent to wrong account.
Resolution Workflow
Mismatch_amount: Compare audit log to see if tip was changed after submission. If so, submit an adjustment batch. If not, contact processor support.
Missing_from_report: Wait 24 hours for a delayed report. If still missing, query processor API for transaction status. If processor has no record, resubmit in the next batch.
Unknown_transaction: Query processor to confirm it's actually tied to your account. If yes, create a retroactive transaction record. If no, dispute with processor.
Money Reconciliation
Aggregate daily: sum of amount_final for all SETTLED transactions should equal sum of amount_settled from reports, minus fees. Any delta triggers an alert and a detailed line-by-line audit.
Monitoring and Operational Safeguards
- Dashboard: Real-time view of settlement progress (batches pending, submitted, failed), projected completion time, reconciliation match rate.
- Alerts: Settlement won't finish in time, reconciliation mismatch exceeds threshold, processor error rate spikes.
- Audit trail: Every state transition logged with timestamp, trigger, and old/new values. Essential for debugging disputes and regulatory compliance.
- Retry limits: Cap retries per transaction (e.g., 3 attempts) to avoid infinite loops. After limit, escalate to manual review.
Common Mistakes to Avoid
- Floating-point currency: Using
floatordoublefor money leads to rounding errors. Always use integers (cents). - Non-idempotent APIs: Forgetting idempotency keys causes duplicate authorizations and charges.
- Lost transactions in settlement: Not tracking batch submission state leads to transactions submitted twice or not at all.
- Ignoring reconciliation gaps: Assuming the processor's report is always correct. Merchants will notice discrepancies in payouts.
- Blocking settlement on one slow batch: If one merchant's batch hangs, it shouldn't block others. Process batches in parallel.
Complexity and Scale
Authorization throughput: With idempotency checks in a fast key-value store (Redis), handle 10,000+ authorizations/sec per region.
Settlement throughput: 10M transactions in 4 hours = ~700 batches/sec (assuming 1,000 txns/batch). With 10 workers, each handles 70 batches/sec. Easily scales horizontally by adding workers.
Reconciliation: Matching 10M records against reports takes seconds with indexed lookups on transaction_id. Aggregation queries run in under a minute on a partitioned database.