Foundations of Data Systems
Condensed study notes from Martin Kleppmann’s Designing Data-Intensive Applications (2017 first edition), with senior engineering applications and FAANG-style practice. Four chapters · approximately 50 minutes of study.
Historical Twitter workload and storage-engine concepts follow the book. Illustrative architecture, interview drills, calculators and migration advice are supplementary engineering examples; product-specific details are not a current-version audit.
Reliable, Scalable, and Maintainable Applications
Design begins with three qualities: reliability (correct behavior despite faults), scalability (handling growth in specified dimensions), and maintainability (making ongoing operation and change manageable).
1.1 Thinking about data systems
| Component | Responsibility |
|---|---|
| Database | Durable storage |
| Cache | Avoid repeated computation |
| Search index | Fast search and filtering |
| Queue | Asynchronous communication |
| Batch / stream processor | Process accumulated / incoming data |
A successful database write followed by a failed cache invalidation can return stale information. A service owns its end-to-end guarantees, not merely the health of each dependency.
1.2 Reliability: fault versus failure
A fault is a component deviating from its expected behavior. A failure is the whole system failing to deliver its required service. Fault tolerance prevents a component fault from becoming a system-wide failure.
| Fault | Example | Mitigation |
|---|---|---|
| Hardware | Disk or instance loss | Redundancy, replication, failover |
| Software | Bad input crashes replicas; cascading failure | Isolation, tests, monitoring |
| Human | Bad deployment or configuration | Canaries, guardrails, rollback |
Correlated faults are particularly dangerous: identical replicas can all crash on the same malformed input. Practical defenses include deadlines, bounded retries with jitter, idempotency, circuit breakers, backpressure, chaos tests, and blast-radius isolation. Retries themselves can amplify overload.
1.3 Scalability and load parameters
| Parameter | Examples |
|---|---|
| Request rate | Average and peak QPS |
| Read/write ratio | 100:1 |
| Data | Volume, growth, payload size |
| Concurrency | Active clients and workers |
| Fan-out and skew | Followers per author; hot keys |
| Cache effectiveness | Hit rate, eviction, miss cost |
Twitter’s historical 2012 workload in the book: 4,600 posts/sec on average and 300,000 timeline reads/sec. A read-heavy feed can shift work from reads to writes.
| Trade-off | Pull on read | Push on write |
|---|---|---|
| Writes | Cheap | Amplified |
| Reads | Expensive | Cheap |
| Storage | Less duplication | More duplication |
| Celebrity authors | Cheap writes | Huge fan-out |
At 75 recipients per post, 4,600 posts/sec become 345,000 timeline writes/sec. Use a hybrid: precompute ordinary accounts, merge high-fan-out authors’ posts at read time. Measure follower distribution, not just averages.
Fan-out calculator
Formula: posts/sec × average recipients per post.
1.4 Measuring performance
| Metric | Meaning |
|---|---|
| Response time | Total observed client time |
| Latency (book terminology) | Waiting before service begins |
| Throughput | Completed operations per unit time |
| p50 / p95 / p99 | 50% / 95% / 99% finish within this duration |
Averages hide tail latency. Example: p50 = 25 ms, p95 = 110 ms, p99 = 450 ms, p99.9 = 1,800 ms. With 100 independent parallel dependencies, each having a 1% chance of being slow, the chance of at least one slow dependency is 1 − 0.99¹⁰⁰ ≈ 63.4%. This assumes the API waits for all calls. Real correlated latency can behave differently.
Tail latency simulator
Formula: 1 − (1 − p)^N, assuming independence.
Queueing and head-of-line blocking increase response time. Load tests should not hide overload by issuing requests only after prior requests finish.
1.5 Scaling strategies
| Strategy | Trade-off |
|---|---|
| Vertical | Simple but bounded by machine capacity |
| Horizontal | More resources; coordination complexity |
| Elastic | Match resources to demand; requires scaling signals |
| Cache | Fast reads; staleness and invalidation |
| Precompute | Cheap reads; additional writes |
| Async | Off critical path; eventual completion |
1.6 Maintainability
| Principle | Practice |
|---|---|
| Operability | Metrics, runbooks, health checks, automated recovery |
| Simplicity | Good abstractions, minimal accidental complexity |
| Evolvability | Compatible contracts, modularity, safe migrations |
Interview drill
Fault vs. failure?
A component fault becomes a failure when the system violates its service guarantee.
Why do replicas not guarantee reliability?
Shared bugs, config and dependencies create correlated failures.
How would you design a feed?
Quantify read/write ratios and follower skew, then choose pull, push or a hybrid.
Why p99 rather than mean?
Percentiles expose slow requests that averages conceal.
How do you handle 10× growth?
Measure bottlenecks, identify skew and growth dimensions; evaluate caching, partitioning and capacity.
What makes systems maintainable?
Operational visibility, understandable abstractions and safe evolution.
Data Models and Query Languages
Data models determine how applications express relationships, query data, and evolve. Choose by access patterns rather than database popularity.
2.1 Relational, document and graph models
| Model | Representation | Best fit | Example |
|---|---|---|---|
| Relational | Tables, foreign keys, joins | Structured related data | PostgreSQL |
| Document | Nested records | Self-contained aggregate reads | MongoDB |
| Graph | Vertices and edges | Variable-depth connected data | Neo4j |
{"user_id":101,"employment":[{"company":"Amazon","role":"Engineer"}]}NoSQL does not inherently mean faster or more scalable. Document models reduce object-relational mismatch when data is nested; references and cross-document relationships can reintroduce join complexity.
2.2 Normalization and denormalization
If one million user records contain a duplicated company name, renaming it may require one million updates. With normalized references, one company record changes. Denormalization moves work from reads to writes.
| Property | Normalized | Denormalized |
|---|---|---|
| Duplication | Low | High |
| Reads | May need joins | Often cheaper |
| Writes | Simpler | Synchronization required |
| Integrity | Easier | Staleness risk |
| Relationship | Example | Natural representation |
|---|---|---|
| 1:1 | User / profile | Table or document |
| 1:N | Order / items | Embed or reference |
| N:1 | Employees / company | Reference |
| N:M | Students / courses | Join table or graph |
| Multi-hop | Friends of friends | Graph or recursive SQL |
2.3 Schema and locality
Schema-on-write: validate before storing. Schema-on-read: interpret and validate when reading. Schemaless does not mean no expected structure; enforcement may move to application code. Data locality improves retrieval when related data is stored together. Large embedded records can be costly when only a small portion is needed.
2.4 Declarative vs. imperative queries
SELECT * FROM users WHERE country = 'US';Declarative SQL specifies what to retrieve; the engine chooses how. An imperative loop fixes the execution strategy. A query optimizer can use a new index without application changes.
2.5 MapReduce querying
Map and reduce functions restrict computation in a way that supports parallel processing. Aggregation pipelines offer declarative alternatives. Distributed batch processing is explored in Chapter 10.
2.6 Graph models
Property graphs attach properties to vertices and edges. RDF triple-stores represent subject–predicate–object facts. Cypher matches graph patterns, SPARQL queries RDF, Datalog derives facts using reusable recursive rules, and recursive SQL can traverse relationships. Use graphs when variable-depth traversals dominate, not merely because relationships exist.
2.7 Database selection guide
| Workload | Starting point |
|---|---|
| Ledger and transactions | Relational |
| Orders | Relational or document |
| Product catalog | Document |
| Session lookup | Key-value |
| Complex relationship traversal | Graph |
| Full-text search | Inverted index |
| High-volume event ingest | Key-value or wide-column |
| Reporting | Column-oriented analytical store |
Interview drill
When prefer a document database?
When entities are self-contained, nested and retrieved together, with few cross-document relationships.
When denormalize?
When measurable read benefits justify write cost, duplication and synchronization.
Are NoSQL databases schemaless?
Usually structure still exists; validation may be handled at read time.
Why declarative languages?
The engine can optimize execution independently of the query.
When use graphs?
When multi-hop or variable-depth relationship traversal is central.
Does NoSQL eliminate joins?
No. Application-side joins can add network calls and complexity.
Storage and Retrieval
Database data models are distinct from physical storage engines. The storage engine determines how records are laid out, indexed, retrieved and modified.
3.1 Append-only logs and hash indexes
user101,Alex
user102,Sam
user103,Jordan
user101,AlexanderAppend-only writes are sequential and simple. A scan to find the newest record is O(n). A memory hash index maps a key to its newest disk offset; lookup is expected O(1), followed by a disk read. It must fit in memory and cannot efficiently support ordered range scans.
A tombstone marks a deletion. Compaction removes obsolete versions and tombstones when safe. Crash recovery needs a reliable persisted log or equivalent mechanism.
3.2 SSTables and LSM-trees
A sorted string table (SSTable) is an immutable sorted key-value file. Log-Structured Merge-trees (LSMs) turn many random updates into sequential writes.
Crash recovery
Sorted keys
Write: record operation in WAL, update memtable, flush sorted data to immutable SSTable, compact files in background. Durability depends on when WAL writes are acknowledged.
Sparse indexes locate blocks; sorted files support range scans and efficient merging. A Bloom filter tests set membership: definitely absent or possibly present. It permits false positives but no false negatives when correctly maintained.
All selected bits are 1: possibly present. Any selected zero: definitely absent. This avoids unnecessary disk reads.
| Compaction | Mechanism | Trade-off |
|---|---|---|
| Size-tiered | Merge similarly sized runs | Often high write throughput; more overlap/duplicates |
| Leveled | Organize into progressively larger levels | Less overlap and space overhead; more rewrite work |
Compaction consumes I/O and CPU. If it cannot keep up, SSTables accumulate, read latency rises, and writes may be throttled.
3.3 B-trees
Traditional B-tree engines update fixed-size pages. Nodes contain sorted separators and references to child pages; high branching factors keep the tree shallow. Root and internal pages are frequently cached.
Writes locate a leaf, modify it and split if full. Splits can propagate upward. A WAL records changes before corresponding modified pages are persisted, enabling recovery; some engines instead use copy-on-write.
3.4 B-tree vs. LSM-tree
| Characteristic | B-tree | LSM-tree |
|---|---|---|
| Write path | Page updates | Append, flush, merge |
| Point reads | Often predictable | May check multiple runs |
| Range scans | Efficient | Efficient with merge overhead |
| Background work | Page maintenance | Compaction essential |
| Write throughput | Workload-dependent | Often high |
| Tail latency | Often predictable | Compaction may interfere |
| Space | Page fragmentation | Old versions, overlap |
| Examples | PostgreSQL, InnoDB | RocksDB, Cassandra, LevelDB |
These are typical tendencies, not guarantees. Hardware, caching, engine implementation and workload can reverse them.
3.5 Amplification
| Type | Meaning | Example |
|---|---|---|
| Write | Physical bytes / logical bytes written | 1 GB → 4 GB = 4× |
| Read | Physical work per logical read | One get → four block reads |
| Space | Occupied bytes / live bytes | 150 GB / 100 GB = 1.5× |
B-trees may write a WAL plus whole data pages. LSMs repeatedly rewrite data during compaction. Size disks and throughput using physical workload, not just logical QPS.
Storage capacity calculator
Formula: logical MB/s × amplification. Excludes replication and other I/O.
3.6 Indexing structures
| Index | Purpose |
|---|---|
| Primary | Lookup by primary key |
| Secondary | Lookup by another attribute |
| Clustered | Records stored in index structure |
| Nonclustered | References to records |
| Covering | Answer query from index alone |
| Composite | Multiple ordered attributes |
| Inverted | Terms → documents |
| Spatial | Geographic / multidimensional lookup |
CREATE INDEX idx_scans ON scans(account_id, scan_date);The ordered composite index works well for account_id alone, both fields, or an account plus a date range. Filtering only by scan_date may be inefficient. Some engines support alternative optimizations. A covering index such as (account_id, status) can answer SELECT status WHERE account_id = … without retrieving the base record, subject to engine rules.
| Term | Posting list |
|---|---|
| distributed | D1, D2 |
| systems | D1, D3 |
| databases | D2 |
| reliable | D3 |
Intersect posting lists for a keyword AND search. In-memory stores avoid disk-oriented access overhead; durability may use WALs, snapshots and replication. Every extra index increases write and storage cost.
3.7 OLTP vs. OLAP
| Characteristic | OLTP | OLAP |
|---|---|---|
| Access | Few records per request | Millions of records per query |
| Goal | Low per-request response time | Fast scans and aggregation |
| Bottleneck | Random I/O, contention | Bandwidth and CPU |
| Layout | Often row-oriented | Often column-oriented |
| Examples | PostgreSQL, MySQL | Redshift, Snowflake, ClickHouse |
SUM(price) can read only price values in a column store. Similar values compress well using bitmap and run-length encoding, and support vectorized processing. Sorting improves compression and pruning. Buffered and batched writes address expensive row updates.
Column scan calculator
Idealized full scan without indexes, compression or pruning; assumes equal column sizes.
3.8 Warehousing and derived data
Separating analytical scans protects operational workloads. A star schema has a central fact table of events and surrounding dimensions such as date, product, customer and store. A snowflake schema further normalizes dimensions.
amount, quantity
A normal view defines a query; a materialized view stores its result and requires maintenance or refresh. Data cubes precompute aggregates across dimensions. Fast reads cost extra storage, updates and potential staleness; retain raw data for flexible queries.
Interview drill
LSM write path?
WAL, memtable, flush to immutable SSTable, then compaction.
Why efficient writes?
Batch and sequentialize random updates; trade off compaction and read amplification.
Why predictable B-tree reads?
High branching factor and bounded page traversal.
What do Bloom filters do?
Skip files that definitely lack the key.
What if compaction falls behind?
More files and overlap, increased latency and eventual write throttling.
Why WAL?
Recover durable changes after crashes before corresponding data pages are persisted.
Why indexes hurt writes?
Every affected index must be maintained.
Why column stores for analytics?
Read fewer columns, compress effectively, and vectorize operations.
Why isolate analytics?
Prevent large scans from degrading operational workloads.
Materialized view trade-off?
Faster reads versus refresh cost, storage and freshness.
Encoding and Evolution
Independent applications and stored data versions coexist. Encoding must support safe evolution, not merely efficient byte representation.
4.1 Encoding formats
| Format | Representation | Typical fit |
|---|---|---|
| JSON / XML | Text, optional schema | APIs and integration |
| CSV | Text, external schema | Tabular export |
| MessagePack | Binary, schema optional | Compact objects |
| Protobuf / Thrift | Schema-driven binary | RPC and service contracts |
| Avro | Schema-driven binary | Event and data pipelines |
Language-specific serialization creates coupling, compatibility and security risks. JSON is readable but can be ambiguous about numbers and binary data. Binary schemas provide defined compatibility rules and often reduce storage and network cost.
4.2 Compatibility
Both are useful during rolling upgrades. Wire compatibility does not guarantee semantic compatibility: units, defaults or meaning may change despite successful decoding.
4.3 Protocol Buffers and Thrift
message ScanResult {
string scan_id = 1;
string account_id = 2;
string status = 3;
int64 duration_ms = 4; // added in V2
}Numerical tags identify fields rather than transmitting full field names. Old readers can generally ignore unfamiliar fields; new readers interpret missing fields using format-specific defaults and presence rules.
| Schema change | Compatibility |
|---|---|
| Add optional field | Generally safe |
| Remove optional field | Generally safe at wire level |
| Rename retaining tag | Usually wire-compatible, not necessarily source compatible |
| Change or reuse field tag | Dangerous / breaking |
| Add mandatory field | Can break old data |
| Change datatype | Check format-specific rules |
4.4 Avro
Avro uses the writer and reader schemas to decode data and matches record fields by name. No per-field numeric tags in the binary data. When the new reader expects a missing field, a suitable reader default can fill it. The writer schema must be available through metadata, an identifier or a schema repository.
| Property | Protobuf | Avro |
|---|---|---|
| Field identity | Numeric tag | Field name through resolution |
| Writer schema | Not separately needed for known fields | Required |
| Code generation | Common | Optional |
| Typical fit | RPC | Event and data pipelines |
4.5 Modes of dataflow
Database records can outlive the code that created them. An old reader that rewrites a new record must preserve unknown fields or risk erasing newer data. Brokers decouple deployments and buffer work but introduce lag, ordering, duplicates, retry and compatibility requirements. Actors encapsulate local state and process messages one at a time; delivery semantics depend on the implementation.
4.6 REST versus RPC
| REST | RPC |
|---|---|
| Resource-oriented | Operation-oriented |
| GET /scans/123 | GetScan(123) |
| Often JSON | Often schema-driven binary |
A remote call is not a local function call: network failures, latency and uncertain outcomes are fundamental. After a payment timeout, the server may have never received it, failed, or completed it while losing the response. Use idempotency keys and safe retry semantics for side effects.
4.7 Expand-and-contract schema migration
Example: replace image_name with image_digest. Keep both fields while old and new consumers coexist; validate the backfill, monitor correctness and remove the old field only after old consumers, rollback needs and retained messages have been addressed.
Interview drill
Backward compatibility?
New reader can interpret old data.
Forward compatibility?
Old reader can interpret new data.
Why Protobuf over JSON?
Compact encoding, schemas, code generation and evolution rules, with additional tooling.
Avro vs. Protobuf?
Writer/reader schema resolution versus stable numeric tags.
Zero-downtime migration?
Expand, compatible readers and writers, backfill, switch reads, contract.
Why is RPC unlike a local call?
Partial failure and ambiguous outcomes require deadlines and safe retries.
Can wire-compatible changes break production?
Yes, incompatible semantics, defaults or units can still cause errors.
Connecting Part I together
Case study: container vulnerability scanning
Illustrative system ingesting 15 million events/day: average ≈174 events/sec; a hypothetical 10× peak ≈1,736/sec; annual volume ≈5.48 billion events. Average throughput is not enough to size scan workers: measure event fan-out, unique digests, processing duration, queue age and bursts.
| Concept | Application |
|---|---|
| Fault tolerance | Bounded retries; isolate malformed or huge inputs |
| Load parameters | Peak ingest, unique digests, queue age, duration |
| Tail latency | p95/p99 scan duration and end-to-end freshness |
| Data model | Digest identity, scan results, account associations |
| Normalization | Reuse digest scan results where validity permits |
| Denormalization | Precomputed account summaries |
| Indexes | Account, digest, status access patterns |
| OLTP/OLAP | Operational reads separated from analytical scans |
| Schema evolution | Old and new event formats coexist |
| Operability | Backlog, throttling, error rates and freshness |
Revision priorities
| Must know | High priority | Lower priority |
|---|---|---|
| Fault/failure, correlated faults, load, fan-out, tail latency | Schema-on-read/write, locality | SPARQL/Datalog syntax |
| Normalization, relational/document/graph | Hash indexes, materialized views | Detailed historical implementations |
| B-tree, LSM, SSTable, WAL, Bloom filters, compaction, amplification | Protobuf vs. Avro | Exact byte encodings |
| OLTP/OLAP, indexes, column storage, compatibility, safe migration | Star/snowflake schemas | Academic references |
Next: Part II — Distributed Data
Chapters 5–9 cover replication, partitioning, transactions, partial failures, consistency and consensus. Those will become the next installment.
Part I assessment
Answer before revealing the explanations. The interactive score is calculated in your browser.