This page requires JavaScript to display.
Y
Unpacking...
← Advanced Data Engineering
Advanced Data Engineering

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.

Contents
1. Batch vs Streaming 2. Lambda and Kappa Architectures 3. Ingest → Process → Store → Serve 4. Design: Video Streaming Analytics Pipeline 5. Design: Ride-Hailing Real-Time Pipeline 6. Scalability and Fault Tolerance 7. A Method for System Design Interviews

1. Batch vs Streaming

BatchMicro-batchStreaming
LatencyMinutes to hoursSeconds to minutesMilliseconds to seconds
DataBounded: a day, a fileSmall bounded chunksUnbounded, event by event
EnginesSpark, dbt, warehouse SQLSpark Structured StreamingFlink, Kafka Streams, Spark real-time mode
ComplexityLow: rerun a dayMediumHigh: state, late events, exactly-once
Use casesFinance close, reporting, ML trainingNear-real-time dashboards, CDCFraud, 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)
Output
window [  0,  60) total = 37
window [ 60, 120) total = 5
window [120, 180) total = 12
dropped as too late: [(55, 99)] | final watermark: 100
Say this in the interview

"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)
LambdaKappaUnified lakehouse
Code pathsTwo (batch and stream)One (stream)One engine; batch and stream write the same tables
ReprocessingRerun batch layerReplay the logRerun over table history or replay
Main drawbackTwo codebases drift apartLong log retention; replay can be slow and costlyNeeds ACID table formats and good table maintenance
TodayLegacy, still commonEvent-driven companies with Kafka at the coreMost new platforms (Delta, Iceberg, Hudi)

Deep dive: the Data Architecture Patterns guide covers this in more depth.

Say this in the interview

"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.

StageDecisionsTypical choices
IngestPush or pull? Batch or stream? CDC? Schema contracts? Back-pressure?Kafka, Kinesis, Pub/Sub; Debezium CDC; Fivetran; file drops to object storage
ProcessLatency? Stateful? Exactly-once? Reprocessing?Spark, Flink, dbt, warehouse SQL
StoreAccess pattern, volume, retention, cost, formatLakehouse tables (Delta, Iceberg, Hudi), warehouse, OLTP, key-value, time-series, search
ServeWho 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)")
Output
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

 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
DecisionChoice and reason
Partition key in Kafkaprofile_id: keeps each viewer's events ordered for sessionisation
Real-time pathFlink with event-time windows and watermarks; results to Druid or Pinot for sub-second dashboards
StorageIceberg tables partitioned by event date (hidden partitioning), compacted daily
SessionisationGroup heartbeats per profile and title with an inactivity gap (e.g. 30 min)
Late dataWatermark of a few minutes for alerts; daily batch reprocessing corrects totals
PrivacyPseudonymous IDs in analytics; deletion requests propagated with row-level deletes
Say this in the interview

"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)
ConcernDesign
Spatial groupingH3 hexagons: uniform cells, easy neighbours, a natural partition key
Latency budgetSurge must refresh every minute and be readable in milliseconds: computed in Flink, served from Redis
OLTP isolationAnalytics reads CDC copies in the lake, never the trips database
Upserts at scaleTrip rows change status; merge-on-read tables (Hudi, Iceberg, Delta deletion vectors) absorb frequent updates
Hot spotsAirports and stadiums create hot cells; split hot keys or add a random suffix (salting) and re-aggregate
FailureFlink checkpoints for exactly-once state; if streaming fails, pricing falls back to the last known multiplier
Say this in the interview

"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

PrincipleTechniqueExample
Scale horizontallyPartition data and work; stateless workersMore Kafka partitions and consumers; Spark executors
Avoid hot spotsGood partition keys, salting, consistent hashingSalt a celebrity user_id in joins
Back-pressureSlow consumers slow producers instead of crashingFlink credit-based flow control, bounded queues
IdempotencyReprocessing the same input gives the same resultMERGE by key; idempotent producers; dedup by event_id
Exactly-once resultsCheckpoints + transactional or idempotent sinksFlink two-phase commit; Spark checkpoint + Delta
Retries with backoffTransient errors retried with exponential backoff and jitterAPI extraction, cloud calls
Dead-letter queuePoison messages set aside instead of blocking the streamInvalid JSON to a DLQ topic with the error
ReplicationCopies across machines, zones, regionsKafka replication factor 3; multi-AZ storage
Graceful degradationServe stale or partial data rather than nothingLast known surge price
ObservabilityMetrics, logs, lineage, freshness alertsConsumer 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)
Output
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

FailureMitigation
Consumer crashes mid-batchCommit offsets after processing; idempotent writes make replays safe
Source sends duplicatesDeduplicate by event ID or business key
Schema change breaks parsingSchema registry with compatibility rules; DLQ for unparseable records
Downstream system slowBack-pressure, buffering in Kafka, autoscaling consumers
Bad data publishedQuality gates before publishing; table time travel to roll back
Region outageReplicated storage, infrastructure as code, tested failover
Say this in the interview

"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

StepTimeWhat to cover
1. Requirements5 minUsers, use cases, latency, freshness, volume, retention, compliance
2. Estimates3 minEvents per second, storage per day and year, peak factor
3. High-level design10 minIngest → process → store → serve on the whiteboard
4. Deep dives15 minTwo or three hard parts: partitioning, late data, exactly-once, schema evolution, hot keys
5. Reliability and operations5 minFailure modes, monitoring, data quality, security
6. Trade-offs2 minWhat 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.