Data Engineering System Design
How to design data systems that scale and survive failure, with worked designs for a video streaming service and a ride-hailing platform.
1. Batch vs Streaming
| Batch | Micro-batch | Streaming | |
|---|---|---|---|
| Latency | Minutes to hours | Seconds to minutes | Milliseconds to seconds |
| Data | Bounded: a day, a file | Small bounded chunks | Unbounded, event by event |
| Engines | Spark, dbt, warehouse SQL | Spark Structured Streaming | Flink, Kafka Streams, Spark real-time mode |
| Complexity | Low: rerun a day | Medium | High: state, late events, exactly-once |
| Use cases | Finance close, reporting, ML training | Near-real-time dashboards, CDC | Fraud, alerting, dynamic pricing, IoT |
Event time, processing time and watermarks
Streaming results must be computed by event time (when it happened), not processing time (when it arrived), because events arrive late and out of order. A watermark says "I believe all events up to time T have arrived": windows older than the watermark are finalised, and events behind it are treated as too late.
from collections import defaultdict
WINDOW, ALLOWED_LATENESS = 60, 30 # 1-minute windows, accept events up to 30 s late
# (arrival_order, event_time_seconds, amount)
events = [(1, 5, 10), (2, 42, 20), (3, 70, 5), (4, 50, 7), # 50 arrives after 70: out of order, still on time
(5, 130, 8), (6, 55, 99), (7, 125, 4)] # 55 arrives when watermark=100: too late
windows, max_event_time, late = defaultdict(int), 0, []
for _, ts, amount in events:
max_event_time = max(max_event_time, ts)
watermark = max_event_time - ALLOWED_LATENESS
start = ts // WINDOW * WINDOW
if start + WINDOW <= watermark:
late.append((ts, amount)) # window already closed: route to a late-data path
continue
windows[start] += amount
for start in sorted(windows):
print(f"window [{start:>3}, {start + WINDOW:>3}) total = {windows[start]}")
print("dropped as too late:", late, "| final watermark:", watermark)window [ 0, 60) total = 37 window [ 60, 120) total = 5 window [120, 180) total = 12 dropped as too late: [(55, 99)] | final watermark: 100
"I pick batch, micro-batch or streaming by the latency the business needs, not by fashion. In streaming I aggregate by event time with windows and a watermark that bounds how late data may arrive; anything later goes to a correction path, such as a batch reprocessing job."
2. Lambda and Kappa Architectures
LAMBDA KAPPA
events -> batch layer (all data, accurate) --+ events -> stream processor -> serving tables
-> speed layer (recent, fast) ---+-> (reprocess = replay the log from offset 0
serving layer merges into a new output, then switch)
| Lambda | Kappa | Unified lakehouse | |
|---|---|---|---|
| Code paths | Two (batch and stream) | One (stream) | One engine; batch and stream write the same tables |
| Reprocessing | Rerun batch layer | Replay the log | Rerun over table history or replay |
| Main drawback | Two codebases drift apart | Long log retention; replay can be slow and costly | Needs ACID table formats and good table maintenance |
| Today | Legacy, still common | Event-driven companies with Kafka at the core | Most new platforms (Delta, Iceberg, Hudi) |
Deep dive: the Data Architecture Patterns guide covers this in more depth.
"Lambda runs a batch layer for accuracy and a speed layer for freshness, merged at serving time, at the cost of two codebases. Kappa uses one streaming path and reprocesses by replaying the log. Most new designs unify both on a lakehouse: streaming and batch jobs write the same ACID tables with largely the same code."
3. Ingest → Process → Store → Serve
Almost every data system is four stages. Designing stage by stage, with explicit choices and reasons, is the backbone of any system design answer.
| Stage | Decisions | Typical choices |
|---|---|---|
| Ingest | Push or pull? Batch or stream? CDC? Schema contracts? Back-pressure? | Kafka, Kinesis, Pub/Sub; Debezium CDC; Fivetran; file drops to object storage |
| Process | Latency? Stateful? Exactly-once? Reprocessing? | Spark, Flink, dbt, warehouse SQL |
| Store | Access pattern, volume, retention, cost, format | Lakehouse tables (Delta, Iceberg, Hudi), warehouse, OLTP, key-value, time-series, search |
| Serve | Who reads, how fast, how often, how many concurrently? | BI on SQL warehouse, APIs over Redis/DynamoDB, Pinot/Druid for real-time OLAP, feature stores, reverse ETL |
Back-of-the-envelope capacity estimation
Interviewers expect rough numbers. Estimate volume, throughput and storage before choosing tools:
daily_active_users = 20_000_000
events_per_user_per_day = 50
event_size_bytes = 1_000
events_per_day = daily_active_users * events_per_user_per_day
avg_eps = events_per_day / 86_400
peak_eps = avg_eps * 3 # assume peak = 3x average
raw_gb_per_day = events_per_day * event_size_bytes / 1e9
compressed_tb_per_year = raw_gb_per_day * 365 / 1000 / 8 # Parquet ~8x smaller than JSON (assumption)
partition_mb_per_s = 5 # conservative per-partition throughput (assumption)
partitions = peak_eps * event_size_bytes / 1e6 / partition_mb_per_s
print(f"events/day: {events_per_day:,.0f} avg: {avg_eps:,.0f}/s peak: {peak_eps:,.0f}/s")
print(f"raw: {raw_gb_per_day:,.0f} GB/day -> ~{compressed_tb_per_year:,.1f} TB/year as Parquet")
print(f"Kafka partitions for peak: >= {partitions:.0f} (round up and leave headroom for growth and consumers, e.g. 12-24)")events/day: 1,000,000,000 avg: 11,574/s peak: 34,722/s raw: 1,000 GB/day -> ~45.6 TB/year as Parquet Kafka partitions for peak: >= 7 (round up and leave headroom for growth and consumers, e.g. 12-24)
State assumptions out loud (peak factor, compression ratio, throughput per partition). Interviewers care that the reasoning is sound and the order of magnitude is right, not about exact figures.
4. Design: Video Streaming Analytics Pipeline
Prompt: "Design the data platform for a video streaming service with 200 million members: personalised recommendations, real-time quality monitoring and business reporting." This is a Netflix-style problem; Netflix itself created Apache Iceberg for this scale of analytics.
Clarify
- Events: playback heartbeats (every few seconds), UI interactions, searches, errors from devices
- Consumers: real-time playback-quality alerts (seconds), recommendations (hourly to daily model training, real-time features), finance and content reporting (daily)
- Scale: billions of events a day; peak during evenings per region
devices --> edge gateway --> Kafka (topics: playback, ui, errors; keyed by profile_id)
|
+------------------+-----------------------------+
v v
Flink: real-time lakehouse ingestion (bronze, Iceberg)
- rebuffer rate per region/CDN (1-min windows) |
- alerts -> on-call, dashboards (Druid/Pinot) Spark batch: sessionise heartbeats
- real-time features -> feature store (key-value) -> silver playback_session
|
gold: title_daily, member_engagement,
training sets for recommendation models
|
BI (Trino / warehouse), ML training, content analytics
| Decision | Choice and reason |
|---|---|
| Partition key in Kafka | profile_id: keeps each viewer's events ordered for sessionisation |
| Real-time path | Flink with event-time windows and watermarks; results to Druid or Pinot for sub-second dashboards |
| Storage | Iceberg tables partitioned by event date (hidden partitioning), compacted daily |
| Sessionisation | Group heartbeats per profile and title with an inactivity gap (e.g. 30 min) |
| Late data | Watermark of a few minutes for alerts; daily batch reprocessing corrects totals |
| Privacy | Pseudonymous IDs in analytics; deletion requests propagated with row-level deletes |
"Devices send events to Kafka keyed by profile. Flink computes real-time quality metrics with event-time windows for alerting and low-latency OLAP, and writes features to a key-value feature store. In parallel, raw events land in Iceberg; Spark sessionises heartbeats into playback sessions and builds gold tables for reporting and recommendation training. Late data is corrected by daily reprocessing."
5. Design: Ride-Hailing Real-Time Pipeline
Prompt: "Design the data systems for a ride-hailing app: live driver locations, surge pricing, ETAs, and analytics on trips." This is an Uber-style problem; Uber created Apache Hudi to make incremental updates on its lake efficient.
driver apps --GPS every 4 s--> Kafka (driver_locations, keyed by driver_id)
rider apps ---requests-------> Kafka (ride_requests, keyed by H3 cell)
|
Flink: supply and demand per H3 hexagon per 1-minute window
-> surge multiplier per cell -> Redis (read by the pricing service in ms)
-> driver location index -> geo store for matching
trips DB (OLTP) --CDC (Debezium)--> Kafka --> lakehouse (Hudi/Iceberg/Delta) bronze -> silver trips
-> gold: trips by zone/hour, driver earnings, ETA accuracy
-> ML: ETA and pricing models (trained offline, served online)
| Concern | Design |
|---|---|
| Spatial grouping | H3 hexagons: uniform cells, easy neighbours, a natural partition key |
| Latency budget | Surge must refresh every minute and be readable in milliseconds: computed in Flink, served from Redis |
| OLTP isolation | Analytics reads CDC copies in the lake, never the trips database |
| Upserts at scale | Trip rows change status; merge-on-read tables (Hudi, Iceberg, Delta deletion vectors) absorb frequent updates |
| Hot spots | Airports and stadiums create hot cells; split hot keys or add a random suffix (salting) and re-aggregate |
| Failure | Flink checkpoints for exactly-once state; if streaming fails, pricing falls back to the last known multiplier |
"GPS pings and ride requests stream into Kafka. Flink aggregates supply and demand per H3 cell per minute and writes surge multipliers to Redis for millisecond reads. Trip changes reach the lakehouse through CDC, where an upsert-friendly table format keeps trips current for analytics and ML. I plan for hot cells, isolate OLTP from analytics, and degrade gracefully to the last known price if the stream stalls."
6. Scalability and Fault Tolerance
| Principle | Technique | Example |
|---|---|---|
| Scale horizontally | Partition data and work; stateless workers | More Kafka partitions and consumers; Spark executors |
| Avoid hot spots | Good partition keys, salting, consistent hashing | Salt a celebrity user_id in joins |
| Back-pressure | Slow consumers slow producers instead of crashing | Flink credit-based flow control, bounded queues |
| Idempotency | Reprocessing the same input gives the same result | MERGE by key; idempotent producers; dedup by event_id |
| Exactly-once results | Checkpoints + transactional or idempotent sinks | Flink two-phase commit; Spark checkpoint + Delta |
| Retries with backoff | Transient errors retried with exponential backoff and jitter | API extraction, cloud calls |
| Dead-letter queue | Poison messages set aside instead of blocking the stream | Invalid JSON to a DLQ topic with the error |
| Replication | Copies across machines, zones, regions | Kafka replication factor 3; multi-AZ storage |
| Graceful degradation | Serve stale or partial data rather than nothing | Last known surge price |
| Observability | Metrics, logs, lineage, freshness alerts | Consumer lag, error rate, SLA dashboards |
Idempotent consumer with a dead-letter queue
import json
messages = [
'{"event_id": "e1", "order_id": 1, "amount": 100}',
'{"event_id": "e2", "order_id": 2, "amount": 80}',
'{"event_id": "e1", "order_id": 1, "amount": 100}', # redelivered after a consumer restart
'{"event_id": "e3", "order_id": 3, "amount": "abc"}', # bad payload
'not json at all', # poison message
'{"event_id": "e4", "order_id": 2, "amount": 95}', # update to order 2
]
table, seen, dlq = {}, set(), []
for offset, raw in enumerate(messages):
try:
msg = json.loads(raw)
if msg["event_id"] in seen:
continue # duplicate: already applied
amount = float(msg["amount"])
except (ValueError, KeyError) as e:
dlq.append({"offset": offset, "error": type(e).__name__, "payload": raw[:30]})
continue # never block the partition
table[msg["order_id"]] = amount # upsert by key: replay-safe
seen.add(msg["event_id"])
print("table:", table)
print("dead-letter queue:")
for d in dlq:
print(" ", d)table: {1: 100.0, 2: 95.0}
dead-letter queue:
{'offset': 3, 'error': 'ValueError', 'payload': '{"event_id": "e3", "order_id":'}
{'offset': 4, 'error': 'JSONDecodeError', 'payload': 'not json at all'}
In production the set of seen event IDs lives in a state store or the sink itself (for example a MERGE that ignores existing event IDs), and the DLQ is a separate topic or table with alerting and a replay tool.
Failure modes to discuss in every design
| Failure | Mitigation |
|---|---|
| Consumer crashes mid-batch | Commit offsets after processing; idempotent writes make replays safe |
| Source sends duplicates | Deduplicate by event ID or business key |
| Schema change breaks parsing | Schema registry with compatibility rules; DLQ for unparseable records |
| Downstream system slow | Back-pressure, buffering in Kafka, autoscaling consumers |
| Bad data published | Quality gates before publishing; table time travel to roll back |
| Region outage | Replicated storage, infrastructure as code, tested failover |
"I scale by partitioning data and work across stateless workers, choosing keys that avoid hot spots. I make every stage idempotent, combine checkpoints with transactional or idempotent sinks for exactly-once results, retry transient errors with backoff, send poison messages to a dead-letter queue, replicate across zones, degrade gracefully, and monitor lag, errors and freshness."
7. A Method for System Design Interviews
| Step | Time | What to cover |
|---|---|---|
| 1. Requirements | 5 min | Users, use cases, latency, freshness, volume, retention, compliance |
| 2. Estimates | 3 min | Events per second, storage per day and year, peak factor |
| 3. High-level design | 10 min | Ingest → process → store → serve on the whiteboard |
| 4. Deep dives | 15 min | Two or three hard parts: partitioning, late data, exactly-once, schema evolution, hot keys |
| 5. Reliability and operations | 5 min | Failure modes, monitoring, data quality, security |
| 6. Trade-offs | 2 min | What you chose, what you rejected and why; what you would do with more time |
More design questions with full answers are in the Enterprise Data Architect guide (design and trade-off sections) and in DE Interview Questions.