Building a Resilient Payment Processing Service
System DesignModel answerLast updated
Design a payment calculation service that maintains SLAs during dependency failures and choose appropriate storage for financial data correctness.
You're designing a service that computes payment amounts for delivery orders based on lifecycle events (order created, picked up, delivered, cancelled, tip modified, etc.).
Address these two architectural challenges:
Part 1: Maintaining Service Reliability Your service depends on several external systems (pricing engines, distance calculators, configuration services, incentive platforms). If one of these dependencies experiences severe latency degradation, what strategies would you employ to ensure your service continues meeting its latency and availability commitments?
Part 2: Storage Architecture Decision You need to persist order state and payment calculations. Evaluate the trade-offs between using an in-memory data store like Redis, a traditional relational database, or alternative storage technologies. What would you recommend and why?
Your answer should demonstrate understanding of distributed systems resilience patterns and storage choices driven by correctness requirements rather than performance alone.
Hints
Hint 1
Consider separating synchronous user-facing APIs from asynchronous event processing—they have different SLA requirements and failure modes
Hint 2
For payments specifically, think about what happens if you acknowledge a write but then lose it during failover—can you afford that risk?
Hint 3
Circuit breakers and timeouts are table stakes; what about fallback strategies when dependencies are degraded but not completely down?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Building a Resilient Payment Processing Service
This problem tests whether you understand operational resilience patterns and can choose storage based on correctness constraints rather than popularity. For financial systems, accuracy and auditability trump raw speed.
1. Understanding Requirements and Scope
Begin by clarifying what you're building and its performance contract:
Inputs: Lifecycle events like order creation, acceptance, pickup, delivery, cancellation, and tip adjustments.
Outputs: Calculated payment breakdowns—what the customer pays, what the delivery person earns, what the merchant receives—with full audit trails.
External dependencies: Pricing/promotion services, distance/routing calculators, merchant configuration, worker incentive systems.
Scale assumptions:
- ~2 million orders daily with ~10 events each = 20M events/day
- Baseline throughput: ~230 events/second
- Peak load: ~1,000-2,000 events/second (dinner rush, 5-10x typical)
- Synchronous API requirement: p99 latency under 200ms for payment quotes
- Asynchronous processing: p99 under 60 seconds from event to finalized calculation
- Correctness: Exactly-once financial effect; no lost or duplicate money movements
The write volume is manageable. The real challenge is maintaining correctness under retries, partial failures, and dependency outages.
2. Architecture Overview
External services → Event stream (order-events, partitioned by order_id)
↓
Payment processor workers
↓ ↓
[External APIs] [Primary Database]
(with resilience) (transactions)
↓
Outbox → downstream events → reporting/payouts
Redis layer (acceleration only, not source of truth)
Data model in the primary database:
eventstable: event_id (PK), order_id, event_type, payload, timestamporder_statestable: order_id (PK), current_state, version (for optimistic locking), updated_atpayment_recordstable: order_id, version, input_snapshot (JSON), calculation_outputs, rule_version_usedfinancial_ledgertable: entry_id (PK), order_id, account, amount_cents (BIGINT), debit_or_credit, idempotency_key (UNIQUE), timestamp
The ledger is append-only with double-entry accounting. Corrections are new reversing entries, never updates.
3. Part 1: Dependency Resilience Strategy
The fundamental insight: architect to avoid synchronous blocking where possible. Event-driven ingestion means slow dependencies increase processing lag rather than failing user requests directly.
Layer 1: Request-level defenses
-
Aggressive timeouts based on latency budgets. With a 200ms SLA, allocate perhaps 50ms to each external call, not the default 30-second timeout. Propagate deadlines through the call chain.
-
Circuit breakers. When failure rate exceeds a threshold (e.g., 40% over a 10-second window), stop attempting calls and fail fast. Use exponential backoff for reopening probes.
-
Bulkhead isolation. Separate thread pools and connection pools per dependency. This prevents one slow service from exhausting resources needed by healthy services.
-
Smart retry policies. Exponential backoff with jitter, but crucially: implement a retry budget (cap retries at, say, 10% of request volume) to avoid amplifying load during an incident.
-
Hedged requests for reads. For idempotent read operations with high tail latency, issue a duplicate request after p95 latency elapses and use whichever responds first.
Layer 2: Degradation strategies
-
Caching with stale-while-revalidate. Pricing rules and merchant configurations change infrequently. Cache these in Redis with appropriate TTLs, and serve stale data when the dependency is unavailable rather than blocking. Asynchronously refresh in the background.
-
Provisional calculations with reconciliation. When non-critical dependencies fail, compute payment using conservative defaults (e.g., base rates without promotions), mark the calculation as
PROVISIONAL, and trigger reconciliation when dependencies recover. Important: this requires business approval since under-paying workers is worse than delayed processing. -
Priority shedding. Drop or delay low-priority work (preview quotes, analytics enrichment) before impacting money-movement operations.
Layer 3: System-level patterns
-
Consumer lag management. Monitor processing lag against the 60-second SLA. When a partition is blocked by failures, move problematic events to a retry topic with backoff, then to a dead-letter queue, preventing them from blocking the entire partition.
-
Observability and alerting. Track per-dependency latency percentiles, circuit breaker state, fallback invocation rates, provisional calculation counts. Alert on SLA burn rate, not just absolute thresholds.
-
Autoscaling and load management. Scale processing capacity based on lag, not just throughput. Implement backpressure mechanisms when the system is saturated.
4. Part 2: Storage Architecture Analysis
| Storage Type | Strengths | Payment System Fit |
|---|---|---|
| Redis (in-memory) | Sub-millisecond latency; excellent for caching, rate limiting, transient deduplication | Risk: Persistence depends on RDB snapshots or AOF with fsync policies. Even with AOF, a failover can lose acknowledged writes. No cross-key ACID on clusters. Limited query capabilities for auditing. Verdict: Cache only, never source of truth. |
| Relational DB (Postgres/MySQL, or distributed SQL like Spanner) | ACID transactions spanning events, state, and ledger. Unique constraints enforce idempotency guarantees. Strong consistency. Rich SQL for reconciliation queries. | Trade-off: Write scaling requires sharding (partition by order_id). Higher latency than in-memory (single-digit milliseconds). Schema evolution needs migration planning. Verdict: Primary store for financial data. |
| NoSQL (Cassandra, DynamoDB) | Massive write throughput; trivial horizontal scaling | Limitation: Weak transaction support. Eventual consistency by default. Poor fit for enforcing double-entry ledger invariants across accounts. Verdict: Not recommended for payment calculations. |
| Event log (Kafka) | Durable, replayable, naturally ordered | Limitation: It's a log, not a queryable state store. Cannot efficiently answer "what's the current payment for order X?" Verdict: Ingestion layer, not primary store. |
Recommended architecture:
Primary database (relational): The source of truth for order state, payment calculations, and the financial ledger. At ~2K writes/second peak, a properly sharded Postgres cluster or a distributed SQL database handles this easily. The critical requirement is transactional atomicity—event deduplication, state machine transition, and ledger entry must commit together or not at all.
Redis as read-through cache: Accelerate queries for current order state, cache external configuration data, cache quote previews (keyed by order parameters with short TTL). The database's unique constraints remain the authoritative guard against duplicate processing. Redis failure should degrade latency, never correctness.
Kafka for event ingestion: Provides durable, ordered event delivery partitioned by order_id, ensuring events for a single order are processed sequentially.
Transactional outbox pattern: Within the same database transaction that commits payment data, write to an outbox table. A separate relay process publishes these to downstream topics. This avoids the dual-write problem (where you commit to the DB but fail to publish to Kafka, or vice versa).
5. Implementation Details
Process each event in a transaction:
BEGIN TRANSACTION
-- Idempotent insert (dedup)
INSERT INTO events (...) ON CONFLICT (event_id) DO NOTHING;
-- Optimistic concurrency on state
UPDATE order_states SET state = 'DELIVERED', version = version + 1
WHERE order_id = ? AND version = ?;
-- Record calculation with inputs snapshot
INSERT INTO payment_records (...);
-- Double-entry ledger
INSERT INTO financial_ledger
(account, amount_cents, direction, idempotency_key)
VALUES
('customer:123', 1500, 'debit', 'order-456-customer'),
('dasher:789', 800, 'credit', 'order-456-dasher'),
('merchant:012', 700, 'credit', 'order-456-merchant');
-- Outbox for downstream
INSERT INTO outbox (event_type, payload, ...);
COMMIT
The idempotency_key unique constraint ensures exactly-once financial effect even if the event is reprocessed.
Common Mistakes
- Using Redis as primary storage for financial data, risking data loss on failover
- No timeout or circuit breaker strategy, allowing cascading failures
- Retry storms without budgets, amplifying outages
- Synchronous dependency calls in the critical path without fallback strategies
- Eventual consistency for payment calculations where strong consistency is required
- Missing audit trail—no way to explain how a number was calculated or trace corrections
The key insight: payments are a correctness problem first, a performance problem second. Choose storage and resilience patterns accordingly.