Designing Data-Intensive Applications
by Martin Kleppmann · 2017 · 8 min read
By Ajay Yadav ·
Note for frontend engineers: you don't need to memorize every algorithm. Focus on the trade-offs. That's what interviewers test.
Part I: Foundations of Data Systems
Reliable, Scalable, Maintainable
The three goals of any data system:
Reliability: works correctly even when things go wrong
- Faults (one component deviating) ≠ failures (whole system stops serving users). Design so faults don't cause failures.
- Fault types: hardware (disks die), software (bugs, cascading failures), human (config mistakes, the #1 cause of outages).
- Mitigations: redundancy, testing, monitoring, easy rollbacks, sandbox environments.
Scalability: handles growing load
- Describe load with load parameters: requests/sec, read/write ratio, active users, cache hit rate.
- Twitter example: Showing the home timeline. Option 1: query all followed users' tweets on read (slow reads). Option 2: fan-out on write: push each tweet into followers' timeline caches (fast reads, expensive writes for celebrities). Twitter uses a hybrid.
- Describe performance with percentiles, not averages:
- p50 (median), p95, p99, p999.
- Tail latency matters: the slowest requests often hit your most valuable users (more data).
- Scaling up (bigger machine) vs. scaling out (more machines).
Maintainability: easy for people to work with
- Operability: easy to run.
- Simplicity: manage complexity with good abstractions.
- Evolvability: easy to change.
Data Models & Query Languages
| Model | Best for | Examples |
|---|---|---|
| Relational | Structured data, many-to-many relationships, joins | PostgreSQL, MySQL |
| Document | Self-contained records, one-to-many trees, flexible schema | MongoDB, DynamoDB |
| Graph | Highly interconnected data (social, recommendations) | Neo4j |
- Impedance mismatch: awkward translation between objects in code and tables (why ORMs exist).
- Document model: better locality (whole record loaded at once), schema-on-read (flexible). Weak at joins and many-to-many.
- Relational: schema-on-write, strong joins.
- Modern databases are converging (Postgres supports JSON; MongoDB supports joins).
- Declarative queries (SQL) let the DB optimize; imperative code doesn't.
Storage & Retrieval (How DBs Store Data)
Two storage engine families
a) Log-structured (LSM-Trees): Cassandra, RocksDB, LevelDB
- Append writes to an in-memory sorted table (memtable), then flush to disk as SSTables (sorted files), then periodically compact/merge.
- ✅ Very fast writes (sequential). ❌ Reads may check multiple files (helped by Bloom filters).
b) Page-oriented (B-Trees): PostgreSQL, MySQL, most relational DBs
- Data in fixed-size pages, organized as a balanced tree. Updates overwrite in place. Write-ahead log (WAL) for crash recovery.
- ✅ Fast, predictable reads. ❌ Writes slower than LSM.
Rule of thumb: LSM for write-heavy. B-Tree for read-heavy.
Indexes
- Speed up reads, slow down writes. Choose indexes based on query patterns.
- Hash indexes, secondary indexes, multi-column indexes, full-text indexes.
OLTP vs. OLAP
| OLTP (transactions) | OLAP (analytics) |
|---|---|
| Many small reads/writes by key | Few huge queries scanning millions of rows |
| User-facing | Business intelligence |
| Row-oriented storage | Column-oriented storage (compresses well, reads only needed columns) |
| Postgres, MySQL | Data warehouses: BigQuery, Snowflake, Redshift, ClickHouse |
Encoding & Evolution
- Data must be encoded (serialized) to send over network or store.
- Formats: JSON/XML (human-readable, verbose), Protocol Buffers, Thrift, Avro (binary, compact, schema-based).
- Backward compatibility: new code reads old data.
- Forward compatibility: old code reads new data.
- Needed for rolling upgrades (old and new versions run simultaneously).
- Data flows via: databases, services (REST/RPC), async message passing (queues).
Part II: Distributed Data
Why distribute? Scalability, fault tolerance/high availability, lower latency (servers closer to users).
Replication: Copies of the Same Data on Multiple Nodes
Three approaches
| Approach | How | Trade-off |
|---|---|---|
| Single-leader | All writes go to one leader; followers copy | Simple; leader is a bottleneck/single point of failure |
| Multi-leader | Multiple nodes accept writes (e.g., one per datacenter) | Better availability; write conflicts must be resolved |
| Leaderless | Any node accepts writes; uses quorums (Dynamo-style: Cassandra, Riak) | Highly available; eventual consistency |
Sync vs. async replication
- Synchronous: leader waits for follower confirmation. Durable but slow.
- Asynchronous: faster, but data can be lost if leader fails.
Replication lag problems (eventual consistency)
- Read-your-own-writes: user updates profile, reloads, sees old data. Fix: read own data from leader.
- Monotonic reads: user sees newer data, then older (time travel). Fix: route a user to the same replica.
- Consistent prefix reads: see an answer before the question. Fix: causally related writes to same partition.
Quorums
With n replicas, write to w, read from r. If w + r > n, reads see the latest write (typical: n=3, w=2, r=2).
Conflict resolution
Last-write-wins (data loss risk), merge values, version vectors, CRDTs (data types that merge automatically, used in collaborative editing like Figma/Google Docs).
Partitioning (Sharding): Splitting Data Across Nodes
Goal: spread data and load evenly; avoid hot spots.
| Strategy | Pros | Cons |
|---|---|---|
| Key range (A-F, G-M…) | Efficient range queries | Hot spots (e.g., timestamps all hitting today's partition) |
| Hash of key | Even distribution | Range queries inefficient |
- Celebrity problem (skew): one hot key (a celebrity's ID) overloads a partition. Fix: add random suffix to split hot keys.
- Secondary indexes: local (per partition; reads scatter/gather) vs. global (partitioned by term; writes more complex).
- Rebalancing: use fixed number of partitions or dynamic partitioning, not
hash mod N(moving N reshuffles everything). Consistent hashing helps. - Request routing: client knows partition, a routing tier, or any node forwards (often coordinated with ZooKeeper).
Transactions
A transaction groups reads/writes into one logical unit: all succeed or all fail.
ACID
- Atomicity: all or nothing (abortability).
- Consistency: app-defined invariants hold (really the app's job).
- Isolation: concurrent transactions don't interfere.
- Durability: committed data survives crashes.
Isolation levels & race conditions
| Level | Prevents | Still allows |
|---|---|---|
| Read committed | Dirty reads, dirty writes | Read skew |
| Snapshot isolation (MVCC) | Read skew (each txn sees consistent snapshot) | Write skew, some lost updates |
| Serializable | Everything, as if run one at a time | Nothing (but slower) |
Key anomalies:
- Lost update: two users increment a counter; one update lost. Fix: atomic operations,
SELECT ... FOR UPDATE, compare-and-set. - Write skew: two doctors both go off-call because each sees the other is on-call. Fix: serializable isolation.
Ways to achieve serializability: actual serial execution (single thread, e.g., Redis/VoltDB), two-phase locking (2PL) (slow), serializable snapshot isolation (SSI) (optimistic, modern).
The Trouble With Distributed Systems
Everything that can go wrong will:
- Unreliable networks: packets lost, delayed, reordered. You can't distinguish a slow node from a dead one. Use timeouts.
- Unreliable clocks: clocks drift; don't rely on timestamps for ordering (use logical clocks).
- Process pauses: GC pauses can freeze a node for seconds; it may wake up thinking it's still the leader. Use fencing tokens.
- Truth is defined by the majority: a node can't trust its own judgment; use quorums.
Consistency & Consensus
- Linearizability: the system behaves as if there's one copy of the data; once a write is seen, all later reads see it. Strong but slow.
- CAP theorem: during a network Partition, choose Consistency or Availability. (Kleppmann notes CAP is oversimplified; think in terms of trade-offs.)
- Causality & ordering: Lamport timestamps, total order broadcast.
- Consensus: getting nodes to agree (leader election, atomic commit). Algorithms: Raft, Paxos, Zab. Tools: ZooKeeper, etcd.
- Two-phase commit (2PC): atomic commit across nodes; blocks if coordinator fails.
Part III: Derived Data
Batch Processing
- Process large, bounded datasets (e.g., nightly jobs).
- Unix philosophy: small tools, composed via pipes (the inspiration for MapReduce).
- MapReduce (Hadoop) led to modern dataflow engines (Spark, Flink) that are faster and more flexible.
- Outputs: search indexes, ML features, analytics.
Stream Processing
- Process unbounded data continuously as events arrive.
- Message brokers: traditional (RabbitMQ: messages deleted after consumption) vs. log-based (Kafka: durable, replayable log).
- Change Data Capture (CDC): stream DB changes to other systems (search index, cache).
- Event sourcing: store every change as an immutable event; derive current state.
- Use cases: real-time analytics, fraud detection, notifications.
- Challenges: time (event vs. processing time), windowing, exactly-once semantics.
The Future of Data Systems
- No single tool does everything. Combine specialized systems (DB + cache + search + queue + warehouse).
- System of record (source of truth) vs. derived data (caches, indexes, views, all rebuildable).
- Unbundling the database: use logs (Kafka) to keep systems in sync.
- Ethics: data has power; consider privacy, surveillance, and consent.
Cheat sheet
- Optimize for reliability, scalability, maintainability.
- Measure latency with p95/p99, not averages.
- Relational vs. document vs. graph: pick by data relationships.
- LSM (writes) vs. B-Tree (reads); OLTP row stores vs. OLAP column stores.
- Replication: single/multi/leaderless; understand replication lag.
- Partitioning: hash vs. range; watch for hot spots.
- Transactions: know isolation levels and anomalies (lost update, write skew).
- Networks and clocks lie; use timeouts, fencing, quorums.
- Consensus (Raft/ZooKeeper) for leader election and coordination.
- Batch (Spark) vs. stream (Kafka/Flink); CDC and event sourcing.
- Every decision is a trade-off: consistency vs. availability vs. latency vs. complexity.
How to apply it
- For HLD interviews: Always state load numbers, choose data model with justification, discuss replication + partitioning, caching, consistency requirements, and failure handling.
- Frontend system design overlap: Read-your-own-writes and optimistic UI updates; CRDTs for collaborative editors; caching and pagination strategies; real-time (WebSockets + Kafka-like event streams).
- Study plan: Ch. 1, 2, 3, 5, 6 and 7 first (core). Then 8-9 (distributed). Skim 10-12.
- Practical drill: Design Twitter timeline, URL shortener, chat app. Apply fan-out, partitioning, replication, and consistency trade-offs.
System Design Interview (Alex Xu) for interview-format practice; The Personal MBA (systems thinking and Gall's Law: start simple).
FAQ
What is Designing Data-Intensive Applications about?
Martin Kleppmann explains the trade-offs behind modern data systems: storage engines, replication, partitioning, transactions, consistency and batch and stream processing. The goal is systems that are reliable, scalable and maintainable.
Is DDIA good for system design interviews?
Yes, it is the standard reference for the reasoning behind high-level design. Pair it with an interview-format book like Alex Xu's System Design Interview for practice.
Which DDIA chapters should I read first for interviews?
Chapters 1 (reliability, scalability, maintainability), 2 (data models), 3 (storage and retrieval), 5 (replication), 6 (partitioning) and 7 (transactions) cover most of what interviews test.