Designing Data-Intensive Applications — Part I

👤 harshazampi📅 December 2, 2026⏱️ 16 min read📝 3,172 words
ENGINEERING STUDY SERIES · PART I OF III

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.

CHAPTER 1 · BOOK PP. 3–23 · 10 MIN

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

Client / API
Primary database
Change propagation
Cache / search index
API
Queue
Async worker
ComponentResponsibility
DatabaseDurable storage
CacheAvoid repeated computation
Search indexFast search and filtering
QueueAsynchronous communication
Batch / stream processorProcess 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.

FaultExampleMitigation
HardwareDisk or instance lossRedundancy, replication, failover
SoftwareBad input crashes replicas; cascading failureIsolation, tests, monitoring
HumanBad deployment or configurationCanaries, 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

ParameterExamples
Request rateAverage and peak QPS
Read/write ratio100:1
DataVolume, growth, payload size
ConcurrencyActive clients and workers
Fan-out and skewFollowers per author; hot keys
Cache effectivenessHit 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.

Fan-out on read
Fetch authors’ posts
Merge and sort
Timeline
Fan-out on write
New post
Fan-out workers
Follower caches
Trade-offPull on readPush on write
WritesCheapAmplified
ReadsExpensiveCheap
StorageLess duplicationMore duplication
Celebrity authorsCheap writesHuge 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

Timeline writes/sec345,000

Formula: posts/sec × average recipients per post.

1.4 Measuring performance

MetricMeaning
Response timeTotal observed client time
Latency (book terminology)Waiting before service begins
ThroughputCompleted operations per unit time
p50 / p95 / p9950% / 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

At least one slow dependency63.4%

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

StrategyTrade-off
VerticalSimple but bounded by machine capacity
HorizontalMore resources; coordination complexity
ElasticMatch resources to demand; requires scaling signals
CacheFast reads; staleness and invalidation
PrecomputeCheap reads; additional writes
AsyncOff critical path; eventual completion

1.6 Maintainability

PrinciplePractice
OperabilityMetrics, runbooks, health checks, automated recovery
SimplicityGood abstractions, minimal accidental complexity
EvolvabilityCompatible 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.

↑ Chapter navigation

CHAPTER 2 · BOOK PP. 27–64 · 10 MIN

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

ModelRepresentationBest fitExample
RelationalTables, foreign keys, joinsStructured related dataPostgreSQL
DocumentNested recordsSelf-contained aggregate readsMongoDB
GraphVertices and edgesVariable-depth connected dataNeo4j
Users
Employment join table
Companies
{"user_id":101,"employment":[{"company":"Amazon","role":"Engineer"}]}
User
Member of group
Assumes role
Can access resource

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.

PropertyNormalizedDenormalized
DuplicationLowHigh
ReadsMay need joinsOften cheaper
WritesSimplerSynchronization required
IntegrityEasierStaleness risk
RelationshipExampleNatural representation
1:1User / profileTable or document
1:NOrder / itemsEmbed or reference
N:1Employees / companyReference
N:MStudents / coursesJoin table or graph
Multi-hopFriends of friendsGraph 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';
Desired result
Query optimizer
Index / scan / join plan
Execution

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

Apple, Apple, Orange
Map: (key, 1)
Group by key
Reduce: Apple 2; Orange 1

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

WorkloadStarting point
Ledger and transactionsRelational
OrdersRelational or document
Product catalogDocument
Session lookupKey-value
Complex relationship traversalGraph
Full-text searchInverted index
High-volume event ingestKey-value or wide-column
ReportingColumn-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.

↑ Chapter navigation

CHAPTER 3 · BOOK PP. 69–104 · 20 MIN

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.

API / SQL
Query processor
Storage engine
Memory structures
Persistent pages / files

3.1 Append-only logs and hash indexes

user101,Alex
user102,Sam
user103,Jordan
user101,Alexander

Append-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:10, B:20, A:30
Compaction
A:30, B:20

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.

PUT(key, value)
Write-ahead log
Crash recovery
Memtable (RAM)
Sorted keys
↓ Flush when full
SSTable 1
SSTable 2
SSTable 3
↓ Merge / compact
Merged SSTable

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.

Read key
Memtable
Bloom filters
Relevant SSTables
Newest value / tombstone

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.

Hash key →010110010100

All selected bits are 1: possibly present. Any selected zero: definitely absent. This avoids unnecessary disk reads.

CompactionMechanismTrade-off
Size-tieredMerge similarly sized runsOften high write throughput; more overlap/duplicates
LeveledOrganize into progressively larger levelsLess 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.

Root: 30 | 60
↙   ↓   ↘
Keys < 30
30 ≤ keys < 60
Keys ≥ 60
↓
Leaf: 32, 41, 45, 55
Example lookup: 45

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

CharacteristicB-treeLSM-tree
Write pathPage updatesAppend, flush, merge
Point readsOften predictableMay check multiple runs
Range scansEfficientEfficient with merge overhead
Background workPage maintenanceCompaction essential
Write throughputWorkload-dependentOften high
Tail latencyOften predictableCompaction may interfere
SpacePage fragmentationOld versions, overlap
ExamplesPostgreSQL, InnoDBRocksDB, Cassandra, LevelDB

These are typical tendencies, not guarantees. Hardware, caching, engine implementation and workload can reverse them.

3.5 Amplification

TypeMeaningExample
WritePhysical bytes / logical bytes written1 GB → 4 GB = 4×
ReadPhysical work per logical readOne get → four block reads
SpaceOccupied bytes / live bytes150 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

Physical write throughput500 MB/s · 43.2 TB/day

Formula: logical MB/s × amplification. Excludes replication and other I/O.

3.6 Indexing structures

IndexPurpose
PrimaryLookup by primary key
SecondaryLookup by another attribute
ClusteredRecords stored in index structure
NonclusteredReferences to records
CoveringAnswer query from index alone
CompositeMultiple ordered attributes
InvertedTerms → documents
SpatialGeographic / 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.

TermPosting list
distributedD1, D2
systemsD1, D3
databasesD2
reliableD3

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

CharacteristicOLTPOLAP
AccessFew records per requestMillions of records per query
GoalLow per-request response timeFast scans and aggregation
BottleneckRandom I/O, contentionBandwidth and CPU
LayoutOften row-orientedOften column-oriented
ExamplesPostgreSQL, MySQLRedshift, Snowflake, ClickHouse
Row-oriented
ID 1 | Phone | US | 800
ID 2 | Laptop | UK | 1200
ID 3 | Tablet | India | 400
Column-oriented
ID: 1 | 2 | 3
Product: Phone | Laptop | Tablet
Region: US | UK | India
Price: 800 | 1200 | 400

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

Relative bytes read5.0% · 20× less data

Idealized full scan without indexes, compression or pruning; assumes equal column sizes.

3.8 Warehousing and derived data

Operational databases / events
ETL
Analytical warehouse
Reports

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.

Date
↓
Product →
Sales fact
amount, quantity
← Store
↑
Customer

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.

↑ Chapter navigation

CHAPTER 4 · BOOK PP. 111–140 · 10 MIN

Encoding and Evolution

Independent applications and stored data versions coexist. Encoding must support safe evolution, not merely efficient byte representation.

In-memory object
Serialize
Bytes on disk / network
Deserialize
Object

4.1 Encoding formats

FormatRepresentationTypical fit
JSON / XMLText, optional schemaAPIs and integration
CSVText, external schemaTabular export
MessagePackBinary, schema optionalCompact objects
Protobuf / ThriftSchema-driven binaryRPC and service contracts
AvroSchema-driven binaryEvent 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

Old writer V1
New reader V2
Backward compatible
New writer V2
Old reader V1
Forward compatible

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 changeCompatibility
Add optional fieldGenerally safe
Remove optional fieldGenerally safe at wire level
Rename retaining tagUsually wire-compatible, not necessarily source compatible
Change or reuse field tagDangerous / breaking
Add mandatory fieldCan break old data
Change datatypeCheck format-specific rules

4.4 Avro

Writer schema V1
Schema resolution
Reader schema V2

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.

PropertyProtobufAvro
Field identityNumeric tagField name through resolution
Writer schemaNot separately needed for known fieldsRequired
Code generationCommonOptional
Typical fitRPCEvent and data pipelines

4.5 Modes of dataflow

Writer
Database
Reader
Client
REST / RPC
Service
Producer
Broker / queue
Consumer

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

RESTRPC
Resource-orientedOperation-oriented
GET /scans/123GetScan(123)
Often JSONOften 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

Add new field
Deploy compatible readers
Dual-write if needed
Backfill
Switch reads
Remove old field

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.

↑ Chapter navigation

APPLIED SYSTEM DESIGN · REVISION

Connecting Part I together

Quantify reliability & scale
Choose model
Choose storage
Design for evolution

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.

Event sources
Ingestion queue
Deduplication
Scan workers
Operational store / analytics
ConceptApplication
Fault toleranceBounded retries; isolate malformed or huge inputs
Load parametersPeak ingest, unique digests, queue age, duration
Tail latencyp95/p99 scan duration and end-to-end freshness
Data modelDigest identity, scan results, account associations
NormalizationReuse digest scan results where validity permits
DenormalizationPrecomputed account summaries
IndexesAccount, digest, status access patterns
OLTP/OLAPOperational reads separated from analytical scans
Schema evolutionOld and new event formats coexist
OperabilityBacklog, throttling, error rates and freshness

Revision priorities

Must knowHigh priorityLower priority
Fault/failure, correlated faults, load, fan-out, tail latencySchema-on-read/write, localitySPARQL/Datalog syntax
Normalization, relational/document/graphHash indexes, materialized viewsDetailed historical implementations
B-tree, LSM, SSTable, WAL, Bloom filters, compaction, amplificationProtobuf vs. AvroExact byte encodings
OLTP/OLAP, indexes, column storage, compatibility, safe migrationStar/snowflake schemasAcademic references

Next: Part II — Distributed Data

Chapters 5–9 cover replication, partitioning, transactions, partial failures, consistency and consensus. Those will become the next installment.

15 QUESTIONS · ACTIVE RECALL

Part I assessment

Answer before revealing the explanations. The interactive score is calculated in your browser.

1. 100 replicas crash on the same malformed request. Why?
Reveal answer

Correlated software fault. Identical replicas can share the same bug.

2. 5,000 posts/sec × 200 followers yields?
Reveal answer

1,000,000 writes/sec. Multiply logical posts by recipients.

3. 100 independent parallel calls, each 1% slow. Probability at least one is slow?
Reveal answer

63.4%. 1 − 0.99^100 ≈ 63.4%.

4. What is the risk of denormalizing employer data?
Reveal answer

Many copies to update. Duplicate records must be synchronized.

5. Natural model for variable-depth authorization relationships?
Reveal answer

Graph. Explicit edges support traversal.

6. Why are LSM writes often efficient?
Reveal answer

Sequentialize random writes. Memtables and sorted flushes batch random updates.

7. Negative Bloom filter means?
Reveal answer

Definitely absent. A correctly maintained standard Bloom filter has no false negatives.

8. Compaction cannot keep up. What happens?
Reveal answer

Files accumulate; amplification rises. Compaction debt can increase latency and cause throttling.

9. 200 MB/s logical, 6× write amplification?
Reveal answer

1,200 MB/s. 200 × 6 = 1,200 MB/s.

10. Why are B-trees shallow?
Reveal answer

High branching factor. Many references fit in each page.

11. Read 5 out of 150 columns across billions of rows. Prefer?
Reveal answer

Column store. Read only required columns.

12. Materialized view trade-off?
Reveal answer

Fast reads for extra storage and maintenance. Precomputation shifts work to refresh or write time.

13. V2 consumer reads V1 producer messages. Property?
Reveal answer

Backward. New code reads old data.

14. Dangerous Protobuf evolution?
Reveal answer

Reuse deleted tag. Historical data may be interpreted incorrectly.

15. Payment RPC times out. Assume?
Reveal answer

Outcome unknown. The response may be lost after a successful payment.

Source: Martin Kleppmann, Designing Data-Intensive Applications, O’Reilly Media, 2017, Part I, Chapters 1–4 (printed pages 3–140). Original condensed notes and examples. See the book for historical context, detailed encoding diagrams and references.