Guide / System design Fundamentals
Data processing: batch, streaming, CDC and analytics storage
Batch vs stream processing, Lambda and Kappa, windows and late data, CDC pipelines, warehouses vs lakes, columnar and time-series stores, and object storage design.
Analytics, search indexing, recommendations, metrics and fraud detection all need data moved and transformed outside the request path. Interviewers want you to pick batch vs stream, say where data lands, and handle late and duplicate events.
Fundamentals#
D.1 OLTP vs OLAP#
| OLTP | OLAP | |
|---|---|---|
| Workload | Many small reads/writes by key | Few huge scans and aggregations |
| Store | Postgres, MySQL, DynamoDB (row-oriented) | Warehouses and column stores (BigQuery, Snowflake, Redshift, ClickHouse) |
| Optimised for | Latency, transactions | Throughput, compression, scan speed |
Never run heavy analytics on the OLTP primary: replicate (CDC) into an analytical store. Columnar storage reads only the needed columns and compresses well (same-type values together, dictionary and run-length encoding) so aggregates over billions of rows take seconds.
D.2 Batch vs stream#
| Batch | Stream | |
|---|---|---|
| Data | Bounded datasets (yesterday’s files) | Unbounded events |
| Latency | Minutes to hours | Milliseconds to seconds |
| Tools | Spark, Hive, dbt, Airflow-scheduled SQL | Kafka Streams, Flink, Spark Structured Streaming, Kinesis |
| Use | Reports, ML training sets, backfills, billing | Fraud, alerts, live dashboards, feature freshness |
| Complexity | Lower: rerun on failure | Higher: state, ordering, late data, exactly-once |
Lambda architecture: a batch layer (accurate, slow) plus a speed layer (approximate, fast), merged at read time; duplicate logic is its weakness. Kappa architecture: one streaming pipeline over a replayable log (Kafka) and reprocess by replaying; simpler if your stream engine is strong enough. Modern practice leans Kappa-like with a lakehouse for storage.
D.3 Stream processing concepts#
- Event time vs processing time: group by when the event happened, not when it arrived.
- Windows: tumbling (fixed, non-overlapping: per minute), sliding (overlapping: last 5 min every 1 min), session (gap-based per user).
- Watermarks and late data: a watermark says “no events older than T will arrive”; allow lateness, update results or send late events to a side output.
- State: keyed state (counts per user) stored locally with checkpoints to durable storage; parallelism by key.
- Delivery semantics: exactly-once state updates through checkpointing and transactional/idempotent sinks.
- Backpressure: a slow stage slows upstream rather than dropping or crashing; monitor lag and watermark delay.
- Joins: stream-stream (time-bounded), stream-table (enrich with a changelog).
- Idempotent sinks: upsert by key so replays do not duplicate.
D.4 CDC pipelines#
Change data capture reads the database log (WAL/binlog) and emits row changes: Debezium → Kafka → consumers feeding search indexes, caches, warehouses, and microservices. Benefits: no dual writes, low overhead, ordered per row. Care: schema changes, initial snapshot plus streaming handoff, deletes (tombstones), large transactions, replication slot growth if a consumer stalls (disk fills on the source), PII in the stream.
D.5 Warehouse, lake, lakehouse#
| Warehouse | Data lake | Lakehouse | |
|---|---|---|---|
| Data | Structured, modelled | Raw files (Parquet, JSON, images) in object storage | Lake files with table formats (Iceberg, Delta, Hudi) |
| Strength | Fast SQL, governance | Cheap, flexible, ML | ACID tables, time travel and schema evolution on cheap storage |
| Pattern | ELT with dbt | Schema-on-read | Bronze (raw) → silver (clean) → gold (aggregates) |
Partition files by date (and maybe tenant), use columnar formats (Parquet), compact small files, and keep a catalogue and lineage. Data quality checks (freshness, row counts, null rates, uniqueness) belong in the pipeline.
D.6 Specialised stores#
| Store | Examples | Use for |
|---|---|---|
| Time-series | InfluxDB, TimescaleDB, Prometheus, VictoriaMetrics | Metrics with timestamps; downsampling and retention tiers; high cardinality labels are the main danger |
| Columnar real-time OLAP | ClickHouse, Druid, Pinot | Sub-second analytics on streams (user-facing dashboards, ad analytics) |
| Search | Elasticsearch, OpenSearch | Text and faceted search, log search |
| Graph | Neo4j | Relationship traversals |
| Object storage | S3, GCS | Blobs, data lake, backups, media |
D.7 Object storage design (what S3 gives you)#
Flat key namespace of immutable objects (replace, do not edit), 11 nines durability via replication or erasure coding across AZs, cheap, with lifecycle policies (hot → infrequent → archive), versioning, presigned URLs for direct upload/download (the app never proxies large files), multipart upload for big files, strong read-after-write consistency, and event notifications to trigger processing. Limits: high latency per request (tens of ms), no in-place append or rename (copy), and request-rate limits per prefix (spread keys). Large uploads: client asks API for a presigned multipart URL, uploads chunks in parallel, then calls complete; an event triggers virus scan and transcoding.
D.8 Orchestration#
Airflow/Dagster for scheduled DAGs, Temporal/Step Functions for durable workflows. Pipelines must be idempotent and re-runnable by partition (overwrite a day’s partition, not append), have retries, SLAs, backfill support and alerts on freshness.
Most asked questions#
1. Batch or streaming for X? Decide by latency requirement and complexity budget: daily reports → batch; fraud or alerts → stream; both → stream with replay.
2. Explain Lambda vs Kappa. Lambda has parallel batch and speed layers merged at query time; Kappa uses a single replayable stream pipeline for both.
3. How do you get data from the OLTP DB to analytics without impacting it? CDC from the log to Kafka to the warehouse or lake; or a read replica for small cases.
4. How do you handle late events? Event-time windows with watermarks, allowed lateness, and corrections or a side output.
5. How do you make a pipeline idempotent? Deterministic partition overwrites, upserts by key, unique event IDs, checkpointed offsets.
6. Why columnar storage for analytics? Reads only needed columns, compresses well, vectorised execution.
7. How would you design a metrics platform? Agents → Kafka → stream aggregation → time-series store (hot) plus object storage (cold), downsampling and retention, with cardinality limits.
Senior-level questions#
1. “Your daily revenue number differs between dashboard and finance.” Different definitions (time zone, refunds, currency), late or duplicate events, non-idempotent loads, partial partitions, or stale data; fix with a single metric layer, reconciliation jobs and data contracts.
2. “A Debezium connector stalls and the source disk fills.” An inactive replication slot retains WAL; alert on slot lag, set max WAL limits, auto-drop dead slots, and monitor connector health.
3. “Handle a 10× traffic spike in the streaming job.” Autoscale parallelism up to partition count, repartition hot keys, backpressure, increase partitions in advance, shed or sample low-value events, and tune checkpointing.
4. “How do you backfill three years of data?” Separate backfill jobs by partition with throttling, same code path as production, idempotent writes, no impact on live resources, validate with reconciliation.
5. “How do you enforce data quality at scale?” Schema registry and contracts at the producer, tests and expectations in the pipeline (freshness, null rate, uniqueness), quarantine bad records, lineage and ownership.
Quiz#
1. Tumbling vs sliding vs session windows?
Tumbling: fixed, non-overlapping. Sliding: fixed size, overlapping, advancing by a smaller step. Session: dynamic windows closed by an inactivity gap.
2. What is a watermark?
A moving estimate of event-time progress: events older than the watermark are considered late.
3. Why partition lake data by date?
Queries prune partitions, and reruns/backfills overwrite exactly one partition idempotently.
4. Why can a stalled CDC consumer take down the source database?
The replication slot retains WAL until consumed, filling disk.
5. Why use presigned URLs for uploads?
The client uploads directly to object storage, so large files do not pass through (or load) your servers.