Presenting End-to-End System Architecture and Database Strategy
System DesignModel answerLast updated
Architect and present a high-volume production system, detailing API flow, query indexing, data partitioning, fault tolerance, and explicit technical trade-offs.
During system design interviews, candidates are often evaluated on their ability to explain the architecture of a complex production system they designed, implemented, or operated.
Structure a technical presentation for a high-volume event or transaction-processing system (such as payment processing, event logging, order fulfillment, or audit telemetry) that requires strong consistency, high reliability, and optimized read performance under high concurrency.
Your walkthrough must address the following five areas:
-
Business Drivers & System Scope
- Define the core domain problem and primary triggers (e.g., synchronous REST calls, asynchronous messaging, batch processes).
- Draw explicit boundaries: upstream producers, downstream dependencies, and system contracts. Include target scale, latency SLAs, and throughput profiles.
-
End-to-End Execution Flow
- Map out the complete lifecycle of a request from ingestion to persistent state and notification delivery.
- Explain the choice of API protocols (e.g., REST, gRPC, event channels) and clear boundaries between synchronous execution and asynchronous background processing.
-
Storage Strategy, Indexing & Partitioning
- Justify the selected database paradigms (RDBMS vs. NoSQL vs. Append-only Logs).
- Analyze query patterns and composite B-tree indexing strategies. Specifically compare composite index structures such as
(user_id, region)vs.(region, user_id)under equality and range filtering, explaining cardinality, index ordering rules, and write amplification. - Detail your data growth strategy: partitioning techniques (range, hash, list) versus application-level sharding, along with replica topology and write isolation.
-
Resilience, Operations & Data Durability
- Address key operational failure modes (e.g., network splits, downstream failures, duplicate deliveries). Explain mitigation patterns such as dual-write prevention (e.g., Transactional Outbox), idempotency control, and dead-letter pipelines.
- Specify observability metrics, tracing across boundaries, and operational alerting strategies.
-
Technical Trade-Offs & Architectural Impact
- Highlight your direct individual contributions to the system design.
- Present at least one significant technical trade-off (e.g., strong immediate consistency vs. write latency, or temporal range partitioning vs. hash sharding across nodes), supported by concrete performance metrics or operational constraints.
Hints
Hint 1
Structure your response logically before jumping into low-level details: establish scale, draw boundaries, then walk through the data path.
Hint 2
When comparing composite indexes (e.g., (user_id, region) vs. (region, user_id)), reference the B-tree leftmost-prefix rule, column selectivity/cardinality, and how sorting or range operations affect index utility.
Hint 3
Ground your trade-offs in real numbers and trade-off metrics (e.g., p99 write latency, storage overhead, operational complexity) rather than abstract assertions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Business Context & System Scope
Problem Statement
Consider an Enterprise Transaction Routing & Authorization Engine. The system ingests financial transfer instructions, runs validation and fraud rules, reserves balance, routes the transaction to an external clearing network, and emits audit events.
Key operational constraints:
- Zero missing or duplicate transactions (strict idempotency and durability).
- Guaranteed data isolation across multi-tenant environments.
- Low-latency status queries for user dashboards and APIs.
Operational Scale & SLAs
| Metric | Target Value |
|---|---|
| Daily Volume | 25,000,000 transactions/day |
| Average Throughput | ~290 writes/sec |
| Peak Throughput | ~3,500 writes/sec (during end-of-month processing) |
| Read / Write Ratio | 12:1 (predominantly status polling & reporting) |
| Read Latency SLA | p99 < 50 ms for status lookups |
| Ingestion Latency SLA | p99 < 200 ms for synchronous acceptance |
| System Availability Target | 99.99% operational uptime |
System Boundaries
- Upstream Producers: Public API Gateway (client traffic), Bulk File Ingestion Pipeline (batch processing), Internal Microservices (system-generated transfers).
- Downstream Consumers: External Settlement Networks, Anti-Money Laundering (AML) Screening, Real-time Accounting Ledger, Analytics Data Warehouse.
- Inputs: Transaction payload with idempotency key, debtor/creditor identifiers, currency, and authorization context.
- Outputs: Durable acknowledgement with internal transaction ID, domain state transition events, and ledger entries.
2. End-to-End Data Flow & Architecture
[Client / API Gateway]
│ (HTTPS / REST + Idempotency Key)
▼
[Transaction API Service (Stateless Pods)]
│
├─────────────► [Primary PostgreSQL DB]
│ ├── Balance Check & Reservation (Tx)
│ ├── Idempotency Key Insertion
│ └── Write to Outbox Table
▼
[Outbox Relayer / CDC] ────► [Kafka Cluster]
│
┌───────────┼───────────┐
▼ ▼ ▼
[AML Service] [Ledger] [Rail Adapter]
Execution Lifecycle
-
Ingestion & Edge Routing:
- The API Gateway authenticates the client, enforces rate limits, and validates request schema.
- The request hits the
Transaction API Servicevia REST over HTTP/2.
-
Synchronous Ingestion Path (Immediate Consistency Window):
- The service opens an ACID transaction against PostgreSQL.
- Idempotency Guard: Tries to insert the client's
Idempotency-Keyinto anidempotency_recordstable with a unique constraint. If a record already exists, it returns the cached response immediately. - Funds Reservation: Executes a conditional update on the balance table:
UPDATE accounts SET balance = balance - :amount WHERE account_id = :debtor_id AND balance >= :amount; - State Persistence: Inserts the transaction row with status
ACCEPTED. - Transactional Outbox: Writes a domain event to an
outboxtable within the same DB transaction to prevent dual-write anomalies. - The DB transaction commits, and the service returns HTTP
201 Createdwith a p99 response time under 150 ms.
-
Asynchronous Execution Path (Eventual Consistency Window):
- An Outbox Relay (using Change Data Capture / Debezium) tails the DB transaction log and pushes events into an Apache Kafka topic partitioned by
account_idto guarantee ordering per account. - Downstream consumers (AML Screening, Settlement Rail Adapters, Analytics) process the messages independently.
- When external settlement networks confirm execution, status updates (
SETTLED/REJECTED) are processed via callback workers and written back to PostgreSQL, publishing a final state update event.
- An Outbox Relay (using Change Data Capture / Debezium) tails the DB transaction log and pushes events into an Apache Kafka topic partitioned by
3. Storage Strategy, Indexing & Partitioning
Storage Engine Selection
- PostgreSQL (Primary Transactional Store): Selected for multi-row ACID transactions, strict schema constraints, robust multi-version concurrency control (MVCC), and support for native declarative partitioning.
- Kafka (Event Log): Used as an append-only distributed log for event streaming, enabling decoupled asynchronous workers and log replayability.
- DynamoDB / Cassandra (Rejected for Core Engine): Rejected because multi-entity transactional guarantees across balances and outbox tables would require complex application-level two-phase commits.
Database Indexing Strategy
A high-frequency query pattern in the system is looking up transactions for a specific user within a given geographic region, ordered by execution time:
SELECT * FROM transactions
WHERE user_id = 'usr_9876' AND region = 'US-EAST'
ORDER BY created_at DESC
LIMIT 50;
Comparing Composite Indexes: (user_id, region) vs (region, user_id)
Consider two indexing choices:
- Index A:
(user_id, region, created_at DESC) - Index B:
(region, user_id, created_at DESC)
Structural & Query Optimization Mechanics:
-
Leftmost-Prefix Rule: A B-tree index can evaluate equality predicates in any sequence provided all leading columns are matched. However, column ordering dramatically impacts index reuse for partial queries. Index A allows queries filtered by
user_idalone, whereas Index B only helps queries that includeregion. -
Selectivity and Cardinality:
user_idhas high cardinality (~50 million unique keys).regionhas low cardinality (~8 distinct values).- When both columns are used with equality filters (
WHERE user_id = X AND region = Y), the B-tree engine traverses down to the precise leaf page in both configurations with equivalent point-lookup work.
-
Sorting and Range Scans: By appending
created_at DESCto Index A (user_id, region, created_at DESC), the database engine locates the matching block for the(user_id, region)tuple and reads index entries pre-sorted by timestamp. This avoids an explicit in-memory sort operation (Sortstep in the query plan). -
Write Amplification: Every additional composite index incurs overhead on
INSERTandUPDATEoperations. By standardizing on(user_id, region, created_at DESC), we eliminate the need for standalone indexes onuser_idor(user_id, created_at), keeping total write amplification low.
Execution Impact:
- Without composite index: Sequential scan or Bitmap Index Scan followed by explicit sort step (~65 ms).
- With
(user_id, region, created_at DESC): Index-Only / Backward Index Scan without explicit sort (~2.8 ms).
Data Growth & Partitioning Strategy
With an annual ingestion rate of ~9 billion rows, a single flat table degrades query performance and increases maintenance overhead (e.g., VACUUM bloat).
[ transactions (Parent Table) ]
│
┌─────────────────────────┼─────────────────────────┐
▼ ▼ ▼
[tx_y2024m01 (Partition)] [tx_y2024m02 (Partition)] [tx_y2024m03 (Partition)]
- Declarative Range Partitioning by Time: The
transactionstable is partitioned by range oncreated_atat monthly intervals (tx_y2024m01,tx_y2024m02, etc.).- Partition Pruning: Queries containing temporal boundaries ignore non-relevant monthly partitions, skipping vast amounts of disk I/O.
- Data Lifecycle Management: Retention policy requires keeping active hot data for 12 months. Aged partitions are detached via
ALTER TABLE ... DETACH PARTITIONand archived to low-cost columnar storage (Parquet on S3) without performing resource-intensiveDELETEoperations.
- Application Sharding (Future-Proofing): When write volume exceeds a single database primary's hardware capacity (e.g., > 10,000 writes/sec), the database is sharded using consistent hashing on
account_idacross multiple PostgreSQL clusters.
4. Resilience, Failure Modes & Operations
Operational Failure Modes & Mitigation
-
Partial Failures & Network Splits (Transactional Outbox Pattern):
- Problem: Emitting a Kafka event directly inside the API code path after a database write risks dual-write anomalies (e.g., DB commits, but network fails before Kafka publish).
- Mitigation: The API writes the domain event to an
outboxdatabase table in the same database transaction as the state update. A separate Debezium CDC agent reads the DB WAL and guarantees at-least-once delivery to Kafka.
-
Duplicate Messages (Idempotent Consumers):
- Problem: Kafka's at-least-once guarantee means downstream services may process the same transaction event twice.
- Mitigation: Downstream consumers store processed transaction event IDs in a Redis cache with a 7-day TTL and check it before executing processing logic.
-
Downstream Dependency Outages:
- Problem: External banking network adapters experience elevated error rates or timeouts.
- Mitigation: Circuit breakers (e.g., Resilience4j) trip when error rates exceed 15% over a 30-second window. Requests fail fast or fall back to an asynchronous queue for retry processing using exponential backoff with jitter.
Observability & Monitoring
- Distributed Tracing: Every request generates a
trace_idat the API Gateway using OpenTelemetry, which is propagated across HTTP headers, Kafka message metadata, and SQL query comments (sqlcommenter). - Key SLI/SLO Alerts:
- Ingestion P99 Latency: Alert if > 250 ms for 5 consecutive minutes.
- Dead Letter Queue (DLQ) Depth: Alert if downstream DLQ count > 50 messages.
- Outbox Replication Lag: Alert if CDC lag exceeds 2 seconds.
5. Technical Trade-Offs & Engineering Leadership
Key Contribution
I served as the lead infrastructure architect for the transaction processing layer. I designed the transactional outbox architecture, optimized the database indexing strategy, and implemented the native table partitioning lifecycle.
Evaluated Architectural Trade-Off
Trade-Off: Immediate Multi-Region Replication vs. Regional Isolation with Eventual Synchronization
- Option A (Multi-Region Synchronous Consensus): Deploy a CockroachDB or Spanner cluster spanning three geographic regions with synchronous raft replication for all writes.
- Option B (Regionally Isolated Primaries with Asynchronous CDC Replication): Deploy primary PostgreSQL databases pinned to specific geographic regions (e.g.,
us-east,eu-west), routing user traffic based on account home region. Cross-region status reporting is synchronized asynchronously via Kafka.
Option A: Multi-Region Synchronous Consensus
[ API (US) ] ──► [ Node (US) ] ◄──( Raft / Paxos )──► [ Node (EU) ] ---> Latency: 120-180ms write
Option B: Regionally Isolated Primaries (Selected)
[ API (US) ] ──► [ Primary DB (US) ] (Write commit <10ms)
│
(Async CDC) ──► [ Kafka ] ──► [ Read Model (EU) ]
Trade-Off Analysis
| Metric / Dimension | Option A: Synchronous Multi-Region | Option B: Isolated Regional Primaries (Selected) |
|---|---|---|
| P99 Write Latency | 140 – 220 ms (constrained by cross-region RTT consensus) | 8 – 15 ms (local commit within single region) |
| Availability Risk | Cross-region network splits degrade write availability | Local network split contained to local region |
| Operational Complexity | High (managing distributed consensus & network latency spikes) | Low-Medium (standard PostgreSQL HA tooling + CDC relay) |
| Data Consistency | Strict global serializability | Strict local consistency; eventual global visibility |
Decision & Impact: We selected Option B. Financial routing rules already mapped client accounts to specific geographic regions. Choosing isolated regional primaries reduced p99 ingestion latency by over 85% (from ~180 ms down to ~12 ms) while containing blast radiuses during global cloud provider network degradation. The minor downside—a 500 ms propagation delay for cross-region dashboard visibility—was acceptable to business stakeholders.