Designing Data-Intensive ApplicationsParts I-III (complete book) · condensed, chapter by chapter
Part I

Foundations of Data Systems

The first four chapters go through the fundamental ideas that apply to all data systems, whether running on a single machine or distributed across a cluster of machines. Later, Part II turns to the particular issues of distributed data systems.

Chapter 1

Reliable, Scalable, and Maintainable Applications

The fundamentals of what we are trying to achieve with data systems: what reliability, scalability and maintainability actually mean, and ways of thinking about each.

Key takeaways

  • Most applications are data-intensive: the hard part is the amount, complexity and rate of change of data, not CPU.
  • Combining a database, cache, index and queue behind an API makes you a data system designer, responsible for its guarantees.
  • A fault is one component deviating from spec; a failure is the whole system no longer serving users. Design so faults do not become failures.
  • Hardware faults are random and uncorrelated; software faults are systematic and correlated; operator configuration errors were the leading cause of outages in one study.
  • Scalability is not a label. Describe load with load parameters (e.g. Twitter's followers-per-user distribution), then ask what happens as they grow.
  • Measure response time as a distribution: use the median and high percentiles (p95, p99, p999), not the mean.
  • One slow backend call slows the whole end-user request (tail latency amplification).
  • Maintainability = operability, simplicity (remove accidental complexity via abstraction) and evolvability.

Thinking About Data Systems

Data-intensive applications are assembled from standard building blocks:

  • Databases: store data so it can be found again later.
  • Caches: remember the result of an expensive operation to speed up reads.
  • Search indexes: search by keyword or filter data in various ways.
  • Stream processing: send a message to another process to be handled asynchronously.
  • Batch processing: periodically crunch a large amount of accumulated data.

There are many variants of each tool, so you still have to choose the right ones and combine them when no single tool does the job.

Why group databases, queues and caches under one term, data systems?

  • Category boundaries are blurring: Redis is a datastore also used as a message queue; Apache Kafka is a message queue with database-like durability.
  • Demanding applications cannot be served by one tool. Work is split into tasks each tool does well, stitched together with application code.
  • Example: with an application-managed cache (Memcached) or a separate full-text server (Elasticsearch, Solr), the application code must keep them in sync with the main database.
Client API Application code keeps all in sync Cache (Memcached) Primary database Full-text index Message queue
A composite data system: general-purpose parts hidden behind one API (after Figure 1-1).
  • The API hides the parts from clients. You have built a new special-purpose data system, which may promise guarantees (e.g. the cache is correctly invalidated or updated on writes).
  • Hard questions follow: keeping data correct and complete when things fail internally, consistent performance when parts are degraded, scaling with load, and what a good API looks like.
  • Design is also shaped by people's skills, legacy dependencies, delivery timescale, risk tolerance and regulation.

The book focuses on three concerns:

  • Reliability: keeps working correctly (right function, desired performance) despite hardware, software or human faults.
  • Scalability: reasonable ways to deal with growth in data volume, traffic volume or complexity.
  • Maintainability: many different people, over time, can work on the system productively.

Reliability

Typical expectations for software: it does what the user expected, tolerates user mistakes, performs well enough for the expected load and data volume, and prevents unauthorized access. Reliability is, roughly, continuing to work correctly even when things go wrong.

  • Faults are the things that can go wrong. Systems that cope with them are fault-tolerant or resilient.
  • "Fault-tolerant" is slightly misleading: you cannot tolerate every possible fault, only certain types.
  • Fault vs failure: a fault is one component deviating from its spec; a failure is the system as a whole no longer providing the required service.
  • Fault probability cannot reach zero, so build mechanisms that stop faults from becoming failures: reliable systems from unreliable parts.
Fault component off spec Fault tolerance redundancy, retry contained Service OK not handled Failure
Fault tolerance keeps a component fault from becoming a system failure.
  • Deliberately inducing faults (e.g. randomly killing processes) makes sense: many critical bugs are poor error handling, and this keeps the fault-tolerance machinery exercised. Example: Netflix Chaos Monkey.
  • Tolerating faults is generally preferred to preventing them, but prevention wins where no cure exists, e.g. security: leaked sensitive data cannot be undone. The book mostly covers curable faults.

Hardware Faults

  • Disks crash, RAM goes bad, power fails, cables get unplugged. With many machines this happens all the time.
  • Disk MTTF is about 10 to 50 years, so a 10,000-disk cluster should expect on average one disk dying per day.
  • First response: hardware redundancy (RAID, dual power supplies, hot-swappable CPUs, batteries and diesel generators). Well understood; can keep a machine up for years.
  • Until recently that sufficed: single-machine total failure was rare, and restoring a backup onto a new machine was quick enough. Multi-machine redundancy was only for apps that truly needed high availability.
  • Now apps use more machines (proportionally more faults), and cloud platforms like AWS can make VM instances unavailable without warning, prioritizing flexibility and elasticity over single-machine reliability.
  • So the trend is toward software fault tolerance that survives the loss of whole machines, in preference or in addition to hardware redundancy.
  • Operational bonus: patch one node at a time with no full-system downtime (a rolling upgrade, Chapter 4), instead of planned downtime for a single server.

Software Errors

  • Hardware faults are mostly random and independent (weak correlations such as rack temperature aside).
  • Systematic errors are correlated across nodes, harder to anticipate, and cause many more failures. Examples:
    • A bug that crashes every app server instance on a particular bad input (the June 30, 2012 leap second hung many applications via a Linux kernel bug).
    • A runaway process exhausting a shared resource: CPU, memory, disk or network bandwidth.
    • A dependency that slows down, stops responding, or returns corrupted responses.
    • Cascading failures: a small fault in one component triggers faults in others.
  • These bugs lie dormant until unusual circumstances break an assumption about the environment that was usually true.
  • No quick fix; many small things help: think carefully about assumptions and interactions, test thoroughly, isolate processes, let processes crash and restart, and measure, monitor and analyze behavior in production.
  • A system that promises a guarantee can check it continuously at runtime and alert on a discrepancy (e.g. a message queue's incoming count equals outgoing count).

Human Errors

  • One study of large internet services: operator configuration errors were the leading cause of outages; hardware (servers or network) played a role in only 10–25%.
Hardware random uncorrelated 10k disks: ~1 dies per day fix: redundancy Software systematic correlated bad input, runaway, cascading failure fix: many small things Human config errors top outage cause hardware: only 10–25% of outages fix: design, test, undo
The three fault classes the chapter covers and how each is typically handled.

The best systems combine several approaches:

  • Minimize opportunities for error: good abstractions, APIs and admin interfaces make the right thing easy. Too restrictive, and people work around them.
  • Decouple where people make mistakes from where they cause failures: full-featured non-production sandbox environments with real data and no real users.
  • Test thoroughly at all levels: unit, whole-system integration and manual tests. Automated tests are especially valuable for rare corner cases.
  • Quick, easy recovery: fast config rollback, gradual code rollout (bugs hit only a small subset of users), tools to recompute data.
  • Detailed, clear monitoring (telemetry): performance metrics and error rates give early warnings, show violated assumptions, and help diagnose problems.
  • Good management practices and training (out of the book's scope).

How Important Is Reliability?

  • Not just for nuclear plants and air traffic control: business-app bugs cost productivity (and legal risk if figures are wrong); ecommerce outages cost revenue and reputation.
  • Even "noncritical" apps carry responsibility to users, e.g. a parent's photos and videos of their children in a photo app that gets corrupted.
  • You may sacrifice reliability to cut development cost (a prototype for an unproven market) or operational cost (a narrow-margin service), but do it consciously.

Scalability

  • Working reliably today does not guarantee it tomorrow. A common reason for degradation is increased load (10,000 to 100,000 concurrent users, or 1 million to 10 million; much more data).
  • Scalability = a system's ability to cope with increased load. It is not a one-dimensional label: "X is scalable" is meaningless.
  • The real questions: "If the system grows in a particular way, what are our options?" and "How can we add computing resources to handle the extra load?"

Describing Load

  • First describe current load with a few numbers, load parameters; only then discuss growth ("what if load doubles?").
  • Which parameters depends on the architecture: requests/sec to a web server, read/write ratio in a database, simultaneously active users in a chat room, cache hit rate, etc.
  • Sometimes the average case matters; sometimes a few extreme cases dominate the bottleneck.

Twitter example (data from November 2012):

  • Post tweet: 4.6k requests/sec average, over 12k/sec at peak.
  • Home timeline: view tweets from people you follow, 300k requests/sec.
  • 12k writes/sec alone would be easy. The challenge is fan-out: each user follows many people and is followed by many. (Fan-out here: the number of requests to other services needed to serve one incoming request.)

Approach 1: merge at read time. Posting inserts into a global tweets collection. Reading a timeline looks up everyone you follow, finds their tweets and merges by time. In a relational schema (Figure 1-2):

SELECT tweets.*, users.* FROM tweets
  JOIN users   ON tweets.sender_id    = users.id
  JOIN follows ON follows.followee_id = users.id
  WHERE follows.follower_id = current_user

Approach 2: fan out at write time. Keep a per-user home timeline cache, like a mailbox. Posting looks up all followers and inserts the tweet into each one's cache, so reading is cheap: the result was computed ahead of time (Figure 1-3).

Approach 1: work at read time Post tweet Global tweets Read timeline join + merge per read 300k/s Approach 2: work at write time (fan-out) Post tweet 4.6k/s Fan-out ~75 followers Timeline cache Timeline cache Timeline cache 345k cache writes/s cheap read
Two ways to build the home timeline (after Figures 1-2 and 1-3), with November 2012 load parameters.
  • Twitter started with approach 1, struggled with timeline-read load, and switched to approach 2.
  • Approach 2 wins because published tweets are almost two orders of magnitude rarer than timeline reads, so do more at write time and less at read time.
  • Cost: an average tweet reaches ~75 followers, so 4.6k tweets/sec become 345k writes/sec to timeline caches.
  • Averages hide skew: some users have over 30 million followers, so one tweet can mean 30M+ timeline writes. Twitter aims to deliver within five seconds.
  • So the key load parameter is the distribution of followers per user (perhaps weighted by how often they tweet): it determines fan-out load.
Most users fan out on write Celebrities no fan-out Timeline cache Celebrity tweets Merge on read home timeline like approach 1 like approach 2
Twitter's hybrid: fan out for most users, fetch and merge celebrity tweets at read time.
  • The final twist: Twitter moved to a hybrid. Users with huge follower counts (celebrities) are excepted from fan-out; their tweets are fetched separately and merged at read time. This gives consistently good performance (revisited in Chapter 12).

Describing Performance

With load described, ask two questions as a load parameter grows:

  • With resources (CPU, memory, network bandwidth) unchanged, how does performance change?
  • How much must resources grow to keep performance unchanged?
  • Batch systems (e.g. Hadoop) care about throughput: records processed per second, or total job time on a dataset of a given size. (Ideally job time = dataset size / throughput; in practice longer, due to skew and waiting for the slowest task.)
  • Online systems care about response time: time between the client sending a request and receiving a response.
  • Response time varies on every request, so treat it as a distribution, not a single number.
  • Outliers may be intrinsically expensive requests, but even identical requests vary: context switch to a background process, lost packet and TCP retransmission, GC pause, page fault reading from disk, mechanical vibration in the rack.
  • The mean (sum of n values divided by n) is a poor "typical" metric: it does not tell you how many users actually saw that delay.
  • Use percentiles. Sort response times fastest to slowest: the median (p50) is the halfway point. Median 200 ms means half of requests return in under 200 ms.
  • The median is per request. A user making several requests (a session, or a page with several resources) is much more than 50% likely to hit at least one slower than median.
  • Outliers: look at p95, p99, p999. A p95 of 1.5 s means 95 of 100 requests take under 1.5 s and 5 take 1.5 s or more.
median mean p95 p99 requests (bar height = response time) rare slow outliers pull the mean up
Response times as a distribution: a few outliers dominate the high percentiles (after Figure 1-4).
  • High percentiles, tail latencies, directly affect user experience.
  • Amazon specifies internal service response times at p999 (1 in 1,000 requests) because the slowest requests often belong to customers with the most data, i.e. the most purchases, i.e. the most valuable customers.
  • Amazon observed a 100 ms slowdown cuts sales by 1%; others report a 1 s slowdown cuts a customer satisfaction metric by 16%.
  • Optimizing p9999 (1 in 10,000) was judged too expensive for too little benefit: very high percentiles are dominated by random events outside your control, with diminishing returns.
  • Percentiles appear in SLOs and SLAs. Example SLA: "up" means median under 200 ms and p99 under 1 s, and the service must be up at least 99.9% of the time. Customers can demand a refund if it is missed.
  • Queueing delays account for much of high-percentile response time. A server processes only a few things in parallel (e.g. limited by CPU cores), so a few slow requests hold up the rest: head-of-line blocking. Hence measure response times on the client side.
  • In load tests, the load generator must send requests independently of response time. Waiting for each response first keeps queues artificially short and skews results.

Percentiles in Practice

  • Backend services called many times per end-user request make high percentiles critical. Even with parallel calls, the end-user request waits for the slowest call.
  • The more backend calls per request, the likelier one is slow, so a higher share of end-user requests end up slow: tail latency amplification.
End-user request waits for slowest call Backend 1 Backend 2 Backend 3 slow call time
Parallel backend calls: one slow call makes the whole end-user request slow (after Figure 1-5).
  • Monitoring dashboards need percentiles computed continuously, e.g. a rolling 10-minute window, recomputing median and percentiles every minute.
  • Naive: keep all response times in the window and sort every minute. Cheaper approximations: forward decay, t-digest, HdrHistogram.
  • Averaging percentiles (to lower time resolution or combine machines) is mathematically meaningless. Aggregate by adding the histograms.

Approaches for Coping with Load

  • An architecture for one load level is unlikely to cope with 10x. Fast-growing services should expect to rethink architecture at each order of magnitude, or more often.
  • Scaling up (vertical: a more powerful machine) vs scaling out (horizontal: spread load over many smaller machines, a shared-nothing architecture).
  • Single-machine systems are simpler, but high-end machines get very expensive, so very intensive workloads must scale out. Good architectures mix both pragmatically: several fairly powerful machines can be simpler and cheaper than many small VMs.
Scale up (vertical) small bigger machine simpler, but costly at the top Scale out (horizontal) node node node node node node shared-nothing, more complex
Scaling up vs scaling out; real systems usually mix the two.
  • Elastic systems add resources automatically on detecting load; others are scaled manually by a human. Elastic helps with highly unpredictable load; manual is simpler with fewer operational surprises.
  • Distributing stateless services is fairly easy; making stateful data systems distributed adds much complexity. So common wisdom was: keep the database on one node (scale up) until cost or high-availability needs force distribution.
  • As distributed tools and abstractions improve, distributed data systems may become the default even for small workloads.
  • No generic, one-size-fits-all scalable architecture ("magic scaling sauce"). The problem may be read volume, write volume, data volume, data complexity, response-time needs, access patterns, or usually a mix.
  • Example: 100,000 req/sec of 1 kB each looks very different from 3 req/min of 2 GB each, despite the same data throughput.
  • A scalable architecture is built on assumptions about which operations are common and which rare (the load parameters). Wrong assumptions make scaling effort wasted at best, counterproductive at worst.
  • In an early-stage startup or unproven product, fast iteration on features usually matters more than scaling to hypothetical future load.
  • Even so, scalable architectures are built from general-purpose building blocks in familiar patterns.

Maintainability

  • Most of software's cost is ongoing maintenance, not initial development: fixing bugs, keeping it running, investigating failures, porting to new platforms, new use cases, repaying technical debt, adding features.
  • People dislike maintaining legacy systems (others' mistakes, outdated platforms, systems forced into jobs they weren't meant for). Each is unpleasant in its own way, so general advice is hard.
  • Instead, design to minimize maintenance pain and avoid creating legacy software ourselves, using three principles.
Operability easy for ops to keep it running Simplicity easy for new engineers to understand Evolvability easy to change for unanticipated uses a.k.a. extensibility
The three design principles for maintainable software.
  • Operability: make it easy for operations teams to keep the system running smoothly.
  • Simplicity: make it easy for new engineers to understand the system by removing complexity (not the same as a simple UI).
  • Evolvability: make future changes easy, adapting to unanticipated use cases. Also called extensibility, modifiability or plasticity.

Operability: Making Life Easy for Operations

  • Good operations can often work around bad or incomplete software, but good software cannot run reliably with bad operations. Automation helps, but humans must set it up and verify it.

A good operations team typically handles:

  • Monitoring health, restoring service quickly, and tracking down causes of failures or slowdowns.
  • Keeping software and platforms patched, and keeping the system secure as configuration changes.
  • Knowing how systems affect each other; anticipating problems (e.g. capacity planning).
  • Deployment and configuration-management practices; complex migrations between platforms.
  • Predictable processes, a stable production environment, and preserved knowledge as people come and go.

Good operability makes routine tasks easy so ops can focus on high-value work. Data systems help by:

  • Giving visibility into runtime behavior and internals with good monitoring.
  • Supporting automation and integration with standard tools.
  • Avoiding dependence on individual machines (take one down for maintenance while the system keeps running).
  • Good documentation and an easy operational model ("If I do X, Y will happen").
  • Good defaults that administrators can override.
  • Self-healing where appropriate, with manual control over system state when needed.
  • Predictable behavior, minimizing surprises.

Simplicity: Managing Complexity

  • Small projects can be simple; large ones often become complex, slowing everyone and raising maintenance cost. A project mired in complexity is a big ball of mud.
  • Symptoms: state-space explosion, tight coupling, tangled dependencies, inconsistent naming, performance hacks, special-casing around problems elsewhere.
  • Complexity overruns budgets and schedules, and raises the risk of bugs on change: hidden assumptions, unintended consequences and unexpected interactions get overlooked.
  • Simpler does not mean less functionality. It can mean removing accidental complexity: per Moseley and Marks, complexity not inherent in the problem (as users see it) but arising only from the implementation.
  • Abstraction is one of the best tools against accidental complexity: it hides implementation detail behind a clean façade and can be reused widely, so improvements to it benefit every user.
  • Examples: high-level languages hide machine code, CPU registers and syscalls. SQL hides on-disk and in-memory data structures, concurrent clients, and inconsistencies after crashes.
  • Good abstractions are hard to find, especially in distributed systems: many good algorithms exist, but how to package them into abstractions that keep complexity manageable is much less clear.

Evolvability: Making Change Easy

  • Requirements are in constant flux: new facts, new use cases, shifting business priorities, user feature requests, new platforms, legal or regulatory changes, growth forcing architectural change.
  • Agile processes provide a framework for adapting to change, with technical tools such as test-driven development (TDD) and refactoring.
  • Those usually work at a small, local scale (a few source files). The book looks for agility at the level of a whole data system of several applications or services, e.g. how would you "refactor" Twitter's timeline from approach 1 to approach 2?
  • Ease of change is closely tied to simplicity and good abstractions. The book calls data-system-level agility evolvability.

Summary

  • Applications have functional requirements (what they do: store, retrieve, search, process data) and nonfunctional ones (security, reliability, compliance, scalability, compatibility, maintainability). This chapter covered reliability, scalability and maintainability.
  • Reliability: working correctly even when faults occur. Faults come from hardware (random, uncorrelated), software (systematic, hard to handle) and humans (inevitable mistakes). Fault-tolerance techniques can hide certain faults from end users.
  • Scalability: strategies to keep performance good as load grows. It requires describing load and performance quantitatively: Twitter home timelines for load, response-time percentiles for performance. A scalable system can add capacity to stay reliable under high load.
  • Maintainability: making life better for the engineering and operations teams. Good abstractions reduce complexity and ease change; good operability means visibility into health and effective ways to manage it.
  • No easy fix exists for any of the three, but recurring patterns and techniques help; later chapters examine them, and Part III covers multi-component systems like Figure 1-1.
Chapter 2

Data Models and Query Languages

How general-purpose data models (relational, document, graph) and their query languages shape what software can do, and how to pick the one that fits your application.

Key takeaways

  • The document model fits self-contained trees of one-to-many data: better locality, schema flexibility, less impedance mismatch.
  • The relational model wins on joins, many-to-one and many-to-many relationships; data tends to get more interconnected as features are added.
  • "Schemaless" really means schema-on-read (implicit, interpreted by readers) versus schema-on-write (explicit, enforced by the database).
  • Declarative query languages (SQL, CSS, Cypher, SPARQL, Datalog) let the optimizer change execution and parallelize without changing queries; imperative APIs cannot.
  • Graph models suit data where anything may relate to anything; variable-length traversals are concise in Cypher/SPARQL and clumsy in SQL.
  • Relational and document databases are converging; a hybrid is a good direction.

Introduction: layered data models

  • Applications stack data models; each layer is represented in terms of the one below and hides its complexity.
  • Every model embeds assumptions: some operations are fast and natural, others awkward or unsupported.
  • This chapter covers layer 2 (storage and query models). Chapter 3 covers how they are implemented (layer 3).
1. App objects, data structures, APIs 2. JSON / tables / graph (this chapter) 3. Bytes on disk, memory, network (Ch. 3) 4. Currents, light, magnetic fields built on
Each layer hides the one below behind a clean data model.

Relational Model Versus Document Model

  • Relational model (Codd, 1970): data in relations (tables), each an unordered collection of tuples (rows).
  • Dominant since the mid-1980s (25-30 years). Roots: business transaction and batch processing on mainframes. Goal: hide internal representation behind a cleaner interface.
  • Competitors (network, hierarchical, object, XML databases) came and went; relational generalized well to most of the web.

The Birth of NoSQL

  • "NoSQL" (2010s) names no particular technology; it began as a 2009 meetup hashtag, later reinterpreted as Not Only SQL.
  • Driving forces:
    • Greater scalability: very large datasets or very high write throughput.
    • Preference for free and open source software.
    • Specialized query operations poorly supported by the relational model.
    • Frustration with restrictive relational schemas; desire for a more dynamic, expressive model.
  • Likely future: relational alongside many nonrelational stores, called polyglot persistence.

The Object-Relational Mismatch

  • OO application code vs tables/rows/columns needs an awkward translation layer: the impedance mismatch.
  • ORMs (ActiveRecord, Hibernate) cut boilerplate but cannot hide the differences.
  • Example: a LinkedIn résumé. Names appear once per user (columns); positions, education, contact info are one-to-many. Three representations:
    1. Normalized: separate tables with a foreign key to users (traditional SQL, pre-SQL:1999).
    2. Structured datatypes / XML / JSON columns that can be queried and indexed (Oracle, DB2, SQL Server, PostgreSQL; JSON in DB2, MySQL, PostgreSQL).
    3. Encode as JSON/XML in a text column, interpreted by the application; usually cannot be queried by the database.
  • A résumé is a self-contained document, so JSON fits (MongoDB, RethinkDB, CouchDB, Espresso). Locality: one query instead of many queries or a multi-way join.
  • One-to-many relationships form a tree; JSON makes it explicit.

Example 2-1 holds the profile as one JSON document: scalar fields (user_id 251, names, region_id, industry_id) plus nested positions and education arrays and a contact_info object.

Relational (shredded) users positions education contact_info FK user_id; many queries or joins Document (tree) user 251 positions education contact Co-chair Harvard one place, one query
Figures 2-1 and 2-2 simplified: one-to-many data shredded into tables vs one JSON tree.

Many-to-One and Many-to-Many Relationships

  • Why store region_id/industry_id as IDs, not strings like "Greater Seattle Area"? Standardized lists give consistent spelling, no ambiguity, easy updates, localization, and better search (the list knows Seattle is in Washington).
  • ID vs text is a question of duplication. An ID has no human meaning, so it never needs to change. Duplicated human-meaningful text must be updated everywhere: write overhead and inconsistency risk.
  • Removing duplication is the key idea of normalization. Rule of thumb: duplicating values that could live in one place means the schema is not normalized.
  • Normalizing needs many-to-one relationships (many people in one region), which fit documents poorly: joins are easy in relational, often weak in document stores (RethinkDB yes, MongoDB no, CouchDB only predeclared views, at time of writing).
  • Without database joins, the application emulates them with multiple queries, shifting work into app code.
  • Data becomes more interconnected as features are added:
    • Organizations and schools as entities: each with its own page and logo, referenced from résumés.
    • Recommendations: one user recommends another; the recommendation must show the author's current photo, so it references the author's profile.
  • These need many-to-many relationships: each résumé can still be one document, but references to organizations, schools and users require joins.
Résumé A (document) position education recommendation Résumé B (document) position education Organization School User B references need joins
Figure 2-4 simplified: documents inside dotted boxes, shared entities referenced many-to-many.

Are Document Databases Repeating History?

  • The many-to-many debate predates NoSQL. IBM's IMS (built for Apollo stock-keeping, released 1968, still maintained) used the hierarchical model: a tree of nested records, much like JSON.
  • IMS handled one-to-many well, made many-to-many hard, had no joins. Developers chose between duplicating (denormalizing) data and manually resolving references: the same problems document databases face today.
  • Two proposed fixes: the relational model (won) and the network model (faded). Their "great debate" ran through the 1970s.

The network model

  • Standardized by CODASYL (the CODASYL model); generalizes the hierarchy: a record can have multiple parents, enabling many-to-one and many-to-many.
  • Links were pointer-like (stored on disk), not foreign keys. A record was reached only by following an access path from a root along chains of links.
  • Queries moved a cursor through record lists; with many paths to a record, programmers tracked them in their heads.
  • Efficient on 1970s hardware (slow tape seeks), but code was complicated and inflexible: changing access paths meant rewriting handwritten query code.
  • In CODASYL the join was effectively done at insert time; relational joins on foreign keys happen at query time.

The relational model

  • All data laid out in the open: a table is just a collection of rows. No nested structures or access paths. Read any rows matching any condition, look up by key, insert without worrying about relationships.
  • The query optimizer picks execution order and indexes, which is effectively the access path, chosen automatically.
  • New query patterns: declare a new index, and queries use it without being changed. Adding features is easier.
  • Key insight: optimizers are hard to build, but you build one once and every application benefits. Hand-coding paths is easier for one query; the general solution wins long term.
Hierarchical one parent each Network (CODASYL) many parents; follow path Relational Query optimizer path chosen automatically
Who picks the access path: the programmer (hierarchical, network) or the optimizer (relational).

Comparison to document databases

  • Documents revert to the hierarchical model in one way: nested one-to-many records live inside the parent.
  • For many-to-one and many-to-many, relational and document are not fundamentally different: a unique ID (foreign key / document reference) resolved at read time by a join or follow-up queries.

Relational Versus Document Databases Today

Comparing only the data model (fault tolerance is Chapter 5, concurrency Chapter 7):

DocumentRelational
Main argumentSchema flexibility, locality, closer to app data structuresJoins, many-to-one and many-to-many support
Best fitTree of one-to-many, whole tree loaded at onceInterconnected data
WeaknessCan't refer directly to nested items; weak joinsShredding a document into tables: cumbersome schema, complex code
SchemaSchema-on-readSchema-on-write

Which data model leads to simpler application code?

  • Document-like data (tree, loaded whole) → document model. Shredding it relationally gives cumbersome schemas.
  • Nested items need paths like "the second position of user 251"; fine if nesting is shallow. Weak joins may not matter (e.g. event analytics).
  • With many-to-many: denormalizing forces the app to keep copies consistent; emulating joins with multiple requests moves complexity into the app and is usually slower than an in-database join.
  • It depends on the relationships: for highly interconnected data, document is awkward, relational acceptable, graph most natural.

Schema flexibility in the document model

  • Most document databases (and JSON in RDBMSes) enforce no schema; XML support often has optional validation. Readers get no guarantee about fields.
  • "Schemaless" is misleading: readers assume an implicit schema. Better terms: schema-on-read vs schema-on-write.
  • Analogy: dynamic (runtime) vs static (compile-time) type checking. No right or wrong answer.
  • Format changes show the difference. Example: split full name into first_name/last_name.
  • Schema-on-read: write new documents with the new fields; app code fills first_name from name when reading old ones.
  • Schema-on-write: a migration, ALTER TABLE users ADD COLUMN first_name text; then an UPDATE that splits name.
  • Schema changes' slow reputation is not entirely deserved: most RDBMSes run ALTER TABLE in a few milliseconds. Exception: MySQL copies the whole table (minutes to hours of downtime on large tables), though tools work around it.
  • UPDATE on a large table is slow everywhere (every row rewritten). Alternative: leave first_name NULL and fill it in at read time, as a document database would.
  • Schema-on-read helps when data is heterogeneous: many object types (impractical as one table each), or structure set by external systems that may change at any time.
  • When all records share a structure, schemas usefully document and enforce it (more in Chapter 4).
Schema-on-write Writer DB checks Storage Reader explicit schema, like static typing Schema-on-read Writer Any keys App interprets Reader implicit schema, like dynamic typing
Where the structure is enforced: at write time by the database, or at read time by the code.

Data locality for queries

  • A document is stored as one continuous string (JSON, XML, or binary like MongoDB's BSON). Fetching it whole (e.g. to render a page) is faster than multiple index lookups and disk seeks across tables.
  • Only helps if you need large parts at once: the whole document is loaded even for a small part; updates usually rewrite the whole document (only size-preserving changes can be done in place).
  • Advice: keep documents small; avoid writes that grow them. These limits shrink where documents are useful.
  • Locality is not document-only: Spanner interleaves child rows in a parent table; Oracle has multi-table index cluster tables; Bigtable column families (Cassandra, HBase) do similar.

Convergence of document and relational databases

  • Most RDBMSes (not MySQL) have supported XML since the mid-2000s, with local modification, indexing and querying inside documents.
  • JSON support: PostgreSQL 9.3+, MySQL 5.7+, IBM DB2 10.5+.
  • Document side: RethinkDB supports relational-like joins; some MongoDB drivers resolve references (client-side join, slower: extra round-trips, less optimized).
  • Codd's original model allowed nonsimple domains (a value could be a nested relation).
  • The models complement each other; a hybrid of relational and document is a good route for future databases.

Query Languages for Data

  • SQL is declarative; IMS and CODASYL used imperative code (typically COBOL iterating one record at a time).
  • Imperative: tell the computer which operations to perform in which order (loop over animals, push sharks into a list).
  • Declarative: specify the pattern of the result (conditions, sorting, grouping, aggregation), not how. The optimizer chooses indexes, join methods, and order.
sharks = σ family = "Sharks" (animals)          -- relational algebra
SELECT * FROM animals WHERE family = 'Sharks';  -- SQL
  • Benefits of declarative:
    • Concise; hides engine details, so performance can improve without query changes (SQL promises no order, so records may move to reclaim disk space).
    • Easier to parallelize: CPUs gain cores, not clock speed; declarative specifies only the result, not an ordered algorithm.

Declarative Queries on the Web

  • Example: an ocean-animals site highlights the selected page title (<li class="selected"><p>Sharks</p>) with a blue background.
  • CSS: li.selected > p { background-color: blue; }. The selector declares the pattern: <p> whose direct parent is an <li> with class selected.
  • XSL/XPath equivalent: li[@class='selected']/p. Both are declarative.
  • Imperative JavaScript with the DOM API needs nested loops over elements. Longer, harder to read, and:
    • If selected moves, the blue stays until page reload; CSS removes it automatically.
    • Using a faster new API needs a rewrite; browsers can speed up CSS/XPath without breaking compatibility.

MapReduce Querying

  • MapReduce: model for bulk processing across many machines, popularized by Google. MongoDB and CouchDB support a limited form for read-only queries over many documents (Chapter 10 covers it in general).
  • Between declarative and imperative: query logic lives in code snippets the framework calls repeatedly. Based on functional map (collect) and reduce (fold/inject).
  • Example: a marine biologist counts sharks sighted per month. In PostgreSQL: filter family = 'Sharks', GROUP BY date_trunc('month', observation_timestamp), sum(num_animals).
db.observations.mapReduce(
  function map() { emit(year + "-" + month, this.numAnimals); },
  function reduce(key, values) { return Array.sum(values); },
  { query: { family: "Sharks" }, out: "monthlySharkReport" });
  • The query filter is declarative (a MongoDB extension). map runs once per matching document and emits (month key, count). Pairs are grouped by key; reduce runs once per key; output goes to monthlySharkReport.
  • Two December 1995 shark observations (3 and 4 animals) → emit("1995-12", 3), emit("1995-12", 4) → reduce("1995-12", [3, 4]) = 7.
  • map and reduce must be pure functions (only their input, no extra queries, no side effects), so the database can run them anywhere, in any order, and rerun on failure.
  • MapReduce is low level. SQL can run as a MapReduce pipeline or without it; nothing ties SQL to one machine.
  • Usability problem: two carefully coordinated functions are harder than one query, and declarative languages give the optimizer more room. So MongoDB 2.2 added the declarative aggregation pipeline.
  • The pipeline chains a $match stage (family Sharks) and a $group stage (by year and month, $sum of animals). Expressiveness like a subset of SQL, in JSON syntax. Moral: a NoSQL system may accidentally reinvent SQL in disguise.
documents 25 Dec 1995 Sharks, 3 12 Dec 1995 Sharks, 4 map ("1995-12", 3) ("1995-12", 4) group by key 1995-12: [3, 4] reduce sum = 7 pure functions: any order, anywhere, rerun on failure
The shark-count example: map emits per document, reduce runs once per key.

Graph-Like Data Models

  • Mostly one-to-many (trees) or no relationships → document model. Very common, complex many-to-many → model as a graph.
  • A graph has vertices (nodes, entities) and edges (relationships, arcs). Examples: social graphs (people), the web graph (pages and links), road or rail networks (junctions and lines).
  • Known algorithms: shortest path for car navigation; PageRank for web page popularity.
  • Graphs need not be homogeneous: Facebook keeps one graph with many vertex types (people, locations, events, checkins, comments) and edge types.
  • Running example (Figure 2-5): Lucy from Idaho and Alain from Beaune, France, married and living in London.
  • Models covered: property graph (Neo4j, Titan, InfiniteGraph) and triple-store (Datomic, AllegroGraph). Declarative languages: Cypher, SPARQL, Datalog. Imperative alternatives exist: Gremlin, and Pregel for processing (Chapter 10).
North America United States Idaho (state) within within Europe France Beaune within within* London within* Lucy Alain married born_in born_in lives_in
Figure 2-5 simplified (intermediate regions collapsed into within* chains). Lucy's birthplace is a state; her residence is a city.

Property Graphs

  • Vertex: unique ID, outgoing edges, incoming edges, properties (key-value pairs).
  • Edge: unique ID, tail vertex (start), head vertex (end), a label for the relationship kind, properties.
  • Think of it as two relational tables, vertices and edges, with properties in a PostgreSQL json column and indexes on tail_vertex and head_vertex.
  • Important aspects:
    1. Any vertex can connect to any other; no schema restricts associations.
    2. Given a vertex, find incoming and outgoing edges efficiently, so traverse forward and backward (hence both indexes).
    3. Different labels store many kinds of information in one graph with a clean model.
  • Easy here, hard relationally: different regional structures per country (France: départements and régions; US: counties and states), a country within a country, varying granularity (residence a city, birthplace a state).
  • Graphs are good for evolvability: e.g. add allergen vertices linked to people and foods, then query what is safe to eat.
vertices vertex_id (PK) properties (json) edges edge_id (PK) tail_vertex (indexed) head_vertex (indexed) label properties (json) outgoing: by tail incoming: by head
Example 2-2 as tables: both endpoint indexes allow traversal in either direction.

The Cypher Query Language

  • Cypher: declarative query language for property graphs, created for Neo4j (named after a Matrix character, unrelated to cryptography).
  • Insert: vertices get symbolic names; edges use arrows, e.g. (Idaho) -[:WITHIN]-> (USA) (Idaho is tail, USA is head).
  • Query: people who emigrated from the US to Europe, i.e. a BORN_IN edge to somewhere within the US and a LIVES_IN edge to somewhere within Europe.
MATCH
  (person) -[:BORN_IN]->  () -[:WITHIN*0..]-> (us:Location {name:'United States'}),
  (person) -[:LIVES_IN]-> () -[:WITHIN*0..]-> (eu:Location {name:'Europe'})
RETURN person.name
  • Execution options: scan all people and check birthplace/residence; or (with an index on name) start from the US and Europe vertices, follow incoming WITHIN edges to all contained locations, then incoming BORN_IN/LIVES_IN edges to people.

Graph Queries in SQL

  • Possible, but difficult. Relational queries usually know their joins in advance; graph queries may traverse a variable number of edges.
  • LIVES_IN may point at a street, city, district, region, state; each may be WITHIN another. Cypher's :WITHIN*0.. means "follow WITHIN zero or more times", like * in a regex.
  • Since SQL:1999, recursive common table expressions (WITH RECURSIVE; PostgreSQL, DB2, Oracle, SQL Server) express this: build sets in_usa/in_europe by repeatedly following incoming within edges, find people via born_in/lives_in, then intersect.
  • It takes 29 lines in SQL vs 4 in Cypher: different models suit different use cases.

Triple-Stores and SPARQL

  • Mostly equivalent to property graphs, in different words.
  • All data is a triple: (subject, predicate, object), e.g. (Jim, likes, bananas).
  • The subject is a vertex. The object is either:
    1. A primitive value: predicate + object = a property key and value, e.g. (lucy, age, 33) ≈ {"age":33}.
    2. Another vertex: predicate = edge label, e.g. (lucy, marriedTo, alain).
  • Written in Turtle (subset of Notation3). Vertices are _:someName, meaningful only within the file. Semicolons say several things about one subject.
(lucy, age, 33) lucy {"age": 33} object = value (lucy, marriedTo, alain) lucy alain marriedTo object = vertex subject = tail object = head
A triple's object is either a property value or another vertex (an edge).

The semantic web

  • Triple-stores are independent of the semantic web (Datomic is a triple-store unrelated to it; it actually uses 5-tuples, with two versioning fields).
  • Idea: sites publish machine-readable data too. RDF (Resource Description Framework) lets sites publish in a consistent format, combinable into a "database of everything".
  • Overhyped in the early 2000s and not realized in practice. Still, triples can be a good internal data model.

The RDF data model

  • Turtle is a human-readable RDF format; RDF/XML does the same far more verbosely. Tools like Apache Jena convert between formats.
  • Designed for internet-wide exchange: subjects, predicates and objects are often URIs (e.g. <http://my-company.com/namespace#within>), so your within won't clash with another party's.
  • The URI need not resolve; it is just a namespace, declared once as a prefix.

The SPARQL query language

  • SPARQL (SPARQL Protocol and RDF Query Language, "sparkle"): query language for RDF triple-stores. It predates Cypher, whose pattern matching borrows from it.
  • The emigration query is even more concise than in Cypher (core patterns):
?person :bornIn  / :within* / :name "United States".
?person :livesIn / :within* / :name "Europe".
  • Variables start with ?. ?person :bornIn / :within* ?location matches Cypher's (person) -[:BORN_IN]-> () -[:WITHIN*0..]-> (location).
  • RDF uses predicates for both properties and edges, so the same syntax matches properties: ?usa :name "United States".

Graph Databases Compared to the Network Model

Are graph databases CODASYL in disguise? No:

CODASYLGraph database
SchemaSpecifies which record type nests in whichAny vertex can link to any other
AccessOnly by traversing an access pathDirectly by unique ID, or via an index
OrderingChildren are ordered sets; inserts must handle positionVertices and edges unordered; sort at query time
QueriesImperative, hard to write, broken by schema changesImperative optional; declarative Cypher/SPARQL available

The Foundation: Datalog

  • Datalog: much older (studied in the 1980s), less known, but the foundation later query languages build on. Used by Datomic and by Cascalog (for large datasets in Hadoop). It is a subset of Prolog.
  • Data model like triples, generalized: predicate(subject, object), e.g. within(usa, namerica)., born_in(lucy, idaho).
  • Queries are built from rules that define new, derived predicates (not stored), here within_recursive and migrated. Rules can call other rules or themselves.
  • Rule 1: a location is within_recursive of its own name. Rule 2: if within(Location, Via) and Via is within Name, so is Location. Rule 3 (migrated): a person's birth and living locations are recursively within BornIn and LivingIn.
  • Query ?- migrated(Who, 'United States', 'Europe'). returns Who = 'Lucy'.
  • Uppercase words are variables; predicates match like in Cypher/SPARQL.
  • A rule applies when all right-hand predicates of :- match; the left side is then as if added to the database.
  • Derivation: rule 1 on name(namerica, ...) → within_recursive(namerica, 'North America'); rule 2 with within(usa, namerica) → within_recursive(usa, ...); rule 2 with within(idaho, usa) → within_recursive(idaho, 'North America').
  • Different thinking: less convenient for one-off queries, but rules combine and are reused, so it copes better with complex data.
stored facts derived facts name(namerica, 'N. America') within(usa, namerica) within(idaho, usa) within_recursive(namerica, 'N. America') within_recursive(usa, 'N. America') within_recursive(idaho, 'N. America') rule 1 rule 2 rule 2 each derived fact feeds the next rule application
Figure 2-6 simplified: repeated rule application proves Idaho is in North America.

Summary

  • History: data began as one big tree (hierarchical), which handled many-to-many poorly; the relational model solved that.
  • Some applications don't fit relational either. NoSQL diverged two ways:
    1. Document databases: self-contained documents, rare relationships between them.
    2. Graph databases: anything potentially related to everything.
  • Document, relational and graph are all widely used, each good in its domain. One can emulate another (graph in relational), but often awkwardly: no one-size-fits-all system.
  • Document and graph databases usually don't enforce a schema, easing change; but the app still assumes structure. The question is explicit (on write) or implicit (on read).
  • Each model has its query language or framework: SQL, MapReduce, MongoDB's aggregation pipeline, Cypher, SPARQL, Datalog; plus CSS and XSL/XPath as parallels.
  • Not covered: genome sequence-similarity search (GenBank), LHC-scale physics data (hundreds of petabytes, custom solutions), full-text search (Chapter 3, Part III).
Chapter 3

Storage and Retrieval

How a database stores the data it is given and finds it again, seen from the engine's side. It also explains why engines tuned for transactions differ from engines tuned for analytics.

Key takeaways

  • An index is derived data that speeds reads; every index slows writes.
  • Log-structured engines only append and never modify written files, which turns random writes into sequential ones.
  • LSM-tree = in-memory memtable + sorted SSTables compacted in the background: high write throughput and range queries.
  • B-trees overwrite fixed-size pages in place, use a WAL for crash safety, and are the default index in relational databases.
  • Rule of thumb: LSM faster for writes, B-tree faster for reads. Benchmark your own workload.
  • OLTP is seek-bound key lookups; OLAP is bandwidth-bound scans, run in a separate data warehouse.
  • Column storage reads only the needed columns, compresses well and enables vectorized processing.
  • Materialized views / data cubes precompute aggregates: fast, but less flexible than raw data.

Data Structures That Power Your Database

The simplest key-value store is two Bash functions over one text file:

db_set () { echo "$1,$2" >> database; }
db_get () { grep "^$1," database | sed -e "s/^$1,//" | tail -n 1; }
  • Writes append, so updates leave old versions behind and reads take the last match. Appending is very fast.
  • Many databases use a log internally: an append-only sequence of records, not necessarily human-readable.
  • Reads scan the whole file: O(n). The fix is an index, extra metadata that points to where data lives.
  • Indexes are derived from primary data. Adding or dropping one changes performance, not contents.

Hash Indexes

  • Keep an in-memory hash map from each key to the byte offset of its latest value in the data file. Update it on every append; reads do one seek.
  • This is essentially Bitcask (Riak's default). It is fast, but all keys must fit in RAM; values can be larger than memory.
  • Good fit: few keys, many updates per key (e.g. play counts per cat-video URL).
In-memory hash map key → offset 123456 → 0 42 → 128 Append-only log on disk 0 123456,{London…} 64 42,{SF: Golden Gate} (stale) 128 42,{SF: Exploratorium} Every write appends and updates the map; reads take one seek.
Figure 3-1 (simplified): a CSV-like log indexed by an in-memory hash map.
  • To bound disk use, split the log into segments. Closed segments get compaction, which drops duplicate keys and keeps the latest value.
  • Compaction and merging of several segments run in a background thread and write a new file (segments are immutable). Reads switch to the new file, then the old files are deleted.
  • Each segment has its own hash map; look up newest first. Merging keeps segment count low.
Segment 1 (older) a: 1 b: 1 a: 2 a: 3 b: 2 Segment 2 (newer) a: 4 c: 1 b: 3 a: 5 compact + merge (background thread) Merged segment a: 5 b: 3 c: 1 Old segments are deleted once reads switch to the merged file.
Figures 3-2 and 3-3 (simplified): compaction and segment merging keep only the most recent value per key.

Real-implementation details:

  • File format: binary with length-prefixed strings, not CSV.
  • Deletes: append a tombstone; merging discards earlier values for the key.
  • Crash recovery: rebuilding maps by rereading segments is slow, so Bitcask snapshots each map to disk.
  • Partial writes: checksums detect and skip corrupted records.
  • Concurrency: one writer thread; immutable segments allow many concurrent readers.

Why append-only beats overwriting in place:

  • Sequential writes are much faster than random ones on spinning disks, and somewhat better on SSDs.
  • Concurrency and crash recovery are simpler: there are no half-old, half-new values.
  • Merging prevents fragmentation.

Limits: the hash table must fit in memory (on-disk hash maps need random I/O, are costly to grow and have fiddly collisions), and range queries such as kitty00000–kitty99999 need one lookup per key.

SSTables and LSM-Trees

Require each segment to be sorted by key, with each key once per merged segment. This is a Sorted String Table (SSTable). Advantages:

  1. Merging is simple, even beyond memory size. It is mergesort-style: copy the lowest key across inputs. On duplicates, the newest segment wins.
  2. Sparse index: to find handiwork, jump to the known offset of handbag and scan toward handsome. One key per few KB is enough.
  3. Compression: records between index entries form a compressed block, saving disk and I/O bandwidth.
Segment 1 (oldest) apple: 1 cherry: 4 dog: 2 Segment 2 apple: 7 bird: 3 Segment 3 (newest) bird: 9 dog: 5 Merged output apple: 7 bird: 9 cherry: 4 dog: 5 Read all inputs side by side; copy the lowest key; for duplicate keys, the newest segment wins.
Figure 3-4 (simplified): merging SSTable segments like mergesort.
Sparse in-memory index handbag → block 1 handsome → block 2 SSTable file handbag handful handiwork handlebar handsome hangout … compressed block 1 compressed block 2 Find handiwork: jump to handbag, then scan forward. One index key every few kilobytes is enough.
Figure 3-5 (simplified): an SSTable with a sparse in-memory index over compressed blocks.

Constructing and maintaining SSTables:

  • Writes go to an in-memory balanced tree (red-black, AVL), the memtable.
  • When it passes a threshold (typically a few MB), flush it as the newest SSTable; a fresh memtable takes new writes.
  • Reads check the memtable, then segments from newest to oldest.
  • Background merging and compaction discard overwritten and deleted values.
  • For crash safety, every write is also appended to an unsorted log, which is discarded once its memtable is flushed.
Write Memtable sorted tree in memory Log on disk unsorted, for recovery flush SSTable 3 (newest) SSTable 2 SSTable 1 (oldest) background merge + compaction Read: memtable → SSTable 3 → 2 → 1 (Bloom filter skips absent keys)
The LSM storage engine: memtable, recovery log, and a cascade of SSTables merged in the background.

Making an LSM-tree out of SSTables:

  • Used by LevelDB and RocksDB (embeddable; LevelDB can replace Bitcask in Riak). Cassandra and HBase use similar engines, inspired by Google's Bigtable, which coined "SSTable" and "memtable".
  • First described by O'Neil et al. as the Log-Structured Merge-Tree. Engines built on merging sorted files are LSM storage engines.
  • Lucene (Elasticsearch, Solr) stores its term → postings list (document IDs) mapping in SSTable-like sorted files merged in the background.

Performance optimizations:

  • Missing keys force a check of every segment. Bloom filters report "definitely absent" cheaply.
  • Size-tiered compaction merges newer, smaller SSTables into older, larger ones (HBase). Leveled compaction splits the key range into small SSTables in levels, which is more incremental and uses less disk (LevelDB, RocksDB). Cassandra supports both.
  • The result works well beyond memory size, supports range queries, and gives very high write throughput.

B-Trees

  • The most widely used index (introduced 1970), standard in almost all relational and many nonrelational databases.
  • Keys are sorted like SSTables, but the data is split into fixed-size pages (traditionally 4 KB), read and written one at a time to match disk blocks.
  • Pages reference each other by address, forming a tree. From the root, follow the child whose key range contains the target (251 lies between 200 and 300) down to a leaf page holding values or references to them.
  • Branching factor = child references per page: six in the figure, typically several hundred.
look up 251 root 100 200 300 400 500 6 refs interior 220 240 260 280 range 200–300 leaf 241 246 251 255 258 keys + values or refs
Figure 3-6 (simplified): looking up a key by following page references from the root to a leaf.
  • Update: rewrite the leaf page; references stay valid.
  • Insert: add the key to the covering page. If it is full, split it into two half-full pages and add the boundary to the parent.
  • The tree stays balanced at depth O(log n). Most databases need 3–4 levels; four levels of 4 KB pages at branching factor 500 hold up to 256 TB.
Before: insert 334 parent: 333 | 345 333 335 337 340 342 344 page full split After parent: 333 | 337 | 345 333 334 335 337 340 342 344 Three pages are rewritten; a crash midway can corrupt the index, hence the WAL.
Figure 3-7 (simplified): growing a B-tree by splitting a page.

Making B-trees reliable:

  • Writes overwrite pages in place, unlike LSM-trees, which never modify files. SSDs must erase and rewrite large blocks to do this.
  • A split rewrites several pages, so a crash midway can leave a corrupt index, e.g. an orphan page.
  • The fix is a write-ahead log (WAL, redo log): each change is appended there before it touches the tree, and replayed after a crash.
  • Concurrent threads need latches (lightweight locks). LSM-trees are simpler here: they merge in the background and swap segments atomically.

B-tree optimizations:

  • Copy-on-write (LMDB): write modified pages elsewhere and create new parent versions instead of using a WAL. This also aids concurrency control.
  • Abbreviated keys in interior pages raise the branching factor and reduce levels (B+ tree).
  • Try to lay leaves out sequentially on disk for range scans. This is hard as the tree grows; LSM merges keep it more easily.
  • Sibling pointers between leaves allow in-order scans without returning to the parent.
  • Fractal trees borrow log-structured ideas to cut seeks.

Comparing B-Trees and LSM-Trees

B-trees are more mature. LSM-trees are typically faster for writes; B-trees are thought faster for reads, because LSM reads check several structures. Benchmarks are workload-sensitive, so test your own.

Advantages of LSM-trees:

  • B-trees write everything at least twice (WAL + page) and write whole pages for small changes. Compaction also rewrites data. One write causing many disk writes is write amplification, which wears out SSDs and costs throughput when disk bandwidth is the bottleneck.
  • LSM-trees often sustain higher write throughput: sometimes lower amplification, and sequential SSTable writes instead of several page overwrites (matters most on magnetic disks).
  • LSM-trees compress better. B-trees leave space unused through fragmentation after splits; LSM rewrites remove it, especially with leveled compaction.
  • SSD firmware already makes random writes sequential, but compact data still fits more I/O into the bandwidth.

Downsides of LSM-trees:

  • Compaction can stall requests. The mean impact is small, but high-percentile latency can be high; B-trees are more predictable.
  • Compaction shares write bandwidth with new writes and needs more as data grows. If it falls behind, segments pile up until disk fills and reads slow. Engines usually don't throttle writes, so monitor for this.
  • A B-tree keeps each key in exactly one place, so range locks for transaction isolation attach directly to the tree (Chapter 7).
  • B-trees aren't going away; log-structured indexes are rising in new datastores. Test empirically.
AspectLSM-treeB-tree
Write patternSequential SSTable writesOverwrite pages in place
StrengthWrite throughputReads, predictable latency
Write amplificationRepeated compaction; sometimes lowerWAL + full pages + splits
Disk footprintSmaller: compression, little fragmentationSpace lost to page splits
Read costMemtable + several SSTablesOne root-to-leaf path
RisksCompaction hurts tail latency; can fall behindCrash mid-split (needs WAL); latches
Key copiesPossibly severalExactly one

Other Indexing Structures

  • Key-value indexes act like a primary key index. Secondary indexes (CREATE INDEX) are common and key to efficient joins, e.g. on user_id.
  • Secondary keys aren't unique. Either store a list of row IDs per key, or append a row ID to make keys unique. B-trees and LSM-trees both work.

Storing values within the index:

  • The value is either the row or a reference into a heap file (unordered). Heap files avoid duplicating data across many indexes.
  • A larger value that must move means updating all indexes or leaving a forwarding pointer.
  • Clustered index: the row lives in the index, which saves a hop. InnoDB's primary key is always clustered, and secondary indexes point to the primary key. SQL Server allows one per table.
  • Covering index (included columns): stores some columns so some queries are answered from the index alone.

Multi-column indexes:

  • Concatenated index: fields appended into one key, like a phone book on (lastname, firstname). It is useless for a first name alone.
  • Multi-dimensional indexes handle queries such as restaurants inside a map rectangle, which B-trees and LSM-trees can't do efficiently (one range only):
SELECT * FROM restaurants WHERE latitude  > 51.4946 AND latitude  < 51.5079
                            AND longitude > -0.1162 AND longitude < -0.1004;
  • Options: a space-filling curve into a normal B-tree, or more commonly an R-tree (PostGIS, on PostgreSQL's GiST).
  • Beyond geography: (red, green, blue) for product colours, or (date, temperature) for weather data. HyperDex uses this technique.

Full-text search and fuzzy indexes:

  • Exact-key indexes can't find similar keys (typos). Full-text engines add synonyms, grammatical variants, proximity and other linguistic features.
  • Lucene searches within an edit distance. Its in-memory term index is a finite state automaton (trie-like), not LevelDB's sparse keys, and can be turned into a Levenshtein automaton.
  • Other fuzzy techniques lean toward document classification and machine learning.

Keeping everything in memory:

  • Disks are awkward but durable and cheaper per GB. Cheaper RAM makes in-memory databases feasible for many datasets.
  • Memcached is cache-only. Others get durability from battery-backed RAM, a change log, snapshots or replication; disk is then only an append-only log, and reads come from memory.
  • Examples: VoltDB, MemSQL, Oracle TimesTen (relational); RAMCloud (durable, log-structured); Redis and Couchbase (weak, async durability).
  • The speed-up comes from not encoding in-memory structures for disk, not from avoiding disk reads (the OS caches blocks anyway).
  • They also allow data models that are hard on disk, such as Redis priority queues and sets.
  • Anti-caching evicts least recently used records to disk and reloads them on access. It is like swap but per record, and indexes must still fit in memory.
  • Non-volatile memory may force further redesign (still research).

Transaction Processing or Analytics?

  • A transaction is a group of reads and writes forming a logical unit. It need not be ACID; it just means low-latency reads and writes, as opposed to periodic batch jobs.
  • OLTP: interactive apps look up a few records by key and write user input.
  • OLAP: analysts scan huge numbers of rows, a few columns each, to compute aggregates (e.g. revenue per store in January) for business intelligence.
PropertyOLTPOLAP
Read patternFew records, fetched by keyAggregate over many records
Write patternRandom, low-latency, from user inputBulk import (ETL) or event stream
Used byEnd users, via web appInternal analysts, decision support
Data representsLatest stateHistory of events
SizeGB to TBTB to PB

SQL serves both, but from the late 1980s companies moved analytics to a separate data warehouse.

Data Warehousing

  • Enterprises run dozens of autonomous OLTP systems that must stay fast and available, so DBAs resist expensive ad hoc scans on them.
  • A data warehouse is a separate, read-only copy of all of them that analysts can query freely.
  • ETL (Extract–Transform–Load): extract via dumps or update streams, transform into an analysis-friendly schema, clean, and load.
  • Common in large enterprises and rare in small ones. Its main benefit is being optimized for analytic access, which OLTP indexes are not.
OLTP systems Website DB Inventory DB Routes DB Extract Transform Load Data warehouse analysts query periodic dump or continuous stream
Figure 3-8 (simplified): ETL into a data warehouse.

The divergence between OLTP databases and data warehouses:

  • Warehouses are usually relational (SQL fits analytics and BI tools), but their internals differ, and vendors increasingly pick one workload.
  • SQL Server and SAP HANA offer both, more and more as two engines behind one SQL interface.
  • Commercial: Teradata, Vertica, SAP HANA, ParAccel (Amazon RedShift is hosted ParAccel). SQL-on-Hadoop: Hive, Spark SQL, Impala, Presto, Tajo, Drill, some based on Google's Dremel.

Stars and Snowflakes: Schemas for Analytics

  • Most warehouses use a star schema (dimensional modeling).
  • The central fact table (fact_sales) has one row per event, e.g. one product purchase. Fact tables get huge: tens of PB at Apple, Walmart or eBay.
  • Fact columns are attributes (price, cost) or foreign keys to dimension tables, which give the who, what, where, when, how and why (e.g. dim_product: SKU, brand, category).
  • Dates get a dimension too, to encode holidays.
  • Snowflake schema: dimensions split into subdimensions (brand, category tables). It is more normalized, but stars are simpler for analysts.
  • Tables are wide: fact tables have 100+ columns, sometimes several hundred.
fact_sales date_key product_sk store_sk promotion_sk customer_sk quantity, net_price, discount_price … dim_date weekday, holiday dim_product sku, brand, category dim_store city, size, bakery dim_customer who bought dim_promotion
Figure 3-9 (simplified): a grocery retailer's star schema; each fact row is one product purchase.

Column-Oriented Storage

  • Fact tables can reach trillions of rows. Dimension tables are much smaller, so the focus is on facts.
  • Queries touch 4–5 of 100+ columns. Example 3-1 (fruit vs candy by weekday, 2013) needs only date_key, product_sk and quantity:
SELECT dim_date.weekday, dim_product.category, SUM(fact_sales.quantity)
FROM fact_sales JOIN dim_date ... JOIN dim_product ...
WHERE dim_date.year = 2013 AND dim_product.category IN ('Fresh fruit', 'Candy')
GROUP BY dim_date.weekday, dim_product.category;
  • Row-oriented stores (most OLTP, document DBs) must load, parse and filter whole 100+ column rows, even with indexes.
  • Column-oriented storage keeps each column together (e.g. one file each), so queries read only the columns they use. Parquet applies this to document data (based on Dremel).
  • All column files keep the same row order: row 23 = entry 23 of each file.
Row-oriented: each row stored together 140102 | 69 | 4 | 1 | … 100+ cols 140102 | 69 | 5 | 3 | … 100+ cols 140102 | 74 | 3 | 1 | … 100+ cols 140103 | 31 | 2 | 5 | … 100+ cols Query must load whole rows, then parse and filter them. Column-oriented: one file per column date_key 140102 140102 140102 140103 product_sk 69 69 74 31 store_sk 4 5 3 2 (not read) quantity 1 3 1 5 Example 3-1 reads only the 3 highlighted files.
Figure 3-10 (simplified): storing relational data by column rather than by row.

Column Compression

  • Columns are repetitive, so they compress well. Bitmap encoding suits warehouses, where distinct values are few (~100,000 products vs billions of sales).
  • n distinct values give n bitmaps with one bit per row. When n is large the bitmaps are sparse, so they are run-length encoded.
  • IN (30, 68, 69) → bitwise OR of three bitmaps. product_sk = 31 AND store_sk = 3 → bitwise AND, valid because bit k is the same row in every column.
product_sk column row: 1 2 3 4 5 6 7 8 31 31 68 69 31 30 68 31 One bitmap per value: = 30 00000100 = 31 11001001 = 68 00100010 = 69 00010000 Run-length encoded = 31: 0 zeros, 2 ones, 2 zeros, 1 one, 2 zeros, 1 one IN (30, 68, 69) → OR the bitmaps. product = 31 AND store = 3 → AND them.
Figure 3-11 (simplified): bitmap-indexed, run-length-encoded storage of one column.

Memory bandwidth and vectorized processing:

  • Beyond disk bandwidth, analytic engines care about memory-to-CPU-cache bandwidth, branch mispredictions, pipeline bubbles and SIMD.
  • Tight loops over compressed column chunks that fit in L1 cache, with operators such as AND/OR working on compressed data directly, are vectorized processing.

Sort Order in Column Storage

  • Sort whole rows, not each column independently, or rows can't be reassembled.
  • Choose sort keys from common queries: date_key first for date-range scans, then product_sk to group a day's sales per product.
  • Sorting aids compression. A low-cardinality first key forms long runs, and run-length encoding can shrink billions of rows to a few KB. The effect fades on later keys.

Several different sort orders: C-Store and Vertica store each replica sorted differently and use whichever fits the query. Unlike secondary indexes in a row store (pointers to one row copy), a column store has no pointers, only value columns.

Writing to Column-Oriented Storage

  • Compressed, sorted columns can't be updated in place; a mid-table insert would rewrite every column file.
  • The solution is LSM-trees: writes go to an in-memory sorted store and are merged into new column files in bulk (as in Vertica).
  • Queries combine disk columns with recent in-memory writes, so changes are visible immediately.

Aggregation: Data Cubes and Materialized Views

  • Not every warehouse is columnar, but columnar storage is much faster for ad hoc analytics and is gaining popularity.
  • Materialized view: an on-disk copy of a query's results. It caches common COUNT/SUM/AVG/MIN/MAX. A virtual view is just a query shortcut expanded at read time.
  • It must be updated when the data changes, which makes writes costlier. So it is rare in OLTP and more useful in read-heavy warehouses.
  • Data cube / OLAP cube: a grid of aggregates by dimension, e.g. SUM(net_price) per (date, product). Summing a row or column drops a dimension. Five dimensions make a hypercube.
  • Pro: some queries are precomputed (sales per store yesterday). Con: no flexibility outside the dimensions (share of sales over $100 is impossible if price isn't a dimension). So warehouses keep raw data and use cubes only as a boost.
product_sk 31 32 33 total date_key 140101 140102 140103 total 14 31 85 130 20 12 40 72 9 44 17 70 43 87 142 272 Each cell = SUM(net_price) for one date-product pair; totals drop one dimension.
Figure 3-12 (simplified): two dimensions of a data cube, aggregating by summing.

Summary

  • Engines are optimized for either OLTP or OLAP.
  • OLTP: user-facing with many requests; each touches few records via a key index. Bottleneck: disk seek time.
  • OLAP: analyst-facing with fewer queries, each scanning millions of rows. Bottleneck: disk bandwidth; column storage is the growing answer.
  • OLTP engines come from two schools: log-structured (append only, delete obsolete files: Bitcask, SSTables, LSM-trees, LevelDB, Cassandra, HBase, Lucene) and update-in-place (overwritable fixed-size pages: B-trees).
  • Log-structured engines' key idea: turn random writes into sequential writes for higher write throughput.
  • The chapter also covered more complex indexes and in-memory databases.
  • For analytic scans, indexes matter less than compact encoding that minimizes bytes read, which column storage provides.
  • Knowing internals helps you choose tools, reason about tuning parameters and read engine docs.
Chapter 4

Encoding and Evolution

How encoding formats (JSON, XML, Thrift, Protocol Buffers, Avro) handle schema change, and how encoded data flows between processes via databases, services and messages while old and new code coexist.

Key takeaways

  • Backward compatibility: new code reads old data. Forward compatibility: old code reads new data. Rolling upgrades need both.
  • Language built-in serialization is language-locked, insecure and ignores versioning: transient use only.
  • JSON/XML/CSV suit cross-organization interchange but are vague about numbers and lack binary strings.
  • Thrift/protobuf identify fields by tags: never change or reuse a tag; added fields must be optional or defaulted.
  • Avro has no tags: the reader resolves the writer's schema against its reader's schema by name; only defaulted fields may be added or removed.
  • Data outlives code: schema evolution makes years-old records readable as the current schema.
  • RPC's location transparency is flawed: network calls time out, get retried and have variable latency.
  • Services: servers upgrade first, so requests need backward and responses forward compatibility. Brokers decouple senders and receivers.

Formats for Encoding Data

Feature changes usually change stored data. Relational databases have one schema in force at a time (changed by migrations); schema-on-read databases can mix old and new formats.

Code cannot change everywhere at once: servers use a rolling upgrade (a few nodes at a time, no downtime); client users may not update for a long time. So old and new code and data coexist, and we need:

  • Backward compatibility: newer code reads older data. Usually easy: you know the old format.
  • Forward compatibility: older code reads newer data. Harder: old code must ignore additions.
Backward: new code reads old data Old code Old data New code writes reads Forward: old code reads new data New code New data Old code writes reads Forward is harder: old code must ignore what it does not know
The two directions of compatibility needed while old and new versions coexist.

Data lives in two representations: in memory (objects, lists, hash tables, with pointers, optimized for the CPU) and as a self-contained byte sequence for files or the network. Memory → bytes is encoding (serialization, marshalling); the reverse is decoding (parsing, deserialization, unmarshalling). The book avoids "serialization" because it means something else for transactions (Chapter 7). Encoding is unrelated to encryption.

In-memory objects structs, lists, pointers Byte sequence file or network encode decode
Encoding (serialization) and decoding (parsing) translate between the two representations.

Language-Specific Formats

Java java.io.Serializable, Ruby Marshal, Python pickle, Kryo: convenient, but:

  • Tied to one language; blocks integration with other organizations.
  • Decoding instantiates arbitrary classes: a security hole that can allow remote code execution.
  • Versioning and efficiency are afterthoughts (Java's serialization is notoriously slow and bloated).

JSON, XML, and Binary Variants

Standard textual formats, widely supported and widely disliked: XML is verbose and complicated; JSON is popular via browser support and simplicity; CSV is weaker. Problems:

  • Number ambiguity. XML/CSV cannot tell numbers from digit strings without a schema; JSON does not separate integers from floats or specify precision.
  • Integers above 2⁵³ lose precision in IEEE 754 doubles (JavaScript). Twitter's API therefore returns 64-bit tweet IDs both as a number and as a decimal string.
  • No binary strings: Base64 works but is hacky and adds 33%.
  • XML Schema and JSON Schema are powerful but complicated; many JSON tools skip them and hardcode decoding logic.
  • CSV has no schema and vague escaping (commas, newlines); not all parsers follow the spec.

Still good enough, especially for interchange between organizations, where agreeing on any format matters more than efficiency.

Binary encoding

Internally you can pick a compact, fast format; this matters at terabytes, not for small data. Binary JSON (MessagePack, BSON, BJSON, UBJSON, BISON, Smile) and binary XML (WBXML, Fast Infoset) stay niche. Lacking a schema, they keep the JSON model and embed every field name. Running example (Example 4-1):

{
    "userName": "Martin",
    "favoriteNumber": 1337,
    "interests": ["daydreaming", "hacking"]
}
  • MessagePack: 0x83 = object with 3 fields; 0xa8 = 8-byte string, then userName; 0xa6 + Martin. Length prefixes remove end markers and escaping.
  • 66 bytes vs 81 for compact JSON: a small gain for lost readability. Schema formats reach 32.

Thrift and Protocol Buffers

Protocol Buffers (Google) and Thrift (Facebook), open-sourced 2007–08, both require a schema in an interface definition language (IDL), plus code generation into many languages:

struct Person {            // Thrift
  1: required string       userName,
  2: optional i64          favoriteNumber,
  3: optional list<string> interests
}
message Person {           // Protocol Buffers
    required string user_name       = 1;
    optional int64  favorite_number = 2;
    repeated string interests       = 3;
}
  • Thrift BinaryProtocol: 59 bytes. Type annotation and length per field, but field tags (1, 2, 3) replace field names.
  • Thrift CompactProtocol: 34 bytes. Tag and type share one byte; variable-length integers use each byte's top bit as "more follows" (−64..63 in 1 byte, −8192..8191 in 2), so 1337 takes 2 bytes.
  • Protocol Buffers: similar bit-packing, 33 bytes.
  • required/optional are not encoded; required just adds a runtime check.
Example 4-1 encoded size (bytes) JSON (text) 81 MessagePack 66 Thrift Binary 59 Thrift Compact 34 Protocol Buffers 33 Avro 32 schema formats omit field names
Same record, six encodings: schema-driven binary formats are less than half the size of JSON.
One field: userName = "Martin" MessagePack type+len "userName" type+len "Martin" Thrift Binary type tag 1 length "Martin" Compact / proto tag+type varint len "Martin" Avro length "Martin" name in data tag, not name 1 byte tag+type no field or type id
What identifies a field: its name (MessagePack), a numeric tag (Thrift, protobuf), or only its position in the schema (Avro).

Field tags and schema evolution

Schema evolution: schemas change over time. A record is its fields concatenated, each with tag and type; unset fields are omitted.

  • Renaming a field is fine; changing a tag invalidates existing data.
  • Add fields with new tags: old code skips unknown tags using the type to know the length (forward compatible). New code reads old data (backward compatible) only if added fields are optional or defaulted, never required.
  • Remove only optional fields, and never reuse their tag numbers.

Datatypes and schema evolution

  • Type changes risk precision loss: widening 32 → 64 bits is fine for new code, but old code truncates large values.
  • Protobuf has no list type, only repeated (the tag repeats), so optional can become repeated: new code sees 0–1 elements, old code sees the last one.
  • Thrift's list type forbids that change but supports nested lists.

Avro

Started in 2009 as a Hadoop subproject because Thrift did not fit Hadoop. Schemas in Avro IDL (for humans) or JSON (for machines):

record Person {
    string               userName;
    union { null, long } favoriteNumber = null;
    array<string>        interests;
}
  • No tags; the encoding is 32 bytes, the smallest. Values are just concatenated with nothing identifying fields or types.
  • The decoder walks fields in schema order, so data decodes correctly only with the exact schema it was written with.

The writer's schema and the reader's schema

  • Writer's schema: the version the encoder knows. Reader's schema: the version the decoding code expects.
  • They need only be compatible. The Avro library compares them and translates writer data into the reader's schema.
  • Fields match by name (order may differ). Writer-only fields are ignored; reader-only fields get the reader's default.
Writer's schema Reader's schema userName favoriteNumber interests writer-only field interests userName favoriteNumber reader-only field ignored default fields matched by name; order may differ
Avro schema resolution (after Figure 4-6): match by name, ignore extra writer fields, fill missing reader fields with defaults.

Schema evolution rules

  • Forward: new writer, old reader. Backward: new reader, old writer.
  • Only add or remove fields with a default. Adding without one breaks backward compatibility; removing without one breaks forward.
  • null needs a union, e.g. union { null, long, string } field;, and is a valid default only as the union's first branch. Explicit nullability prevents bugs. So Avro uses unions and defaults, not optional/required.
  • Type changes work if Avro can convert. Renames via reader-side aliases, and adding union branches, are backward but not forward compatible.
ChangeThrift / Protocol BuffersAvro
Field identityNumeric tagName, resolved across both schemas
Add fieldNew tag; optional or defaultMust have default
Remove fieldOptional only; never reuse tagMust have default
RenameFreeAliases; backward only
Nullabilityoptional / requiredUnion with null

But what is the writer's schema?

Embedding the schema in every record would erase the space savings. It depends on context:

  • Large file with lots of records (Hadoop): schema once at the file start, in an Avro object container file.
  • Database with individually written records: prefix each record with a schema version number and store the versions in the database (as Espresso does).
  • Sending records over a network connection: negotiate the version at connection setup (Avro RPC).

A schema-version database also documents schemas and enables compatibility checks; versions can be an incrementing integer or a schema hash.

Dynamically generated schemas

  • No tags makes Avro suit generated schemas: dump a relational database by generating one record schema per table, one field per column (named after it).
  • When columns change, regenerate and export; readers still match fields by name.
  • Thrift/protobuf would need tags assigned by hand (or by a generator careful never to reuse them). Generated schemas were Avro's design goal, not theirs.

Code generation and dynamically typed languages

  • Code generation helps static languages (Java, C++, C#): efficient structures, type checks, IDE autocompletion.
  • In dynamic languages (JavaScript, Ruby, Python) it adds a needless compile step, and blocks access to generated-schema data.
  • Avro's code generation is optional. Container files embed the writer's schema, so they are self-describing; tools like Apache Pig can read and write them without thinking about schemas.

The Merits of Schemas

  • These schema languages are far simpler than XML Schema or JSON Schema, so they support many languages.
  • Not new: ASN.1 (1984) evolves via tags and its DER encoding still encodes X.509 certificates, but it is complex and badly documented.
  • Databases use proprietary binary network protocols, decoded by vendor drivers (ODBC, JDBC).

Benefits of schema-based binary encodings:

  • More compact than binary JSON (no field names).
  • The schema is documentation that cannot go stale, since decoding needs it.
  • A schema database lets you check compatibility before deploying.
  • Generated code gives compile-time type checking.

Modes of Dataflow

Compatibility is a relationship between the process that encodes and the one that decodes. Data flows between processes in three common ways: databases, service calls (REST and RPC), and asynchronous message passing.

Database Writer Database Reader encode later RPC / REST Client Server request response Messaging Sender Broker Recipient one-way async
Who encodes and who decodes in each of the three dataflow modes.

Dataflow Through Databases

  • Writer encodes, reader decodes. Storing data is like messaging your future self: backward compatibility is required.
  • Many processes share a database; during rolling upgrades old code may read what new code wrote, so forward compatibility is also often needed.
  • Snag: old code reads a record with a new field, updates it and writes it back. It should keep the unknown field. Formats support this, but decoding into model objects and re-encoding can drop it; just be aware.
New code DB record fields + new field Old code reads into model object Updates and re-encodes DB record new field lost write read write fix: preserve unknown fields
After Figure 4-7: an older app version updating data written by a newer one can silently drop the new field.

Different values written at different times

  • A database holds values written milliseconds and years ago. Code is replaced in minutes; old data stays in its old encoding: data outlives code.
  • Rewriting large datasets is expensive. Most relational databases add a column with a null default without rewriting (MySQL often rewrites anyway). Espresso uses Avro's evolution rules.
  • So the database appears to use one schema while storing many historical versions.

Archival storage

  • Snapshots (backups, warehouse loads) are usually encoded consistently in the latest schema.
  • Written once and immutable: Avro container files fit, or a columnar format such as Parquet.

Dataflow Through Services: REST and RPC

  • Servers expose an API over the network, a service; clients call it. On the web, browsers use standard HTTP, URLs, TLS and HTML, so any browser reaches any site.
  • Native apps and client-side JavaScript (XMLHttpRequest, Ajax) also call servers, usually getting data such as JSON through an application-specific API.
  • Servers can be clients of other services. Splitting an app this way is service-oriented architecture (SOA), now microservices.
  • Unlike databases' arbitrary queries, services expose only business-logic APIs: encapsulation.
  • Goal: each team deploys its service independently, so client and server versions mix and encodings must stay compatible.

Web services

A web service uses HTTP, in three contexts: device apps calling over the internet; services within one organization (middleware); and cross-organization APIs (credit card processing, OAuth).

RESTSOAP
NatureDesign philosophy on HTTP principlesXML-based protocol
HTTPURLs for resources; HTTP caching, auth, content negotiationAims to be HTTP-independent; WS-* standards
DescriptionOpenAPI (Swagger)WSDL, with code generation
StatusGrowing, esp. cross-organization and microservicesLarge enterprises; tool-dependent, vendor interop issues

An API following REST is RESTful. SOAP is not required for SOA.

The problems with remote procedure calls (RPCs)

Earlier technologies: EJB and RMI (Java only), DCOM (Microsoft only), CORBA (very complex, no compatibility). All are RPC (since the 1970s), which makes a remote call look local: location transparency. This is fundamentally flawed:

Local callNetwork request
PredictableLost messages, slow or down remote; must retry
Returns, throws or hangsCan time out, leaving the outcome unknown
Runs onceRetries may repeat the action unless you add idempotence
Consistent durationMuch slower; under 1 ms to many seconds
Passes pointersMust encode all parameters; hard for big objects
One languageTypes translated across languages (e.g. 2⁵³ in JavaScript)

So do not make remote services look like local objects. REST appeals partly because it does not hide the network.

Current directions for RPC

  • Thrift and Avro include RPC; gRPC uses Protocol Buffers; Finagle uses Thrift; Rest.li uses JSON over HTTP.
  • They admit calls are remote: Finagle and Rest.li use futures for failable async calls and combining parallel requests; gRPC has streams of requests and responses. Some offer service discovery.

Data encoding and evolution for RPC

  • Assume servers upgrade first, clients second: requests need backward, responses forward compatibility.
  • Rules come from the encoding: Thrift, gRPC and Avro RPC follow their formats; SOAP's XML schemas have pitfalls; REST typically uses schemaless JSON, where adding optional request parameters or response fields is compatible.
  • Providers cannot force external clients to upgrade, so compatibility may last forever and breaking changes mean multiple API versions side by side.
  • Versioning has no standard: REST puts it in the URL or Accept header, or the server stores each API key's version, set via an admin interface.
upgraded second upgraded first Old client New server request: backward new code reads old data response: forward old code reads new data guarantees inherited from the encoding format
With servers upgraded before clients, requests need backward and responses forward compatibility.

Message-Passing Dataflow

Between RPC and databases: messages arrive with low latency, but via a message broker (message queue) that stores them temporarily. Versus direct RPC, a broker:

  • Buffers for unavailable or overloaded recipients, and redelivers after crashes.
  • Hides recipient addresses (useful when cloud VMs come and go).
  • Fans out one message to many recipients, and decouples senders from consumers.

Messaging is usually one-way and asynchronous; any reply uses a separate channel.

Message brokers

  • Once commercial (TIBCO, IBM WebSphere, webMethods); now open source (RabbitMQ, ActiveMQ, HornetQ, NATS, Apache Kafka).
  • Producers send to a named queue or topic; the broker delivers to consumers or subscribers. Consumers can chain to other topics or answer on a reply queue.
  • Messages are bytes plus metadata, so any encoding works; compatible encodings let you deploy publishers and consumers in any order.
  • Republishing consumers must preserve unknown fields (as in Figure 4-7).
Producer A Producer B Broker queue / topic Consumer 1 Consumer 2 optional reply queue
Producers publish to a named queue or topic; the broker buffers and delivers to consumers. Replies need a separate channel.

Distributed actor frameworks

  • The actor model replaces threads (races, locks, deadlock) with actors: private state, asynchronous messages, one message at a time. Delivery is not guaranteed.
  • Distributed actor frameworks use the same messaging across nodes, encoding remote messages transparently. Location transparency fits better here because loss is already assumed.
  • Rolling upgrades still need forward and backward compatibility.
FrameworkDefault encodingRolling upgrades
AkkaJava serializationPossible if swapped for e.g. Protocol Buffers
OrleansCustom formatNo by default: new cluster, move traffic; plug-ins possible
Erlang OTPRecords, hard to changeNeed careful planning; maps (R17, 2014) may help

Summary

  • Encoding choices affect efficiency and, more importantly, architecture and deployment options.
  • Rolling upgrades give releases without downtime and lower risk, which helps evolvability; nodes then run mixed versions, so data needs backward and forward compatibility.
  • Language-specific encodings: one language, often no compatibility.
  • JSON, XML, CSV: widespread; compatibility depends on use; vague about numbers and binary strings.
  • Thrift, Protocol Buffers, Avro: compact, clear compatibility semantics, schemas for docs and code generation; but not human-readable without decoding.
  • Dataflow modes: databases (writer encodes, reader decodes), RPC and REST (requests and responses each encoded and decoded), async messaging via brokers or actors.
  • With care, compatibility and rolling upgrades are quite achievable.
Part II

Distributed Data

Part I covered data on a single machine. Part II asks: what happens if multiple machines are involved in storage and retrieval of data?

Why distribute a database?

  • Scalability: data volume, read load or write load grows past what one machine can handle.
  • Fault tolerance / high availability: keep working when a machine, the network or a whole datacenter goes down.
  • Latency: serve users from a datacenter geographically close to them.

Scaling to Higher Load

  • Shared-memory (vertical scaling, scaling up): one big machine. Cost grows faster than linearly; twice the size does not handle twice the load; limited to one location.
  • Shared-disk: several machines, shared disk array over a fast network. Used for some data warehousing; contention and locking overhead limit scalability.
  • Shared-nothing (horizontal scaling, scaling out): each node uses its own CPUs, RAM and disks; coordination is in software over a normal network. No special hardware; can span regions and survive a datacenter loss. Part II focuses on this architecture because it demands the most caution from the application developer: the database cannot hide the constraints and trade-offs from you.
  • Caveat from the book: a simple single-threaded program can sometimes beat a cluster with over 100 CPU cores.

Replication Versus Partitioning

Database Partition 1 Replica node A Replica node B Partition 2 Replica node C Replica node D
Figure II-1 (simplified): a database split into two partitions, with two replicas per partition.
  • Replication (Chapter 5): keep a copy of the same data on several nodes, possibly in different locations. Gives redundancy and can improve performance.
  • Partitioning (Chapter 6, also called sharding): split a big database into smaller subsets, assigned to different nodes.
  • Separate mechanisms, but they usually go hand in hand. Then Chapter 7 covers transactions, and Chapters 8 and 9 the fundamental limitations of distributed systems.
Chapter 5

Replication

Keeping a copy of the same data on several networked machines. Copying static data is easy; all the difficulty is in replicating changes. The chapter covers the three algorithms almost every distributed database uses: single-leader, multi-leader and leaderless.

Key takeaways

  • Replication buys high availability, disconnected operation, lower latency (data near users) and read scalability.
  • Single-leader: all writes go to one leader that streams changes to followers. Easy to reason about, no conflict resolution.
  • Synchronous vs asynchronous replication decides what happens on faults: promoting an async follower after leader failure can lose recently committed writes.
  • Failover is fraught: lost writes, split brain, and choosing the right timeout. Some teams prefer manual failover.
  • Replication lag breaks user expectations; the guarantees that fix it are read-after-write, monotonic reads and consistent prefix reads.
  • Multi-leader and leaderless tolerate faulty nodes, network problems and latency spikes better, but allow concurrent writes, so conflicts must be resolved and consistency is weak.
  • Quorums (w + r > n) make stale reads less likely, not impossible. Sloppy quorums are not quorums in the traditional sense.
  • Last write wins converges by silently dropping writes. Version vectors tell overwrites from concurrent writes so no data is lost.

Why replicate

  • Keep data geographically close to users (lower latency).
  • Keep working when some parts fail (higher availability).
  • Scale out the machines serving reads (higher read throughput).

Assumption for this chapter: the whole dataset fits on every machine. Partitioning comes in Chapter 6.

Key choices are often database config options: synchronous vs asynchronous, and how to handle failed replicas. The principles date from the 1970s because network constraints have not changed.

Leaders and Followers

Each node holding a copy is a replica. Every write must reach every replica. The most common solution is leader-based replication (also called active/passive or master–slave):

  1. One replica is the leader (primary). Clients send all writes to it; it writes to local storage first.
  2. The others are followers (read replicas, secondaries, hot standbys). The leader sends each change to them as a replication log or change stream; each follower applies writes in the leader's order.
  3. Reads can go to the leader or any follower; followers are read-only to clients.

Built into PostgreSQL (since 9.0), MySQL, Oracle Data Guard, SQL Server AlwaysOn Availability Groups; also MongoDB, RethinkDB, Espresso; and message brokers Kafka and RabbitMQ highly available queues. DRBD and some network filesystems are similar.

Writer client Reader client Leader Follower 1 Follower 2 Follower 3 write repl. log read (any replica)
Figure 5-1 (simplified): writes go only to the leader; followers apply its log in order; reads may go anywhere.

Synchronous Versus Asynchronous Replication

Example: a user updates a profile image. Client sends to leader; leader forwards to followers; leader eventually reports success.

  • Synchronous follower: leader waits for its confirmation before reporting success to the user and making the write visible.
  • Asynchronous follower: leader sends the change and does not wait.
  • Replication is usually under a second, but there is no bound: followers can fall minutes behind during recovery, near-capacity load, or network problems.
Client Leader Follower 1 Follower 2 update sync ack ok to user async, delayed time →
Figure 5-2 (simplified): the leader waits for follower 1 (sync) before replying; follower 2 (async) applies the change much later.
SynchronousAsynchronous
Up-to-date copyGuaranteed on follower; survives leader lossNot guaranteed; unreplicated writes lost if leader dies
Follower down/slowLeader must block all writesLeader keeps accepting writes
Durability of acked writeOn at least two nodesNot guaranteed even if confirmed to client
  • All-synchronous is impractical: any one outage halts the system.
  • Semi-synchronous: one follower synchronous, the rest asynchronous; if the sync one gets slow, an async one is promoted to sync. Guarantees an up-to-date copy on two nodes.
  • Fully asynchronous is common, especially with many or geographically spread followers, despite weakened durability.
  • Research: chain replication is a synchronous variant that avoids data loss with good performance (used in Microsoft Azure Storage). Replication consistency is closely tied to consensus (Chapter 9).

Setting Up New Followers

Needed to add replicas or replace failed nodes. Copying data files does not work (data is in flux); locking the database for writes defeats availability. Instead, without downtime:

1. Snapshot consistent, no lock 2. Copy to new follower 3. Request backlog since log position 4. Caught up stream live changes Snapshot tied to exact log position: PostgreSQL log sequence number, MySQL binlog coordinates
Adding a follower without downtime: snapshot, copy, replay the backlog from the snapshot's log position.
  • Snapshots are usually built in (needed for backups); sometimes third-party tools, e.g. innobackupex for MySQL.
  • Practical steps vary: fully automated in some systems, an arcane manual multi-step workflow in others.

Handling Node Outages

Nodes go down from faults or planned maintenance (e.g. a kernel security patch reboot). Goal: keep the whole system running and keep the impact of one outage small.

Follower failure: catch-up recovery. Each follower keeps a local log of changes received. After a crash or network break it knows its last processed transaction, requests all later changes from the leader, applies them, and is caught up.

Leader failure: failover. Promote a follower to leader, reconfigure clients to write to it, and make other followers consume from it. Manual or automatic. Automatic failover steps:

1. Detect failure timeout, e.g. 30 s no foolproof way 2. Choose leader election or controller most up-to-date wins 3. Reconfigure writes to new leader old leader → follower Risks: lost async writes · split brain · wrong timeout
Automatic failover. Agreeing on a new leader is a consensus problem (Chapter 9).

What goes wrong with failover:

  • With async replication the new leader may lack some old-leader writes. If the old leader rejoins, those writes may conflict; usually they are discarded, violating clients' durability expectations.
  • Discarding is worse when outside systems depend on the data. GitHub incident: an out-of-date MySQL follower was promoted; its lagging autoincrement counter reused primary keys that were also used in Redis, so private data was shown to the wrong users.
  • Split brain: two nodes both believe they are leader. If both accept writes without conflict resolution, data is lost or corrupted. Shutting one down (fencing, STONITH) helps, but a badly designed mechanism can shut down both.
  • Timeout: too long means slow recovery; too short means unnecessary failovers from load spikes or network glitches, which make an already struggling system worse.

No easy solutions, so some operations teams fail over manually even when automation exists. Node failures, unreliable networks and the consistency/durability/availability/latency trade-offs are fundamental (Chapters 8 and 9).

Implementation of Replication Logs

Statement-based replication. The leader logs each write statement (INSERT, UPDATE, DELETE); followers parse and execute it as if from a client. Breaks when:

  • Nondeterministic functions (NOW(), RAND()) give different values per replica.
  • Autoincrement columns or statements that depend on existing data (UPDATE … WHERE <condition>) must run in exactly the same order everywhere, limiting concurrent transactions.
  • Side effects (triggers, stored procedures, UDFs) differ unless fully deterministic.

Workaround: the leader substitutes fixed values for nondeterministic calls, but edge cases abound. MySQL used it before 5.1; it now switches to row-based on any nondeterminism. VoltDB uses it safely by requiring deterministic transactions. Its advantage: compactness.

Write-ahead log (WAL) shipping. Storage engines already append every write to a log (the LSM segments themselves, or a B-tree's WAL). The leader sends that same log to followers, which build identical data structures. Used in PostgreSQL and Oracle.

  • Downside: the WAL is very low level (which bytes changed in which disk blocks), so replication is coupled to the storage engine.
  • Leader and followers usually cannot run different versions, so upgrades need downtime. A protocol that allows newer followers enables zero-downtime upgrades: upgrade followers, then fail over to one.

Logical (row-based) log replication. A separate log format for replication, decoupled from storage internals: a logical log. For relational databases, records at row granularity:

  • Insert: new values of all columns.
  • Delete: enough to identify the row (primary key, or all old column values if none).
  • Update: row identity plus new values of all (or changed) columns.
  • A multi-row transaction produces several records plus a commit record. MySQL's binlog in row-based mode works this way.

Benefits: easier backward compatibility (different versions or even storage engines on leader and follower), and easy for external applications to parse, e.g. to feed a data warehouse or custom indexes and caches. That is change data capture (Chapter 11).

Trigger-based replication. Moves replication to the application layer when you need a subset of data, replication between different databases, or custom conflict resolution. Oracle GoldenGate reads the database log for applications. Alternatively a trigger runs custom code on each write, logs the change into a separate table, and an external process replicates it (Databus for Oracle, Bucardo for Postgres). Higher overhead and more bugs than built-in replication, but flexible.

Statement SQL text compact NOW(), RAND() break it WAL shipping bytes in blocks exact copy engine-coupled same version Logical (row) row changes decoupled versions differ OK enables CDC Trigger-based app code most flexible overhead bug-prone inside the database application layer
The four replication log methods and the main strength and weakness the book gives for each.

Problems with Replication Lag

For read-mostly workloads (common on the web), a read-scaling architecture adds many followers and spreads reads across them. This only works with asynchronous replication: fully synchronous to many nodes would be very unreliable.

  • Reading from a lagging async follower returns outdated data, so leader and follower can answer the same query differently.
  • The inconsistency is temporary: stop writing and followers catch up. This is eventual consistency. Async relational followers have it too, not just NoSQL.
  • "Eventually" is deliberately vague: no limit on lag. Replication lag is normally a fraction of a second, but can reach seconds or minutes near capacity or with network problems.

Reading Your Own Writes

A user submits data (written to the leader) then views it (read from a follower). If the follower has not caught up, the user's data seems lost.

User 1234 Leader Follower 2 insert comment ok arrives late read no results!
Figure 5-3 (simplified): a read from a stale replica right after a write. The fix is read-after-write consistency.

Read-after-write consistency (read-your-writes): a user who reloads always sees their own updates. No promise about other users' updates. Techniques with leader-based replication:

  • Read things the user may have modified from the leader, the rest from followers. Needs a way to know without querying: e.g. read the user's own profile from the leader, others' profiles from followers.
  • If most things are user-editable, that negates read scaling. Use other criteria: read from the leader for one minute after the user's last update, or refuse queries on followers more than one minute behind.
  • The client remembers the timestamp of its latest write; the serving replica must reflect updates up to that time, otherwise another replica serves it or the query waits. A logical timestamp (e.g. log sequence number) or system clock (then clock sync is critical).
  • Multiple datacenters: any request needing the leader must route to the leader's datacenter.

Cross-device read-after-write consistency (e.g. desktop browser and mobile app):

  • One device does not know the other's last-update timestamp, so that metadata must be centralized.
  • Devices may route to different datacenters (home broadband vs cellular). If reads must hit the leader, first route all of a user's devices to the same datacenter.

Monotonic Reads

Reads to different replicas can make time appear to go backward. User 2345 runs the same query twice: a low-lag follower returns user 1234's new comment, then a high-lag follower returns nothing. Likely when each page refresh goes to a random server.

User 1234 Leader Follower 1 Follower 2 User 2345 insert comment read 1: sees it read 2: gone
Figure 5-4 (simplified): a fresh read followed by a staler one. The fix is monotonic reads.
  • Monotonic reads: a user's successive reads never return older data after newer data. Weaker than strong consistency, stronger than eventual consistency.
  • Implementation: each user always reads from the same replica, chosen e.g. by a hash of the user ID rather than randomly. If that replica fails, reroute.

Consistent Prefix Reads

A violation of causality. Mr. Poons asks Mrs. Cake how far into the future she can see; she answers about ten seconds. An observer reading through followers gets her reply via a low-lag path and his question via a high-lag path, so the answer appears before the question.

Partition 1 1. Question Partition 2 2. Answer Observer sees Answer, then Question long lag short lag
Figure 5-5 (simplified): partitions replicated at different speeds let an observer see the answer before the question.
  • Consistent prefix reads: if writes happen in some order, every reader sees them in that order.
  • Mainly a problem in partitioned databases: partitions operate independently with no global write order, so a reader sees some parts older and some newer. A single write order always gives a consistent prefix.
  • Fixes: write causally related data to the same partition (not always efficient), or algorithms that track causal dependencies (see happens-before, below).

Solutions for Replication Lag

  • Ask how the application behaves if lag grows to minutes or hours. If that is a bad user experience, design for a stronger guarantee such as read-after-write.
  • Pretending async replication is synchronous is a recipe for problems.
  • Application-level fixes (e.g. some reads on the leader) are complex and easy to get wrong. Better if the database "does the right thing": that is why transactions exist.
  • Many distributed databases dropped transactions, claiming they cost too much performance and availability and that eventual consistency is inevitable at scale. The book calls this partly true but overly simplistic (Chapters 7, 9, Part III).

Multi-Leader Replication

Single-leader's main downside: all writes go through one leader; if you cannot reach it, you cannot write. Multi-leader (master–master, active/active) lets several nodes accept writes; each leader also acts as a follower of the others. (With partitioning, each partition has one leader in a single-leader setup.)

Use Cases for Multi-Leader Replication

Rarely worth the complexity inside one datacenter.

Multi-datacenter operation. A leader in each datacenter; normal leader–follower replication inside each; leaders replicate to each other across datacenters.

Datacenter 1 Datacenter 2 Leader Leader Follower Follower Follower Follower async conflict resolution
Figure 5-6 (simplified): a leader per datacenter, leaders replicate to each other asynchronously and must resolve conflicts.
Single-leader across DCsMulti-leader across DCs
PerformanceEvery write crosses the internet to the leader's DC; adds latencyWrites processed locally, replicated async; inter-DC delay hidden from users
DC outageFailover promotes a follower in another DCEach DC runs independently; catches up on return
Network problemsVery sensitive: writes go synchronously over the inter-DC linkTolerates temporary interruptions; writes still processed
  • Often via external tools: Tungsten Replicator (MySQL), BDR (PostgreSQL), GoldenGate (Oracle).
  • Big downside: the same data may be modified concurrently in two DCs, so write conflicts must be resolved.
  • Often retrofitted, with pitfalls around autoincrementing keys, triggers and integrity constraints. Often considered dangerous territory to avoid if possible.

Clients with offline operation. E.g. calendar apps on phone, laptop and other devices must read and write while offline, then sync. Each device's local database is a leader; sync is async multi-leader replication with lag of hours or days. Architecturally the same as multi-DC taken to the extreme: each device is a "datacenter" on a very unreliable network. Broken calendar sync implementations show how hard it is. CouchDB is designed for this mode.

Collaborative editing. Etherpad and Google Docs allow concurrent editing. Edits apply instantly to the local replica (browser state) and replicate async to the server and other editors.

  • To guarantee no conflicts, lock the document before editing: equivalent to single-leader with transactions on the leader.
  • For faster collaboration, make the unit of change tiny (a keystroke) and skip locks: this brings all multi-leader challenges, including conflict resolution.

Handling Write Conflicts

The biggest multi-leader problem. Wiki example: user 1 changes a page title A→B, user 2 changes A→C at the same time. Both succeed at their local leader; the conflict is detected when changes replicate. Cannot happen with a single leader.

User 1 Leader 1 Leader 2 User 2 title = B title = C ok ok conflict detected
Figure 5-7 (simplified): two leaders accept concurrent updates to the same record; the conflict surfaces only on async replication.

Synchronous versus asynchronous conflict detection. A single leader makes the second writer block or abort and retry. Multi-leader accepts both and finds the conflict later, possibly too late to ask the user. Synchronous detection (wait for all replicas before acking) gives up independent writes; then just use single-leader.

Conflict avoidance. Simplest and often recommended (many implementations handle conflicts poorly): route all writes for a record through one leader. E.g. route each user to a "home" datacenter (maybe the geographically nearest); for that user it is effectively single-leader. Breaks down when the designated leader changes: a datacenter fails, or a user moves closer to another datacenter.

Converging toward a consistent state. Single-leader applies writes in sequence, so the last write sets the final value. Multi-leader has no defined order: in the wiki example leader 1 ends with C, leader 2 with B. Every scheme must make replicas eventually equal, so resolution must be convergent. Options:

  • Give each write a unique ID (timestamp, random number, UUID, hash of key and value); highest wins, others discarded. With timestamps this is last write wins (LWW): popular but dangerously prone to data loss.
  • Give each replica an ID; the higher-numbered replica's writes win. Also loses data.
  • Merge values, e.g. sort and concatenate: "B/C".
  • Record the conflict in an explicit data structure keeping all information; application code resolves it later (perhaps by asking the user).

Custom conflict resolution logic. Most multi-leader tools let application code resolve conflicts:

  • On write: a handler runs as soon as a conflict appears in the replicated log (Bucardo: a Perl snippet). Runs in the background, must be fast, cannot prompt a user.
  • On read: all conflicting writes are stored and returned on the next read; the app (or the user) resolves and writes back. CouchDB works this way.
  • Resolution is per row or document, not per transaction: each write in a multi-write transaction is resolved separately.

Automatic Conflict Resolution. Custom code gets complicated and error-prone. Amazon's shopping cart handler once preserved added items but not removals, so removed items reappeared. Research directions:

  • CRDTs (conflict-free replicated datatypes): sets, maps, ordered lists, counters that concurrent users can edit and that resolve conflicts sensibly. Some are in Riak 2.0. They use two-way merges.
  • Mergeable persistent data structures: track history explicitly, like Git, with a three-way merge.
  • Operational transformation: behind Etherpad and Google Docs; designed for concurrent editing of an ordered list, such as the characters of a document.
  • Database implementations are still young but may make multi-leader sync much simpler.

What is a conflict? Some are obvious (same field set to two values). Others are subtle: a meeting room booking system must prevent overlapping bookings for one room, yet two bookings made on two different leaders can conflict even if each checked availability first. Covered further in Chapters 7 and 12.

Multi-Leader Replication Topologies

A replication topology is the set of paths along which writes propagate. Two leaders allow only one. With more:

(a) Circular (b) Star root (c) All-to-all MySQL default generalizes to tree most general
Figure 5-8 (simplified): circular, star and all-to-all multi-leader topologies.
  • All-to-all: every leader sends to every other. Most general.
  • Circular: each node receives from one and forwards (plus its own writes) to one other. MySQL's default.
  • Star: a root forwards writes to all others; generalizes to a tree.
  • In circular and star, writes pass through several nodes. To stop infinite loops, each node has a unique ID and each write is tagged with the IDs it has passed; a node ignores writes tagged with its own ID.
  • Circular/star: one failed node can block replication between others until fixed; rerouting is usually manual. Denser topologies (all-to-all) avoid a single point of failure.
  • All-to-all: faster links let messages overtake others.
Client A Leader 1 Leader 2 Leader 3 Client B insert insert, slow update update arrives first
Figure 5-9 (simplified): leader 2 receives B's update before the insert it depends on.
  • A causality problem like consistent prefix reads: the update depends on the insert. Timestamps are not enough because clocks are not reliably in sync.
  • Version vectors can order these events (see Detecting Concurrent Writes).
  • Many systems implement conflict detection poorly: at the time of writing PostgreSQL BDR gives no causal ordering, and Tungsten Replicator does not even try to detect conflicts. Read the docs and test the guarantees.

Leaderless Replication

Single- and multi-leader rely on a leader to order writes. Leaderless systems let any replica accept client writes. Early replicated systems were leaderless; the idea returned with Amazon's in-house Dynamo. Riak, Cassandra and Voldemort follow it, hence "Dynamo-style". (AWS DynamoDB is a different, single-leader architecture.)

  • The client sends writes to several replicas directly, or a coordinator node does it, but without enforcing a write order. This has profound consequences.

Writing to the Database When a Node Is Down

Three replicas, one down for a reboot. Leader-based might need failover; leaderless has no failover. User 1234 sends the write to all three in parallel; two acknowledge; two of three is enough, so the write succeeds and the missed replica is ignored.

When the node returns it serves stale values. So reads also go to several nodes in parallel, and version numbers decide which response is newer.

User 1234 write v7 User 2345 read Replica 1: v7 Replica 2: v7 Replica 3: v6 ✗ 2 of 3 ok Read from all 3 v7, v7, v6 newest = v7 Read repair write v7 back to replica 3
Figure 5-10 (simplified): quorum write while replica 3 is down, then a quorum read that spots and repairs the stale v6.

Read repair and anti-entropy. Two ways a returning node catches up:

  • Read repair: a parallel read spots a stale response (replica 3 returns v6, others v7) and writes the newer value back. Works well for frequently read values.
  • Anti-entropy process: background process compares replicas and copies missing data. No write order and possibly a long delay, unlike a replication log.
  • Not every system has both (Voldemort lacks anti-entropy). Without it, rarely read values may be missing from some replicas, reducing durability.

Quorums for reading and writing. With n replicas, a write needs w confirmations and a read queries at least r nodes. If w + r > n, at least one node read is up to date. These are quorum reads and writes (strict quorum); r and w are minimum votes.

  • Common: n odd (3 or 5), w = r = (n + 1) / 2 rounded up.
  • Few writes, many reads: w = n, r = 1. Faster reads, but one failed node fails all writes.
  • The cluster may have more than n nodes; each value lives on only n of them (partitioning, Chapter 6).
  • w < n: writes survive an unavailable node. r < n: reads do.
  • n=3, w=2, r=2 tolerates one unavailable node; n=5, w=3, r=3 tolerates two.
  • Requests normally go to all n; w and r say how many replies to wait for.
  • Fewer than w or r available: error. The cause (crash, full disk, network) does not matter; only whether a success came back.
n = 5, w = 3, r = 3 write succeeded on w = 3 read from r = 3 new new new old old w + r = 6 > 5: at least one node read has the latest write
Figure 5-11 (simplified): if w + r > n, the read set and the write set must overlap.

Limitations of Quorum Consistency

  • Quorums need not be majorities; only overlap of read and write sets matters. Majorities (more than n/2) are common because they tolerate up to n/2 failures. Other assignments allow flexibility in distributed algorithm design.
  • w + r ≤ n: stale reads more likely, but lower latency and higher availability; unavailable only when reachable replicas fall below w or r.

Even with w + r > n, stale values can be returned:

  • A sloppy quorum may put the w writes on different nodes than the r reads, so no guaranteed overlap.
  • Concurrent writes have no clear order; the only safe fix is merging. LWW by timestamp can lose writes to clock skew.
  • A write concurrent with a read may be on only some replicas; the read may return old or new.
  • A write that succeeded on fewer than w replicas is reported failed but not rolled back where it did succeed, so later reads may or may not return it.
  • If a node with the new value fails and is restored from a replica with the old value, the new value may fall below w copies.
  • Even when everything works, timing edge cases exist (Linearizability and quorums, Chapter 9).

So Dynamo-style databases suit workloads that tolerate eventual consistency. w and r tune the probability of stale reads; they are not absolute guarantees. You usually do not get read-your-writes, monotonic reads or consistent prefix reads; stronger guarantees need transactions or consensus.

Monitoring staleness. Even if stale reads are tolerable, alert when replication falls far behind (network problems, overloaded node).

  • Leader-based: same write order everywhere, each node has a log position; lag = leader position − follower position.
  • Leaderless: no fixed write order, so harder. With only read repair, a rarely read value may be ancient.
  • Research predicts the expected percentage of stale reads from n, w, r; not yet common. For operability, quantify "eventual".

Sloppy Quorums and Hinted Handoff

Quorums tolerate failed and slow nodes without failover (return after w or r replies), which suits high-availability, low-latency workloads that accept occasional stale reads. But a network interruption can cut a client off from enough nodes that it cannot assemble a quorum, though the nodes are alive. In a cluster with many more than n nodes, the client may still reach some nodes. The trade-off: return errors, or accept the write on reachable nodes outside the value's n "home" nodes?

Client home nodes (n = 3) A B C cut off Stand-in D holds write + hint w = 3 incl. D hinted handoff
Sloppy quorum: a reachable non-home node accepts the write; hinted handoff sends it home when the network heals.
  • Sloppy quorum: still need w and r successes, but they may come from non-home nodes. (The book's analogy: locked out of your house, you sleep on the neighbor's couch.)
  • Hinted handoff: after the interruption, writes held for other nodes are sent to their home nodes.
  • Raises write availability: any w reachable nodes will do. But even with w + r > n a read may miss the latest value until handoff completes. It is only a durability assurance: the data is on w nodes somewhere.
  • Optional in all common Dynamo implementations: on by default in Riak, off by default in Cassandra and Voldemort.

Multi-datacenter operation. Leaderless also suits multiple datacenters, being built to tolerate concurrent writes, network interruptions and latency spikes.

  • Cassandra, Voldemort: n spans all DCs; config says how many replicas per DC. Writes go to all replicas, but the client usually waits only for a quorum in its local DC; remote writes are often async.
  • Riak: client traffic stays in one DC, n counts replicas within one DC; cross-DC replication between clusters is async in the background, similar to multi-leader.

Detecting Concurrent Writes

Dynamo-style databases let several clients write the same key concurrently, so conflicts occur even with strict quorums, and also during read repair or hinted handoff. Events arrive in different orders at different nodes. Example: clients A and B write key X on three nodes:

  • Node 1 gets A's write, never B's (transient outage).
  • Node 2 gets A then B. Node 3 gets B then A.
  • If each node simply overwrites, they stay permanently inconsistent: node 2 says X = B, the others say A.
Client A Node 1 Node 2 Node 3 Client B set X = A ✗ set X = B X = A X = B X = A
Figure 5-12 (simplified): with plain overwrites, concurrent writes leave nodes permanently disagreeing.

Replicas must converge. Most implementations are poor at this, so to avoid losing data the application developer must know the database's conflict handling internals.

Last write wins (discarding concurrent writes). Each replica keeps only the most "recent" value. But for concurrent writes neither happened "first"; the order is undefined. LWW forces an arbitrary order: attach a timestamp, keep the biggest, discard the rest.

  • Only conflict resolution in Cassandra; optional in Riak.
  • Converges at the cost of durability: of several concurrent writes all acked to clients (on w replicas), only one survives; the others are silently discarded. LWW may even drop non-concurrent writes (clock issues, Chapter 8).
  • Acceptable for e.g. caching. If losing data is not acceptable, LWW is a poor choice.
  • Only safe use: write each key once and treat it as immutable. Recommended Cassandra practice: a UUID as the key, so each write has a unique key.

The "happens-before" relationship and concurrency.

  • Figure 5-9's writes are not concurrent: B's update builds on A's insert, so B is causally dependent on A.
  • Figure 5-12's writes are concurrent: neither client knew about the other.
  • A happens before B if B knows about, depends on, or builds on A. Two operations are concurrent if neither happens before the other.
  • Three possibilities: A before B, B before A, or concurrent. A later operation may overwrite an earlier one; concurrent ones are a conflict to resolve.

Concurrency, Time, and Relativity. Concurrency is not about overlapping in physical time (hard to tell anyway, given clock problems). Operations are concurrent if they are unaware of each other. Some compare this with special relativity: distant events cannot affect each other faster than light. In computers, slow or interrupted networks can make operations far apart in time still concurrent.

Capturing the happens-before relationship. Start with a single replica. Two clients add items to one shopping cart (the book offers air traffic controllers adding aircraft as a less inane analogy):

  1. Client 1 adds milk. Server stores it as version 1, echoes value and version.
  2. Client 2 adds eggs, unaware of milk. Server stores eggs as version 2 alongside milk as a separate value; returns both and version 2.
  3. Client 1 sends [milk, flour] with version 1. It supersedes [milk] but is concurrent with [eggs]. Server: version 3 [milk, flour], keeps [eggs].
  4. Client 2 merges [milk] and [eggs], adds ham, sends [eggs, milk, ham] with version 2. Overwrites [eggs]; concurrent with [milk, flour]. Values: v3 [milk, flour], v4 [eggs, milk, ham].
  5. Client 1 merges its v3 values, adds bacon, sends [milk, flour, eggs, bacon] with version 3. Overwrites [milk, flour]; keeps concurrent [eggs, milk, ham].
Client 1 Server Client 2 milk v1 eggs v2 milk, flour (v1) v3 eggs, milk, ham (v2) v4 milk, flour, eggs, bacon (v3) v5 siblings: v4 and v5 each write carries the version of its prior read
Figure 5-13 (simplified): each write names the version it was based on, so the server knows what it overwrites and what is concurrent.
v1 milk v2 eggs v3 +flour v4 +ham v5 +bacon final siblings v4 and v5 arrow = later write knew about the earlier one; no write is lost
Figure 5-14 (simplified): graph of causal dependencies in the cart example.

Clients are never fully up to date, yet old versions are eventually overwritten and no writes are lost. The server decides concurrency from version numbers alone, without interpreting values. The algorithm:

  • The server keeps a version number per key, increments it on every write, and stores it with the value.
  • A read returns all values not yet overwritten plus the latest version. A client must read before writing.
  • A write includes the version from the prior read and merges all values received then. (The write response can act like a read, enabling chained writes.)
  • On a write with version v, the server overwrites all values with version ≤ v (they were merged) and keeps higher-versioned values (concurrent).
  • A write without a version is concurrent with everything: it overwrites nothing and is returned as one of the values later.

Merging concurrently written values. No data is silently dropped, but clients must merge concurrent values, which Riak calls siblings. Same problem as multi-leader conflict resolution.

  • Picking one by version or timestamp (LWW) loses data.
  • Cart: take the union. Final siblings [milk, flour, eggs, bacon] and [eggs, milk, ham] merge to [milk, flour, eggs, bacon, ham], no duplicates.
  • With removals, a union brings back an item removed in only one sibling. So removal leaves a tombstone: a deletion marker with a version number.
  • Hand-written merging is complex and error-prone; Riak's datatype support uses CRDTs that merge siblings automatically, including deletions.

Version vectors. With multiple replicas and no leader, one version number is not enough: use a version number per replica as well as per key.

  • Each replica increments its own number on writes it processes and tracks the numbers it has seen from other replicas. That tells it what to overwrite and what to keep as siblings.
  • The collection of these numbers is a version vector. Notable variant: the dotted version vector in Riak 2.0.
  • Sent to clients on read and back on write (Riak encodes it as a string called causal context). Lets the database tell overwrites from concurrent writes.
  • Reading from one replica and writing back to another is safe: siblings may appear, but nothing is lost if siblings are merged correctly.
  • A version vector is sometimes called a vector clock, but they are not quite the same; for comparing replica state, version vectors are the right structure.
One counter per replica, per key stored value R1:2 R2:1 R3:0 incoming write's context R1:2 R2:1 R3:1 Write has seen stored value → overwrite Neither has seen the other → keep both as siblings
Version vectors: the per-replica counters show whether a write overwrites a value or is concurrent with it. (Illustrative values; the book gives no numeric example.)

Summary

  • Replication serves high availability (survive a machine, several, or a whole datacenter down), disconnected operation (work through network interruptions), latency (data near users) and scalability (more reads than one machine handles).
  • A simple goal that is remarkably tricky: you must think about concurrency and every failure, at minimum unavailable nodes and network interruptions (not even counting silent data corruption from bugs).
  • Single-leader: writes to one leader, which streams change events to followers; reads anywhere, possibly stale.
  • Multi-leader: writes to any of several leaders, which stream changes to each other and to followers.
  • Leaderless: writes to several nodes and reads from several in parallel to detect and correct stale data.
  • Single-leader is popular: easy to understand, no conflict resolution. Multi-leader and leaderless are more robust to faulty nodes, network interruptions and latency spikes, but harder to reason about with very weak consistency.
  • Sync vs async replication profoundly changes fault behavior. Async is fast when healthy; plan for growing lag and server failures. Promoting an async follower can lose recently committed data.
  • Consistency models for replication lag: read-after-write (see your own submissions), monotonic reads (never see an earlier point after a later one), consistent prefix reads (causal order, e.g. question before answer).
  • Multi-leader and leaderless allow concurrent writes, so conflicts occur. A database can determine whether one operation happened before another or they were concurrent, and conflicts can be resolved by merging concurrent updates.
  • Next (Chapter 6): partitioning, the counterpart of replication.
Chapter 6

Partitioning

When replication is not enough for a huge dataset or very high query throughput, the data is split into partitions (shards) spread across nodes. This chapter covers how to split data, how secondary indexes fit in, how to rebalance, and how requests find the right partition.

Key takeaways

  • Goal of partitioning: spread data and query load evenly; uneven load is skew, and an overloaded partition is a hot spot.
  • Key range partitioning keeps keys sorted, so range scans are cheap, but sequential keys (timestamps) create hot spots.
  • Hash partitioning spreads load evenly but destroys key order; Cassandra's compound key hashes only the first column and sorts by the rest.
  • Hashing cannot fix a single very hot key (a celebrity); the application must split it, e.g. by appending a random number.
  • Secondary indexes: local (document-partitioned) = cheap writes, scatter/gather reads; global (term-partitioned) = single-partition reads, multi-partition and usually asynchronous writes.
  • Never rebalance with hash mod N: changing N moves almost every key. Use a fixed number of partitions, dynamic splitting, or a fixed number per node.
  • Fully automatic rebalancing plus automatic failure detection can cause cascading failures; a human in the loop is safer.
  • Request routing is service discovery: nodes forward, a routing tier forwards, or clients route; cluster metadata often lives in ZooKeeper or spreads by gossip.

Introduction

  • A partition is called a shard (MongoDB, Elasticsearch, SolrCloud), region (HBase), tablet (Bigtable), vnode (Cassandra, Riak) or vBucket (Couchbase).
  • Usually each record belongs to exactly one partition; each partition is in effect a small database of its own.
  • Not the same as a network partition (a fault; see Chapter 8).
  • Main reason: scalability. Partitions live on different nodes of a shared-nothing cluster, spreading data over many disks and queries over many processors.
  • Single-partition queries scale by adding nodes; large queries can be parallelized across nodes, but that is much harder.
  • Pioneered in the 1980s (Teradata, Tandem NonStop SQL), rediscovered by NoSQL and Hadoop warehouses. Fundamentals apply to both transactional and analytic workloads.

Partitioning and Replication

  • Partitioning is usually combined with replication: each record is in one partition, but that partition is copied to several nodes for fault tolerance.
  • A node can hold many partitions. With leader-follower replication, each partition's leader sits on one node and its followers on others, so a node is leader for some partitions and follower for others.
  • Chapter 5's replication ideas apply unchanged per partition; the partitioning scheme is mostly independent of the replication scheme, so the chapter ignores replication.
Node 1 Node 2 Node 3 Node 4 P1 leader P3 follower P4 follower P2 leader P1 follower P4 follower P3 leader P1 follower P2 follower P4 leader P2 follower P3 follower leader follower
Figure 6-1: each node leads some partitions and follows others.

Partitioning of Key-Value Data

  • Aim: each node takes a fair share, so in theory 10 nodes handle 10x the data and 10x the read/write throughput.
  • Skew: some partitions get more data or queries. Worst case: all load on one partition, 9 of 10 nodes idle. That partition is a hot spot.
  • Random assignment spreads data evenly, but then a read cannot know where an item lives and must query every node.
  • Better: assume a key-value model accessed by primary key and derive the partition from the key.

Partitioning by Key Range

  • Each partition owns a continuous range of keys, like the volumes of a paper encyclopedia. Known boundaries tell you the partition, and the partition-to-node map tells you the node.
  • Ranges need not be even: the book's encyclopedia has volume 1 = A-B but volume 12 = T-Z. Boundaries must adapt to the data; set by an admin or chosen automatically.
  • Used by Bigtable, HBase, RethinkDB, and MongoDB before 2.4.
  • Keys stay sorted inside a partition (SSTables), so range scans are easy and the key acts as a concatenated index.
  • Example: sensor readings keyed by timestamp; fetching a month of readings is one range scan.
  • Downside: hot spots from access patterns. With timestamp keys, all of today's writes go to today's partition while others idle.
  • Fix: put the sensor name first (key = sensor name + timestamp). Writes spread across sensors, but a time-range query over many sensors needs one range query per sensor.
sorted key space, boundaries follow the data Vol 1 A - B Vol 2 C Vol 3 D - F ... Vol 11 S Vol 12 T - Z Timestamp key: Mon Tue today: HOT all writes land here Fix: key = sensor + time, writes spread by sensor
Figure 6-2 (simplified): key range partitioning, and the timestamp hot spot.

Partitioning by Hash of Key

  • To avoid skew, many stores hash the key. A good hash turns skewed input into a uniform spread (e.g. a 32-bit hash gives values 0 to 232 − 1; similar strings hash far apart).
  • Need not be cryptographic: Cassandra and MongoDB use MD5; Voldemort uses Fowler-Noll-Vo.
  • Language built-ins may be unsuitable: Java's Object.hashCode() and Ruby's Object#hash can give the same key different hashes in different processes.
  • Each partition owns a range of hashes. Boundaries may be evenly spaced or chosen pseudorandomly (then sometimes called consistent hashing).
2016-04-12 19:00 2016-04-12 19:01 2016-04-12 19:02 adjacent keys hash() P0: hash 0 .. b0 P1: hash b0 .. b1 P2: hash b1 .. max even spread, but sort order lost
Figure 6-3 (simplified): partitioning by hash of key.
  • Cost of hashing: no efficient range queries. Adjacent keys scatter over all partitions.
  • MongoDB in hash-sharding mode sends range queries to all partitions. Riak, Couchbase and Voldemort do not support range queries on the primary key.
  • Cassandra's compromise: a compound primary key. Only the first column is hashed to pick the partition; the other columns form a concatenated index for sorting in SSTables.
  • You cannot range-scan the first column, but with a fixed first column you can range-scan the rest.
  • Fits one-to-many data: key (user_id, update_timestamp) keeps one user's updates on one partition, sorted by time, while users spread across partitions.
user_id update_timestamp hashed: picks partition sorted within partition Partition for user 42 (42, 09:00) (42, 09:15) (42, 10:30) range scan over time
Cassandra compound key: hash the first column, sort by the rest.

Skewed Workloads and Relieving Hot Spots

  • Hashing cannot help if all reads and writes hit the same key: identical IDs hash identically.
  • Book's example: a celebrity with millions of followers triggers a burst of writes to one key (the user ID, or the ID of the action being commented on).
  • Most systems cannot compensate automatically, so the application must reduce skew.
  • Technique: add a random number to the start or end of a known hot key. A two-digit random number splits writes over 100 keys on different partitions.
  • Costs: reads must fetch all 100 keys and combine them; you need bookkeeping of which keys are split, and should split only the few hot ones.
hot key writes key+00 key+01 ... key+99 random suffix read: merge 100
Splitting a hot key: writes spread out, reads pay to recombine.

Partitioning and Secondary Indexes

  • Primary-key access maps cleanly to a partition. A secondary index searches for occurrences of a value (all actions by user 123, articles containing "hogwash", red cars) and does not map neatly to partitions.
  • Core to relational and document databases and the whole point of Solr and Elasticsearch. HBase and Voldemort avoided them for complexity; Riak started adding them.
  • Two approaches: document-based and term-based partitioning.
  • Hand-rolling a value-to-ID index in a key-value store is risky: races and partial write failures easily put it out of sync with the data.

Partitioning Secondary Indexes by Document

  • Example: a used-car site partitioned by document ID (IDs 0-499 in partition 0, 500-999 in partition 1), with secondary indexes on color and make.
  • Each partition keeps its own index covering only its own documents (adding a red car adds its ID to that partition's color:red entry). Called a local index.
  • Writes touch only the partition holding the document.
  • Reads: red cars can be in any partition, so a query goes to all partitions and results are combined: scatter/gather.
  • Scatter/gather is expensive and, even in parallel, prone to tail latency amplification.
  • Still widely used: MongoDB, Riak, Cassandra, Elasticsearch, SolrCloud, VoltDB.
  • Vendors advise designing so index queries hit one partition, which is often impossible, especially with several indexes in one query (color and make together).
query: color = red scatter / gather Partition 0 (IDs 0-499) primary data 191: red Honda 306: red Ford local index color:red → 191, 306 make:Honda → 191 make:Ford → 306 Partition 1 (IDs 500-999) primary data 515: silver Dodge 768: red Volvo local index color:red → 768 color:silver → 515 make:Volvo → 768
Figure 6-4 (simplified): document-partitioned (local) secondary indexes.

Partitioning Secondary Indexes by Term

  • Instead build a global index over all partitions. It cannot sit on one node (bottleneck), so it is itself partitioned, but differently from the primary key.
  • Book's example: color:red lists red cars from every partition; colors a-r live in index partition 0, s-z in partition 1; the make index splits between f and h.
  • Called term-partitioned: the term (e.g. color:red) picks the index partition. "Term" comes from full-text indexes, where terms are a document's words.
  • Partition by the term itself (supports range scans, e.g. asking price) or by its hash (more even load).
  • Reads are efficient: one request to the partition holding the term, no scatter/gather.
  • Writes are slower and complex: one document write may touch several index partitions on different nodes.
  • Keeping the index always current needs a distributed transaction across those partitions, which not all databases support (Chapters 7, 9).
  • So global index updates are often asynchronous: a read right after a write may miss it. DynamoDB says its global secondary indexes update within a fraction of a second normally, longer during infrastructure faults.
  • Also used by Riak search and the Oracle data warehouse (which offers local or global). More in Chapter 12.
Data partition 0 191: red Honda 306: red Ford Data partition 1 515: silver Dodge 768: red Volvo Index part. 0 (a-r) color:red → 191, 306, 768 make:Dodge → 515 make:Ford → 306 Index part. 1 (s-z) color:silver → 515 make:Volvo → 768 write 768 updates 2 index partitions
Figure 6-5 (simplified): term-partitioned (global) secondary index.
Document-partitioned (local)Term-partitioned (global)
Index livesWith the documents it coversPartitioned by the indexed term
WriteOne partitionPossibly many index partitions
ReadScatter/gather over all partitionsOne partition per term
FreshnessUpdated with the writeOften asynchronous
Used byMongoDB, Riak, Cassandra, Elasticsearch, SolrCloud, VoltDBDynamoDB GSIs, Riak search, Oracle DW

Rebalancing Partitions

  • Things change: throughput grows (more CPUs), data grows (more disks and RAM), machines fail (others take over). Each calls for moving data and requests between nodes: rebalancing.
  • Minimum requirements: load is shared fairly afterward; the database keeps serving reads and writes during it; no more data moves than necessary.

Strategies for Rebalancing

How not to do it: hash mod N. Why assign hash ranges instead of hash(key) mod N? Because when N changes, most keys move.

  • Book's example: hash(key) = 123456 sits on node 6 with 10 nodes, node 3 with 11, node 0 with 12. Such frequent moves make rebalancing far too expensive.
hash(key) = 123456 N = 10 node 6 N = 11 node 3 N = 12 node 0 every change of N moves most keys
hash mod N: adding one node relocates almost all data.

Fixed number of partitions. Create many more partitions than nodes, several per node (e.g. 10 nodes, 1,000 partitions, about 100 each).

  • A new node steals a few partitions from every existing node; removal reverses this.
  • Only whole partitions move. Key-to-partition mapping and partition count never change, only partition-to-node assignment.
  • Transfer takes time, so the old assignment serves reads and writes during the move.
  • Mismatched hardware: give stronger nodes more partitions.
  • Used by Riak, Elasticsearch, Couchbase, Voldemort.
  • The count is usually set at setup and never changed (splitting is often not implemented), so it caps the number of nodes. Choose it high enough for growth, but each partition has overhead.
  • Hard when dataset size varies: partition size grows with total data. Too big = expensive rebalancing and recovery; too small = too much overhead.
Before: 3 nodes, 12 partitions Node 0 p0 p3 p6 p9 Node 1 p1 p4 p7 p10 Node 2 p2 p5 p8 p11 After: node 3 joins Node 0 p0 p3 p6 Node 1 p1 p4 p7 Node 2 p2 p5 p8 Node 3 (new) p9 p10 p11 whole partitions move; key → partition never changes
Figure 6-6 (simplified): a new node steals partitions from existing nodes.

Dynamic partitioning. Fixed boundaries suit key ranges badly: wrong boundaries could put all data in one partition, and fixing them by hand is tedious.

  • HBase and RethinkDB split a partition when it exceeds a configured size (HBase default 10 GB), about half on each side; small partitions can merge with a neighbor. Similar to a B-tree's top level.
  • Nodes hold many partitions; after a split, one half can move to another node (HBase moves files via HDFS).
  • Advantage: partition count adapts to data volume. Small data, few partitions, low overhead; huge data, each partition capped at a maximum.
  • Caveat: an empty database starts with one partition, so one node takes all writes until the first split. Pre-splitting (HBase, MongoDB) configures initial partitions, but for key ranges you must know the key distribution in advance.
  • Works with hash partitioning too: MongoDB since 2.4 splits dynamically in both modes.
keys A - Z over 10 GB split A - M N - Z move other node holds N - Z shrunk partitions can merge with a neighbor
Dynamic partitioning: split on size, move one half.

Partitioning proportionally to nodes. Dynamic: partition count tracks dataset size. Fixed: partition size tracks dataset size. Both are independent of node count.

  • Cassandra and Ketama instead use a fixed number of partitions per node. Partitions grow with data, then shrink when nodes are added; since more data usually means more nodes, size stays fairly stable.
  • A joining node randomly picks a fixed number of existing partitions, splits them, and takes one half of each.
  • Randomness can split unfairly, but it averages out over many partitions (Cassandra default 256 per node). Cassandra 3.0 added an algorithm that avoids unfair splits.
  • Random boundaries require hash partitioning. This is closest to Karger's original consistent hashing; newer hash functions get a similar effect with less metadata.
StrategyPartition countPartition sizeUsed by
Fixed numberFixed at setupGrows with datasetRiak, Elasticsearch, Couchbase, Voldemort
DynamicGrows with datasetBetween min and maxHBase, RethinkDB, MongoDB
Proportional to nodesFixed per nodeFairly stableCassandra, Ketama

Operations: Automatic or Manual Rebalancing

  • A gradient from fully automatic (system moves partitions itself) to fully manual (admin configures assignment). Couchbase, Riak and Voldemort suggest an assignment automatically but need an admin to commit it.
  • Automatic is convenient but unpredictable. Rebalancing reroutes requests and moves lots of data; done carelessly it overloads the network or nodes and hurts other requests.
  • Danger with automatic failure detection: an overloaded, slow node is declared dead; the cluster moves load away from it, adding load to it, other nodes and the network, risking a cascading failure.
  • A human in the loop is slower but prevents operational surprises.

Request Routing

  • How does a client know which node (IP and port) holds key "foo", given that assignments change during rebalancing? This is service discovery, a general problem for any highly available networked software; many companies have open-sourced in-house tools.
  • Three approaches (Figure 6-7):
    1. Client contacts any node (e.g. round-robin load balancer); that node handles it or forwards to the owner and relays the reply.
    2. A routing tier receives all requests and forwards them; it handles none itself, acting as a partition-aware load balancer.
    3. Partition-aware clients connect straight to the right node.
  • Key problem: how does whoever routes learn about assignment changes? All participants must agree, or requests go to the wrong node. Consensus protocols exist but are hard to implement (Chapter 9).
1. Any node 2. Routing tier 3. Aware client client client aware client routing tier node 0 node 1 node 0 forwards node 0 node 1 node 0 node 1 direct to owner
Figure 6-7 (simplified): three ways to route a request to the right node.
  • Many systems keep cluster metadata in a coordination service such as ZooKeeper: nodes register, ZooKeeper holds the authoritative partition-to-node map, and the routing tier or clients subscribe and get notified of changes.
  • ZooKeeper users: LinkedIn's Espresso (via Helix, with a routing tier), HBase, SolrCloud, Kafka. MongoDB is similar but uses its own config servers with mongos daemons as the routing tier.
  • Cassandra and Riak use a gossip protocol among nodes; any node accepts a request and forwards it (approach 1). More complexity in the nodes, no external coordination dependency.
  • Couchbase does not rebalance automatically, simplifying things; it usually uses a routing tier, moxi, that learns changes from cluster nodes.
  • Clients still need IP addresses of the routing tier or nodes; these change slowly, so DNS is usually enough.
client routing tier ZooKeeper key range → partition → node A-ak → P0 → node 0 ak-bo → P1 → node 1 notify node 0 node 1 node 2 nodes register forward
Figure 6-8 (simplified): ZooKeeper tracks partition-to-node assignment.

Parallel Query Execution

  • So far: single-key reads and writes, plus scatter/gather for local indexes. That is about what most NoSQL stores support.
  • Massively parallel processing (MPP) relational databases, often for analytics, support far richer queries (joins, filters, grouping, aggregation).
  • The MPP optimizer breaks a query into stages and partitions, many run in parallel on different nodes. Large scans benefit most.
  • A specialized, commercially important topic; techniques covered in Chapter 10.

Summary

  • Partitioning is needed when data is too large to store and process on one machine. Goal: spread data and query load evenly and avoid hot spots, via a scheme suited to the data plus rebalancing as nodes come and go.
  • Key range partitioning: sorted keys, each partition owns min to max. Efficient range queries; hot-spot risk when accesses cluster in key order. Usually rebalanced dynamically by splitting a range in two when it grows too big.
  • Hash partitioning: each partition owns a range of hashes. Loses key order (range queries inefficient) but may spread load more evenly. Commonly a fixed number of partitions created up front, several per node, whole partitions moved on node changes; dynamic partitioning also works.
  • Hybrid: a compound key, one part picking the partition and another the sort order.
  • Secondary indexes must be partitioned too. Document-partitioned (local): stored with the primary data; one-partition writes, scatter/gather reads. Term-partitioned (global): partitioned by indexed value; writes update several index partitions, reads hit one.
  • Routing ranges from partition-aware load balancing to sophisticated parallel query engines.
  • Partitions operate mostly independently, which is what lets the database scale. Writes spanning several partitions are hard to reason about (what if one succeeds and another fails?); later chapters address this.
Chapter 7

Transactions

What safety guarantees transactions give, what they cost, and how databases implement isolation levels: read committed, snapshot isolation and serializability, on single-node and distributed databases.

Key takeaways

  • A transaction groups reads and writes into one unit that either commits or aborts; an aborted transaction can be safely retried.
  • ACID atomicity really means abortability; consistency is an application property, not a database one.
  • Most databases default to weak isolation (read committed or snapshot isolation), which leaves some race conditions to the application.
  • Read committed prevents dirty reads and dirty writes; snapshot isolation (MVCC) also prevents read skew.
  • Lost updates are fixed by atomic operations, explicit locks, automatic detection or compare-and-set; write skew and phantoms generally need serializability.
  • Serializability has three implementations: actual serial execution, two-phase locking (pessimistic, slow at high percentiles) and serializable snapshot isolation (optimistic, aborts at commit).
  • "Repeatable read" and "serializable" mean different things in different databases; check what your database actually does.

The Slippery Concept of a Transaction

Many things go wrong in data systems: database or hardware crashes mid-write, the application crashes mid-sequence, the network cuts off clients or nodes, concurrent clients overwrite each other, clients read partially updated data, and race conditions cause odd bugs.

  • For decades, transactions have been the main tool for simplifying these problems. All reads and writes in a transaction run as one logical operation: it commits or it aborts (rolls back).
  • On abort the application can retry safely, with no partial failure to reason about. The database takes care of these cases: its safety guarantees.
  • Transactions are not a law of nature. They exist to simplify the programming model. Some applications do not need them, and weakening or dropping them can buy performance or availability.
  • Almost all relational databases (MySQL, PostgreSQL, Oracle, SQL Server) follow the style of IBM System R (1975), largely unchanged for 40 years.
  • Late-2000s NoSQL databases often abandoned transactions or redefined the word to mean much weaker guarantees. The belief that transactions kill scalability, and the opposite claim that "serious" apps need them, are both hyperbole: transactions have advantages and limits like any design choice.

The Meaning of ACID

ACID = Atomicity, Consistency, Isolation, Durability (Härder and Reuter, 1983). In practice implementations differ, especially on isolation, so "ACID compliant" has become mostly a marketing term. BASE (Basically Available, Soft state, Eventual consistency) is vaguer still; it effectively means "not ACID".

Atomicity

  • In multi-threaded programming, "atomic" means no other thread sees a half-finished result. In ACID it is not about concurrency; that is the I.
  • ACID atomicity: if a fault (crash, network cut, full disk, constraint violation) stops a group of writes from committing, the transaction is aborted and the database discards every write it made.
  • Without it, the app cannot tell which changes took effect, and retrying risks duplicates. With it, an aborted transaction changed nothing, so a retry is safe.
  • The book suggests abortability would have been the better term.

Consistency

"Consistency" has at least four meanings:

  • Replica consistency and eventual consistency (Chapter 5).
  • Consistent hashing, a rebalancing approach (Chapter 6).
  • In the CAP theorem, it means linearizability (Chapter 9).
  • In ACID, an application-specific notion of the database being in a "good state".
  • ACID consistency means invariants always hold (e.g. credits and debits balance). If each transaction starts valid and preserves validity, invariants stay satisfied.
  • The application defines the invariants and writes transactions that keep them; the database cannot stop bad data. It can check some kinds (foreign key, uniqueness constraints).
  • A, I and D are database properties; C is an application property that relies on A and I. "The letter C doesn't really belong in ACID."

Isolation

  • Clients touching the same records concurrently hit race conditions. Example (Figure 7-1): two clients each read a counter, add 1 and write back. It should go 42 → 44 but ends at 43.
  • ACID isolation: concurrent transactions cannot step on each other. Textbooks formalize it as serializability: the result is the same as if transactions had run one after another.
  • In practice serializable isolation is rarely used because of its performance cost. Oracle 11g's "serializable" is actually snapshot isolation, a weaker guarantee.
Client 1 Database Client 2 read: 42 write 42+1 42 43 43 read: 42 write 42+1 time expected 44, got 43
Figure 7-1: a race between two clients incrementing a counter; one increment is lost.

Durability

  • Durability: once committed, data is not forgotten despite hardware faults or crashes.
  • Single node: written to nonvolatile storage (disk/SSD), usually with a write-ahead log for recovery. Replicated: copied to some number of nodes. The database must wait for these before reporting commit.
  • Perfect durability does not exist: if all disks and backups are destroyed together, nothing can save you.

Replication and durability. Durability once meant archive tape, then disk, now replication. Neither is perfect:

  • Disk-only: a dead machine keeps data but makes it inaccessible; replicas stay available.
  • Correlated faults (power outage, a bug that crashes every node on one input) can take out all replicas, losing in-memory data, so disk still matters for in-memory databases.
  • Asynchronous replication can lose recent writes when the leader fails.
  • SSDs can violate guarantees on sudden power loss; even fsync may not work. Disk firmware has bugs.
  • Storage engine and filesystem interactions can corrupt files after a crash.
  • Undetected gradual corruption can spread to replicas and recent backups; restore from a historical backup.
  • One study: 30%–80% of SSDs develop at least one bad block in four years. HDDs have fewer bad sectors but more complete failures.
  • An unpowered SSD can start losing data within a few weeks, depending on temperature.

Single-Object and Multi-Object Operations

  • Atomicity: all-or-nothing; an error halfway discards earlier writes.
  • Isolation: another transaction sees all or none of a transaction's writes, never a subset.
  • Both assume multi-object transactions, needed when several pieces of data must stay in sync.
  • Email example: instead of counting unread emails with a slow query, store an unread counter (denormalization). Inserting an email and incrementing the counter must happen together.
  • Figure 7-2: user 2 sees the new email but a counter of 0, because the increment has not happened yet. Isolation would show both or neither.
  • Figure 7-3: if the counter update fails, atomicity rolls back the inserted email.
  • Relational databases group a transaction by the client's TCP connection: everything between BEGIN TRANSACTION and COMMIT. (If the connection drops after the commit request but before the acknowledgment, the client does not know whether it committed; a transaction ID not tied to the connection can solve this.)
  • Many nonrelational databases cannot group operations. A multi-put API may succeed for some keys and fail for others.
User 1 User 2 insert email unread += 1 list: 1 unread counter: 0 sees email but not counter: dirty read time
Figure 7-2: violating isolation; user 2 reads user 1's uncommitted writes.
insert email unread += 1 fails abort email insert is undone one transaction
Figure 7-3: atomicity undoes prior writes when an error occurs, avoiding an inconsistent state.

Single-object writes

  • Atomicity and isolation also matter for one object. Writing a 20 KB JSON document: does an interrupted write leave a 10 KB fragment? Does a power cut splice old and new values? Does a concurrent reader see a partial value?
  • Storage engines almost always give single-object atomicity (via a crash-recovery log) and isolation (via a per-object lock) on one node.
  • Some offer an increment operation (no read-modify-write) or compare-and-set (write only if the value is unchanged). These prevent lost updates.
  • They are not transactions in the usual sense. Calling them "lightweight transactions" or "ACID" is misleading; a transaction groups operations on multiple objects.

The need for multi-object transactions

Many distributed datastores dropped multi-object transactions because they are hard across partitions and can hurt very high availability or performance. Nothing fundamentally prevents them (Chapter 9). Cases needing coordinated writes:

  • Foreign keys (or graph edges): records that refer to each other must stay valid.
  • Document databases: one document needs no multi-object transaction, but lack of joins encourages denormalization, and updating denormalized data touches several documents.
  • Secondary indexes are separate objects; without isolation a record can appear in one index but not another.

You can build such apps without transactions, but error handling gets much harder without atomicity, and missing isolation causes concurrency problems.

Handling errors and aborts

  • ACID databases would rather abandon a transaction than leave it half-finished.
  • Leaderless-replication datastores work on a best effort basis: they do not undo what is done, so recovery falls on the application.
  • ORMs such as Rails's ActiveRecord and Django do not retry aborted transactions; the exception bubbles up and user input is lost. That wastes the point of aborts: safe retries.

Retrying is simple and effective but not perfect:

  • If the commit succeeded but the acknowledgment was lost, a retry runs it twice unless the app deduplicates.
  • If the error is overload, retries make it worse. Limit retries, use exponential backoff, and treat overload errors differently.
  • Retry only transient errors (deadlock, isolation violation, network blip, failover), not permanent ones (constraint violation).
  • Side effects outside the database (e.g. sending an email) may happen even if the transaction aborts. Two-phase commit can make several systems commit or abort together.
  • If the client fails while retrying, the data it was writing is lost.

Weak Isolation Levels

  • Race conditions only arise when one transaction reads data another is modifying, or two modify the same data.
  • Concurrency bugs are timing-dependent, rare, hard to reproduce by testing and hard to reason about in large apps.
  • Serializable isolation lets you pretend there is no concurrency, but costs performance, so many systems use weaker, nonserializable levels that protect against some issues only.
  • Weak isolation bugs have caused loss of money, auditor investigations and corrupted customer data. "Use an ACID database" misses the point: many popular relational databases use weak isolation too.
  • So understand the kinds of concurrency problems and how to prevent them, rather than blindly trusting tools.

Read Committed

The most basic level. Two guarantees:

  1. No dirty reads: you only see committed data.
  2. No dirty writes: you only overwrite committed data.

(An even weaker level, read uncommitted, prevents dirty writes but not dirty reads.)

No dirty reads

  • A dirty read is seeing another transaction's uncommitted writes. Under read committed, a transaction's writes become visible only when it commits, all at once.
  • Why it matters: seeing a partial multi-object update (Figure 7-2) confuses users and can mislead other transactions; and seeing writes later rolled back (Figure 7-3) is mind-bending to reason about.
User 1 User 2 set x = 3 commit get x → 2 get x → 2 get x → 3 old value until commit time
Figure 7-4: no dirty reads; user 2 sees the new x only after user 1 commits.

No dirty writes

  • A dirty write overwrites a value written by a transaction that has not yet committed. Read committed prevents it, usually by delaying the second write until the first transaction commits or aborts.
  • Figure 7-5: Alice and Bob buy the same car. Each must update the listing and the invoice. With dirty writes, Bob wins the listing and Alice wins the invoice.
  • Read committed does not stop the counter race of Figure 7-1: the second write comes after the first commits, so it is not dirty, just wrong in another way (lost update).
Alice Bob listing: Alice invoice: Alice listing: Bob invoice: Bob Final: listing → Bob invoice → Alice later write wins each time
Figure 7-5: with dirty writes, conflicting writes from different transactions get mixed up.

Implementing read committed

  • Very popular: default in Oracle 11g, PostgreSQL, SQL Server 2012, MemSQL and others.
  • Dirty writes: row-level locks. A writer acquires the object's lock and holds it until commit or abort; other writers wait. Done automatically.
  • Dirty reads could use the same lock briefly for reads, but one long write transaction would then block many readers, hurting response time and spreading slowdowns across the app.
  • So most databases remember the old committed value and the new uncommitted value; readers get the old value until commit. (Only IBM DB2 and SQL Server with read_committed_snapshot=off use read locks.)

Snapshot Isolation and Repeatable Read

  • Read committed allows aborts, hides incomplete results and stops intermingled writes, yet still allows bugs.
  • Figure 7-6: Alice has $1,000 split as $500 in two accounts. A transfer moves $100. Reading mid-transfer she sees $500 and $400: $100 seems to vanish.
  • This is nonrepeatable read or read skew; re-reading account 1 would give $600. It is acceptable under read committed, since each value was committed when read. ("Skew" here means a timing anomaly, not a hot spot.)
Alice Transfer acct 1 → $500 acct 2 → $400 acct 1 + 100 acct 2 − 100 commit Alice's total: $500 + $400 = $900 time
Figure 7-6: read skew; Alice observes the database in an inconsistent state.

Alice can reload and see consistent balances, but some cases cannot tolerate temporary inconsistency:

  • Backups take hours while writes continue; a backup mixing old and new versions makes inconsistencies permanent on restore.
  • Analytic queries and integrity checks scan much of the database; seeing parts at different times gives nonsensical results.

Snapshot isolation is the common fix: each transaction reads a consistent snapshot of everything committed at its start, even if data later changes. It suits long read-only queries. Supported by PostgreSQL, MySQL/InnoDB, Oracle, SQL Server and others.

Implementing snapshot isolation

  • Write locks prevent dirty writes as in read committed; reads take no locks.
  • Key principle: readers never block writers, and writers never block readers.
  • The database keeps several committed versions of each object, because in-progress transactions may need different points in time: multi-version concurrency control (MVCC).
  • Read committed only needs two versions (committed and uncommitted), but MVCC engines typically use it for read committed too: a new snapshot per query, versus one snapshot per transaction for snapshot isolation.
  • PostgreSQL (Figure 7-7): each transaction gets a unique, always-increasing transaction ID (txid, 32-bit; vacuum handles overflow). Writes are tagged with the writer's txid.
  • Each row has created_by and deleted_by. Delete sets deleted_by; garbage collection removes the row once no transaction can see it.
  • An update becomes a delete plus a create. Transaction 13 deducting $100 from account 2 leaves a $500 row deleted by 13 and a $400 row created by 13.
id balance created_by deleted_by 1 $500 3 — 2 $500 5 13 2 $400 13 — txid 13: update acct 2: 500 → 400 = delete old row + create new row txid 12 reads acct 2 → sees $500 13 started later: its delete and its create are both invisible to 12
Figure 7-7: snapshot isolation using multi-version objects.

Visibility rules for observing a consistent snapshot

  1. At transaction start, list all in-progress transactions; ignore their writes even if they later commit.
  2. Ignore writes by aborted transactions.
  3. Ignore writes by transactions with a later txid, committed or not.
  4. All other writes are visible.
  • Rules apply to creation and deletion. In Figure 7-7, transaction 12 sees $500 because 13's delete and create are both invisible under rule 3.
  • Equivalently, an object is visible if its creator had committed when the reader started, and it is not deleted, or its deleter had not committed when the reader started.
  • Never updating in place, but always creating a new version, gives consistent snapshots at small overhead, even for long-running readers.

Indexes and snapshot isolation

  • Option 1: the index points to all versions and queries filter out invisible ones; garbage collection removes index entries with old versions. PostgreSQL avoids index updates when versions of an object fit on the same page.
  • Option 2 (CouchDB, Datomic, LMDB): append-only / copy-on-write B-trees. A write copies each modified page and its parents up to the root; unaffected pages stay immutable and shared.
  • Each write transaction (or batch) creates a new root, which is a consistent snapshot. No txid filtering needed, but background compaction and garbage collection are.
root v1 root v2 (new) page A (old) page B (shared) page A′ (copy) each root is a consistent snapshot; old pages await garbage collection
Append-only (copy-on-write) B-tree: a write copies the changed page and its ancestors, sharing the rest.

Repeatable read and naming confusion

  • Snapshot isolation is called serializable in Oracle and repeatable read in PostgreSQL and MySQL.
  • The SQL standard follows System R's 1975 isolation levels, before snapshot isolation existed. It defines repeatable read, which looks similar, so PostgreSQL and MySQL use that name to claim compliance.
  • The standard's definitions are ambiguous, imprecise and not implementation-independent. Implementations of repeatable read differ widely; most do not meet the research literature's formal definition; IBM DB2 uses "repeatable read" for serializability.
  • "Nobody really knows what repeatable read means."

Preventing Lost Updates

  • Read committed and snapshot isolation are mostly about what readers see under concurrent writes. Dirty writes are just one kind of write-write conflict.
  • The best known other one is the lost update: two concurrent read-modify-write cycles; the later write clobbers the earlier one.
  • Occurs when incrementing a counter or balance, making a local change to a complex value (adding to a list in a JSON document), or two users saving whole wiki pages at once.

Atomic write operations

  • Database-provided atomic updates remove the read-modify-write cycle from app code and are usually the best choice when they fit. E.g. UPDATE counters SET value = value + 1 WHERE key = 'foo'; is concurrency-safe in most relational databases.
  • MongoDB offers atomic local changes to JSON documents; Redis offers atomic changes to data structures like priority queues. Arbitrary text edits (wiki pages) do not fit.
  • Implemented with an exclusive lock on read until the update is applied (cursor stability), or by running all atomic operations on one thread.
  • ORMs make it easy to write unsafe read-modify-write cycles by accident, a source of bugs hard to find by testing.

Explicit locking

  • The application locks the objects it will update; concurrent readers wait until the cycle completes.
  • Example 7-1, a multiplayer game: a move must obey game rules that a query cannot express, so lock the piece with SELECT ... FOR UPDATE, check the move, then UPDATE its position.
  • FOR UPDATE locks every returned row. It works, but it is easy to forget a lock and create a race.
BEGIN TRANSACTION;
SELECT * FROM figures WHERE name = 'robot' AND game_id = 222 FOR UPDATE;
-- check the move is valid, then:
UPDATE figures SET position = 'c4' WHERE id = 1234;
COMMIT;

Automatically detecting lost updates

  • Alternative: let cycles run in parallel; if the transaction manager detects a lost update, abort and retry.
  • Efficient alongside snapshot isolation. PostgreSQL's repeatable read, Oracle's serializable and SQL Server's snapshot isolation detect it; MySQL/InnoDB's repeatable read does not. Some authors say that disqualifies MySQL from snapshot isolation.
  • Needs no special app code, so it is less error-prone than remembering locks or atomic operations.

Compare-and-set

  • In databases without transactions: update only if the value is unchanged since you read it; otherwise do nothing and retry.
  • Wiki example: UPDATE wiki_pages SET content = 'new content' WHERE id = 1234 AND content = 'old content'; then check whether it took effect.
  • If the WHERE clause can read from an old snapshot, this may not prevent lost updates. Check that your database's compare-and-set is safe.

Conflict resolution and replication

  • Locks and compare-and-set assume a single up-to-date copy. Multi-leader and leaderless replication allow concurrent writes replicated asynchronously, so those techniques do not apply.
  • Common approach: allow conflicting versions (siblings) and merge them afterward with app code or special data structures.
  • Commutative atomic operations (increment a counter, add to a set) work well across replicas. Riak 2.0 datatypes merge concurrent updates without losing any.
  • Last write wins (LWW) is prone to lost updates and is the default in many replicated databases.
TechniqueHow it prevents lost updatesCaveat
Atomic write operationDatabase does the read-modify-write (lock or single thread)Only for operations it supports; ORMs bypass it
Explicit lock (FOR UPDATE)App forces cycles to run sequentiallyEasy to forget a lock
Automatic detectionAbort and retry the losing transactionNot in MySQL/InnoDB repeatable read
Compare-and-setWrite only if value unchangedUnsafe if WHERE reads an old snapshot
Replicated: siblings / commutative opsMerge concurrent versionsLWW (common default) loses updates

Write Skew and Phantoms

  • Dirty writes and lost updates involve concurrent writes to the same object. Subtler conflicts exist.
  • Hospital on-call example: there must be at least one doctor on call per shift. Alice and Bob are both on call, both sick, and both click "go off call" at about the same time (Figure 7-8).
  • Each transaction checks that two or more doctors are on call. Under snapshot isolation both see 2, both remove themselves, both commit: zero doctors on call.
Alice Bob on call? → 2 set Alice off call commit on call? → 2 set Bob off call commit result: 0 doctors on call different rows updated: not a dirty write or lost update
Figure 7-8: write skew causing an application bug.

Characterizing write skew

  • Write skew is neither a dirty write nor a lost update: the transactions update different objects. Run serially, the second doctor would have been refused.
  • It generalizes lost update: two transactions read the same objects, then update some of them (possibly different ones). If they update the same object, you get a dirty write or lost update.

Options are more limited than for lost updates:

  • Atomic single-object operations do not help: several objects are involved.
  • Automatic lost-update detection does not help: PostgreSQL repeatable read, MySQL/InnoDB repeatable read, Oracle serializable and SQL Server snapshot isolation do not detect write skew. Automatic prevention needs true serializable isolation.
  • Multi-object constraints ("at least one doctor on call") are rarely built in; triggers or materialized views may work, depending on the database.
  • Without serializable isolation, the second-best option is to explicitly lock the rows the transaction depends on:
BEGIN TRANSACTION;
SELECT * FROM doctors WHERE on_call = true AND shift_id = 1234 FOR UPDATE;
UPDATE doctors SET on_call = false WHERE name = 'Alice' AND shift_id = 1234;
COMMIT;

More examples of write skew

  • Meeting room booking (Example 7-2): check for overlapping bookings for the room, then insert if none. Snapshot isolation does not stop a concurrent conflicting insert; serializable isolation is needed. (PostgreSQL range types help, but are not widely supported.)
  • Multiplayer game: the Example 7-1 lock stops two players moving the same figure, but not moving two figures to the same square or other rule violations. A unique constraint may work for some rules.
  • Claiming a username: check-then-create is unsafe under snapshot isolation; a unique constraint is a simple fix (the second insert aborts).
  • Preventing double-spending: insert a tentative spending item, sum the account, check it is positive. Two concurrent items can together push the balance negative unseen.
-- Example 7-2 (unsafe under snapshot isolation)
SELECT COUNT(*) FROM bookings WHERE room_id = 123
  AND end_time > '2015-01-01 12:00' AND start_time < '2015-01-01 13:00';
-- if zero:
INSERT INTO bookings (room_id, start_time, end_time, user_id)
  VALUES (123, '2015-01-01 12:00', '2015-01-01 13:00', 666);

Phantoms causing write skew

All examples share one pattern:

  1. A SELECT checks a requirement by searching for matching rows.
  2. The app decides, based on the result, whether to proceed.
  3. If so, it writes (INSERT/UPDATE/DELETE) and commits. The write changes the precondition: repeating step 1 would now give a different result.
  • The steps may be reordered (write, then query, then commit or abort).
  • In the doctors case, step 3 modifies rows returned in step 1, so SELECT FOR UPDATE fixes it. The other four check for the absence of rows and then add one; with no rows returned, there is nothing to lock.
  • A phantom is a write in one transaction changing the result of a search query in another. Snapshot isolation avoids phantoms in read-only queries, but in read-write transactions phantoms cause tricky write skew.

Materializing conflicts

  • Introduce lock objects artificially. Booking example: a table of rooms × time slots (say 15 minutes), pre-created e.g. for the next six months.
  • A booking transaction locks (SELECT FOR UPDATE) the relevant slot rows, then checks for overlaps and inserts. The table holds no booking data; it is purely locks.
  • Materializing conflicts turns a phantom into a lock conflict on concrete rows.
  • It is hard and error-prone, and leaks concurrency control into the data model. Use it as a last resort; serializable isolation is much preferable.

Serializability

The state of weak isolation is sad:

  • Isolation levels are hard to understand and inconsistently implemented (e.g. "repeatable read").
  • It is hard to tell from app code whether it is safe at a given level, especially in large apps.
  • No good tools detect race conditions; static analysis research has not reached practice, and nondeterministic bugs are hard to test.

Researchers' answer since the 1970s: use serializable isolation, usually regarded as the strongest level. Even with parallel execution the result equals some serial order, so if transactions are correct alone they are correct concurrently: the database prevents all race conditions. Three implementation techniques (single-node here; distributed in Chapter 9):

  • Literally executing transactions in serial order.
  • Two-phase locking, for decades the only viable option.
  • Optimistic concurrency control such as serializable snapshot isolation.

Actual Serial Execution

  • Remove concurrency: run one transaction at a time on a single thread. Isolation is serializable by definition.
  • Only around 2007 did designers decide a single-threaded loop was feasible. Two changes made it so:
    • RAM became cheap enough to keep the whole active dataset in memory, so transactions run much faster without waiting for disk.
    • OLTP transactions are usually short with few reads and writes; long analytic queries are read-only and can run on a snapshot outside the serial loop.
  • Used by VoltDB/H-Store, Redis and Datomic. Avoiding lock coordination can make it faster than concurrent systems, but throughput is capped at one CPU core, and transactions must be structured differently.

Encapsulating transactions in stored procedures

  • Early databases imagined one transaction spanning a whole user flow (e.g. an airline booking: search, choose, book seats, enter details, pay).
  • Humans are slow, so that means huge numbers of mostly idle transactions. Most OLTP apps instead commit within one HTTP request; a new request starts a new transaction.
  • Transactions still run interactively, one statement at a time, with network round trips between app and database. Serial execution would leave the database waiting most of the time, so such databases need concurrency.
  • Hence serial systems forbid interactive multi-statement transactions. The app submits the whole transaction ahead of time as a stored procedure. With data in memory, it runs very fast with no network or disk wait (Figure 7-9).
Interactive transaction Stored procedure App DB BEGIN; SELECT count = 2 UPDATE ok COMMIT network waits each step App DB call proc(args) runs all in memory result one round trip
Figure 7-9: an interactive transaction versus a stored procedure (using the on-call example).

Pros and cons of stored procedures

Part of the SQL standard (SQL/PSM) since 1999, but with a bad reputation:

  • Each vendor has its own language (Oracle PL/SQL, SQL Server T-SQL, PostgreSQL PL/pgSQL): archaic, few libraries.
  • Code in the database is harder to debug, version-control, deploy, test and monitor.
  • A database is shared by many app servers and is more performance-sensitive; one bad procedure can cause much more trouble.
  • Modern systems use general-purpose languages: VoltDB uses Java or Groovy, Datomic Java or Clojure, Redis Lua.
  • With stored procedures and in-memory data, single-threaded execution gets good throughput: no I/O waits, no concurrency-control overhead.
  • VoltDB replicates by executing the same procedure on each replica, so procedures must be deterministic (e.g. current time via special deterministic APIs).

Partitioning

  • Serial execution limits write throughput to one core on one machine; high-write apps hit a bottleneck.
  • If each transaction touches one partition only, each partition gets its own thread; give each core a partition and throughput scales linearly with cores (VoltDB supports this).
  • Cross-partition transactions need lock-step coordination across all partitions touched and are vastly slower. VoltDB reports about 1,000 cross-partition writes per second, orders of magnitude below single-partition, and not improvable by adding machines.
  • Key-value data partitions easily; data with multiple secondary indexes likely needs much cross-partition coordination.

Summary of serial execution

  • Every transaction must be small and fast: one slow one stalls everything.
  • The active dataset must fit in memory. Rarely used data can live on disk, but touching it in a transaction is very slow. (Anti-caching: abort, fetch the data asynchronously, restart the transaction.)
  • Write throughput must fit one core, or transactions must be partitioned without cross-partition coordination.
  • Cross-partition transactions are possible but hard-limited.

Two-Phase Locking (2PL)

  • For about 30 years the only widely used serializability algorithm. Sometimes called strong strict two-phase locking (SS2PL).
  • 2PL is not 2PC (two-phase commit, Chapter 9); they are completely different.
  • Readers may share an object as long as nobody writes it. Writing requires exclusive access:
    • If A has read an object and B wants to write it, B waits until A commits or aborts.
    • If A has written an object and B wants to read it, B waits. Reading an old version is not allowed.
  • Writers block readers and readers block writers, the opposite of snapshot isolation's mantra. In exchange, 2PL prevents all earlier races, including lost updates and write skew.

Implementation of two-phase locking

  • Used by serializable in MySQL (InnoDB) and SQL Server, and repeatable read in DB2.
  • Each object has a lock in shared mode or exclusive mode:
    • Read: acquire shared. Many may hold shared; wait if someone holds exclusive.
    • Write: acquire exclusive. Wait if anyone holds any lock.
    • Read then write: upgrade shared to exclusive (same as acquiring exclusive).
    • Hold every lock until commit or abort.
  • "Two-phase": phase 1 acquires locks while executing; phase 2 releases them all at the end.
  • Deadlock: A waits for B and B for A. The database detects it and aborts one; the app must retry.
locks held time phase 1: acquire phase 2: release commit Can B get lock? A holds ↓ B shared B excl. shared yes wait exclusive wait wait
2PL: locks only grow while the transaction runs and are all released at commit or abort; only shared locks coexist.

Performance of two-phase locking

  • The big downside: throughput and query response times are significantly worse than under weak isolation. Partly lock overhead, mostly reduced concurrency: any potential race makes one transaction wait.
  • Traditional databases do not limit transaction duration (built for human-paced interactive apps), so waits are unbounded; queues form on hot objects.
  • Latencies are unstable and very slow at high percentiles under contention. One slow transaction, or one that locks a lot of data, can grind the system to a halt.
  • Deadlocks happen with lock-based read committed too, but far more often under 2PL; each retried deadlock victim redoes its work.

Predicate locks

  • Serializable isolation must prevent phantoms. In the booking example, after one transaction searches a room and time window, no other may insert or update a booking for the same room and overlapping time (other rooms or times are fine).
  • A predicate lock belongs to all objects matching a search condition (e.g. room_id = 123 and the noon–1 p.m. window), not to one row.
  • Reading by condition: acquire a shared predicate lock; wait if another transaction holds an exclusive lock on any matching object.
  • Insert/update/delete: check whether the old or new value matches any existing predicate lock; if another transaction holds one, wait for it to finish.
  • Key idea: it covers objects that do not exist yet (phantoms). 2PL plus predicate locks prevents all write skew and races, making it serializable.

Index-range locks

  • Predicate locks perform badly: checking many active locks is slow. Most 2PL databases use index-range locking (next-key locking), an approximation.
  • It is safe to broaden a predicate: lock room 123 at any time, or all rooms from noon to 1 p.m. Any write matching the original also matches the broader version.
  • With an index on room_id, attach a shared lock to the index entry for room 123. With a time index, lock a range of values in it.
  • A conflicting write must update the same part of the index, hits the lock and waits. This protects against phantoms and write skew.
  • Less precise than predicate locks (may lock more than needed) but much cheaper: a good compromise.
  • With no suitable index, fall back to a shared lock on the whole table: safe, but stops all other writers.
predicate room 123, 12:00–13:00 room_id index entry 123 = room 123, any time time index range = all rooms, 12:00–13:00 broaden (safe) conflicting writer updates the same index part → waits no usable index → shared lock on the whole table
Index-range (next-key) locks approximate a predicate lock by locking a broader index entry or range.

Serializable Snapshot Isolation (SSI)

  • So far: serializability that performs badly (2PL) or does not scale (serial execution), versus weak isolation that is fast but racy.
  • Serializable snapshot isolation (SSI) gives full serializability with only a small penalty over snapshot isolation. First described in 2008 (Michael Cahill's PhD thesis).
  • Used in PostgreSQL's serializable level since 9.1, and a similar algorithm in FoundationDB (distributed). Still proving itself, but could become the new default.

Pessimistic versus optimistic concurrency control

  • 2PL is pessimistic: if anything might go wrong, wait until safe, like mutual exclusion.
  • Serial execution is pessimistic to the extreme: an exclusive lock on the whole database (or partition) per transaction, made tolerable by very fast transactions.
  • SSI is optimistic: proceed without blocking; at commit, check whether isolation was violated and abort if so. Only serializable executions commit.
  • Optimistic control is an old idea. It performs badly under high contention (many aborts), and retries add load near maximum throughput.
  • With spare capacity and low contention it tends to beat pessimistic control. Commutative atomic operations (e.g. concurrent counter increments, if the counter is not read in the same transaction) reduce contention.
  • Unlike earlier optimistic techniques, SSI reads from a consistent snapshot, and adds an algorithm to detect serialization conflicts and choose which transactions to abort.

Decisions based on an outdated premise

  • Write skew pattern: read, examine, act on the result. Under snapshot isolation the read may be out of date by commit time.
  • The transaction acts on a premise (e.g. "two doctors are on call") that may no longer be true at commit.
  • The database does not know how the app uses a query result, so it must assume a causal dependency: any change in the premise may invalidate the writes. It must detect transactions that acted on an outdated premise and abort them.
  • Two cases:
    • Reads of a stale MVCC version (an uncommitted write happened before the read).
    • Writes that affect prior reads (the write happens after the read).

Detecting stale MVCC reads

  • Figure 7-10: transaction 43 sees Alice as on_call = true because 42's change was uncommitted at snapshot time. By 43's commit, 42 has committed, so 43's premise is false.
  • The database tracks when a transaction ignores another's writes due to MVCC visibility. At commit, if any ignored write has since committed, abort.
  • Why wait until commit? A read-only transaction needs no abort (no write skew risk), and the database does not yet know whether 43 will write. Also 42 may still abort or be uncommitted. Avoiding unneeded aborts keeps snapshot isolation's support for long-running reads.
Tx 42 Tx 43 on call? → 2 Alice off call commit ✓ on call? → 2 (stale) Bob off call abort ✗ uncommitted write ignored now committed at commit, 43 checks: has an ignored write committed? yes → abort time
Figure 7-10: detecting when a transaction reads outdated values from an MVCC snapshot.

Detecting writes that affect prior reads

  • Case 2: another transaction modifies data after it was read (Figure 7-11).
  • Like index-range locks, but SSI locks do not block. Both 42 and 43 search on-call doctors for shift 1234; the index entry for shift_id = 1234 records that they read it (or the table, if no index).
  • This record is kept only until the transaction and all concurrent ones have finished.
  • A writer looks in the index for recent readers of the affected data. The lock acts as a tripwire: it notifies readers that their read may be outdated, rather than blocking.
  • 43 notifies 42 and vice versa. 42 commits first and succeeds (43's write has not taken effect). When 43 commits, 42's conflicting write is committed, so 43 aborts.
index: shift_id = 1234 read by: 42, 43 Tx 42 Tx 43 read shift write Alice commit ✓ read shift write Bob commit → abort writes trip the wire: notify other reader
Figure 7-11: SSI detects when one transaction modifies another transaction's reads.

Performance of serializable snapshot isolation

  • Tracking granularity is a trade-off: detailed tracking aborts precisely but costs bookkeeping; coarse tracking is faster but aborts more than necessary.
  • Reading overwritten data is sometimes provably still serializable; PostgreSQL uses this theory to cut unnecessary aborts.
  • Versus 2PL: no blocking on other transactions' locks; writers do not block readers and vice versa, so latency is more predictable. Read-only queries need no locks, good for read-heavy workloads.
  • Versus serial execution: not limited to one core. FoundationDB distributes conflict detection across machines for very high throughput, with serializable multi-partition reads and writes.
  • Abort rate drives overall performance. Long read-write transactions likely conflict and abort, so read-write transactions should be short (long read-only ones may be fine). SSI is probably less sensitive to slow transactions than 2PL or serial execution.
ApproachStyleStrengthLimit
Actual serial executionPessimistic (extreme)Simple; no lock overheadOne core per partition; in-memory; short transactions; ~1,000 cross-partition writes/s in VoltDB
Two-phase lockingPessimisticPrevents all races (with predicate / index-range locks)Readers and writers block; unstable high-percentile latency; deadlocks
Serializable snapshot isolationOptimisticNo blocking; scales across machines (FoundationDB)Aborts under high contention; read-write transactions must be short

Summary

  • Transactions are an abstraction that lets apps pretend some concurrency problems and hardware/software faults do not exist; many errors reduce to an abort and a retry.
  • Apps with very simple access patterns (one record) can probably do without; for complex patterns, transactions greatly reduce the error cases to think about.
  • Without them, crashes, network cuts, power loss, full disks and unexpected concurrency make data inconsistent (e.g. denormalized data out of sync), and complex interactions become very hard to reason about.

Race conditions that characterize isolation levels:

  • Dirty reads: reading uncommitted writes. Prevented by read committed and stronger.
  • Dirty writes: overwriting uncommitted writes. Prevented by almost all implementations.
  • Read skew (nonrepeatable reads): seeing parts of the database at different times. Usually prevented by snapshot isolation via MVCC.
  • Lost updates: concurrent read-modify-write cycles clobber each other. Some snapshot isolation implementations prevent it automatically; others need SELECT FOR UPDATE.
  • Write skew: a decision based on a read whose premise is false by write time. Only serializable isolation prevents it.
  • Phantom reads: another write changes a search's results. Snapshot isolation prevents simple phantom reads; phantoms in write skew need e.g. index-range locks.
AnomalyRead committedSnapshot isolationSerializable
Dirty readpreventedpreventedprevented
Dirty writepreventedpreventedprevented
Read skewpossiblepreventedprevented
Lost updatepossibledepends on implementationprevented
Write skew / phantoms in write skewpossiblepossibleprevented
  • Weak levels leave some anomalies to the developer (e.g. explicit locks); only serializable isolation protects against all.
  • Serial execution: simple and effective if transactions are very fast and throughput fits one core.
  • Two-phase locking: the standard for decades, but many apps avoid it for performance reasons.
  • SSI: a fairly new optimistic algorithm that avoids most downsides; transactions proceed without blocking and are checked and aborted at commit if not serializable.
  • Examples used the relational model, but transactions are valuable in any data model. Distributed transactions bring new challenges (next two chapters).
Chapter 8

The Trouble with Distributed Systems

A deliberately pessimistic tour of what goes wrong once software spans machines: unreliable networks, unreliable clocks and process pauses. It then covers how to reason about knowledge and truth when no node can be sure of anything.

Key takeaways

  • Partial failure (some parts broken, others fine, nondeterministically) is the defining trait of distributed systems.
  • In an asynchronous network, a missing reply is ambiguous: request lost, node dead or slow, or reply lost. A timeout is the only practical detector, and it cannot tell these apart.
  • Network delays are unbounded because packet switching with queueing trades predictability for utilization. No timeout value is "correct"; measure it, or adapt it (Phi Accrual).
  • Use monotonic clocks for durations. Time-of-day clocks drift, jump and carry an unknown error, so they are dangerous for ordering events (LWW silently drops writes).
  • A clock reading is really a confidence interval; Spanner's TrueTime exposes it and waits it out to order transactions.
  • Any process can pause for seconds or minutes (GC, VM suspend, swapping) without noticing. Leases checked against clocks are therefore unsafe on their own.
  • A node cannot trust its own judgment: decisions go to a majority quorum, and resources must reject stale lock holders using fencing tokens.
  • Reason with a system model (usually partially synchronous plus crash-recovery). Safety properties must always hold; liveness may carry caveats.

Faults and Partial Failures

Earlier chapters (failover, replication lag, weak isolation) were still too optimistic. This chapter assumes that anything that can go wrong will go wrong.

  • A single computer with good software is deterministic: it either works or fails totally (kernel panic). It is designed this way, preferring a crash to a wrong result, and it presents an idealized model of perfect computation.
  • Across a network that idealization is gone. Physical reality intrudes: switch failures, power failures for racks or whole datacenters, long-lived partitions, and even a truck driven into a datacenter's cooling system.
  • Partial failure: some parts are broken in unpredictable ways while others work. Partial failures are nondeterministic. An operation over several nodes may sometimes work and sometimes fail, and you may not even know whether it succeeded.
Single computer Works or Crashed deterministic, all-or-nothing Distributed system OK Down OK Slow? OK partial, nondeterministic
One machine fails as a whole; a distributed system fails in parts, unpredictably.

Cloud Computing and Supercomputing

  • High-performance computing (HPC): supercomputers with thousands of CPUs for scientific jobs such as weather forecasting. Cloud computing: multi-tenant datacenters, commodity machines on IP/Ethernet, elastic allocation, metered billing. Enterprise datacenters sit in between.
  • Supercomputers checkpoint state. When a node fails they stop the whole workload and restart from the last checkpoint. Partial failure escalates to total failure, like a single machine.

Internet services differ from supercomputers:

  • They are online and need low latency at all times, so stopping the cluster for repair is unacceptable. Batch jobs can be restarted cheaply.
  • Supercomputer nodes are specialized and reliable, talking over shared memory and RDMA. Cloud nodes are commodity machines: cheaper for the same performance, but with higher failure rates.
  • Datacenter networks use IP/Ethernet in Clos topologies for high bisection bandwidth. HPC uses meshes and toruses suited to known communication patterns.
  • With thousands of nodes, something is always broken. If the strategy is to give up on any fault, a large system spends much of its time recovering.
  • Tolerating failed nodes enables rolling upgrades, and in the cloud you can simply replace a badly performing VM.
  • Geo-distributed deployments talk over the slow, unreliable internet. Supercomputers assume their nodes are close together.

So we must accept partial failure and build fault tolerance into the software: a reliable system from unreliable components. Even a small system eventually hits faults, so fault handling is part of the design. Test unlikely faults deliberately; suspicion, pessimism and paranoia pay off.

Building a Reliable System from Unreliable Components

  • A system is not limited to the reliability of its weakest part. Error-correcting codes carry data accurately over a channel that flips bits. TCP over unreliable IP retransmits lost packets, removes duplicates and restores order.
  • There is always a limit. Codes fail when interference swamps the signal, and TCP cannot remove network delay.
  • The higher layer is still useful: it handles tricky low-level faults, so the remaining faults are easier to reason about.
TCP (more reliable) retransmit, dedupe, reorder IP (unreliable) drop, delay, duplicate, reorder delay still leaks up
A reliable layer on an unreliable base hides some faults, but not all (TCP cannot remove delay).

Unreliable Networks

The book focuses on shared-nothing systems. Each machine has its own memory and disk, and the network is the only channel. This is the dominant approach because it needs no special hardware, can use commodity cloud services, and gains reliability through redundancy across datacenters.

The internet and most datacenter networks are asynchronous packet networks. There is no guarantee when a packet arrives, or whether it arrives at all. When a request gets no response:

  1. The request was lost (for example, an unplugged cable).
  2. The request is waiting in a queue (the network or recipient is overloaded).
  3. The remote node failed (crashed or powered down).
  4. The remote node is temporarily unresponsive (for example, a long GC pause).
  5. The node processed it, but the response was lost (for example, a misconfigured switch).
  6. The node processed it, but the response is delayed.
(a) request lost (b) node down (c) response lost Client Node X Client Node X Client Node X Client sees the same thing in all three: no response yet
Figure 8-1, simplified: without a response you cannot tell which failure happened.
  • The sender cannot even tell whether a packet was delivered. Only a response says so, and that response can also be lost or delayed.
  • The usual remedy is a timeout. When it fires you still do not know whether the node got the request, and a queued request may still be delivered after you gave up.

Network Faults in Practice

  • Network problems are surprisingly common, even inside one company's datacenter. One study of a medium-sized datacenter found about 12 network faults per month: half disconnected a single machine, half a whole rack.
  • Another study found that redundant networking gear helps less than hoped, because it does not guard against human error (misconfigured switches), a major cause of outages.
  • Public clouds such as EC2 have frequent transient glitches. Other examples: a switch software upgrade causing a topology reconfiguration that delayed packets for over a minute, sharks biting undersea cables, and a NIC that dropped all inbound packets while outbound ones still worked. A link working in one direction says nothing about the other.
  • Network partition / netsplit: one part of the network cut off from the rest. The book says network fault to avoid confusion with storage partitions (shards).
  • Untested fault handling can do arbitrarily bad things: a cluster that deadlocks permanently even after the network recovers, or one that deletes all your data.
  • Handling faults need not mean tolerating them. Showing users an error during network trouble can be valid, but you must know how the software reacts and make sure it recovers. Deliberately trigger faults to test this (the idea behind Chaos Monkey).

Detecting Faults

Load balancers must take dead nodes out of rotation. Single-leader databases must promote a follower when the leader fails. Sometimes you get explicit feedback:

  • The machine is reachable but no process listens on the port: the OS refuses the connection with a RST or FIN. If the node crashed mid-request, though, you cannot know how much was processed.
  • The process crashed but the OS is alive: a script can notify other nodes so one takes over without waiting for a timeout (HBase does this).
  • With access to the datacenter switches' management interface, you can query link failures at the hardware level. This is not possible over the internet, in shared datacenters, or when the interface itself is unreachable.
  • A router sure that an IP is unreachable may send ICMP Destination Unreachable, but it has no special detection powers either.
  • Rapid feedback is useful but cannot be counted on. A TCP ack does not mean the application handled the packet; certainty requires a positive response from the application.
  • In general assume you get no response at all: retry a few times (TCP retries transparently; you may also retry at the application level), wait for a timeout, then declare the node dead.

Timeouts and Unbounded Delays

Long timeoutShort timeout
DetectionSlow: users wait or see errors meanwhileFast
RiskLow risk of false deathDeclares nodes dead during a mere load spike
  • Declaring a live node dead prematurely risks doing an action twice (for example, sending an email) when another node takes over.
  • Moving a "dead" node's responsibilities adds load to other nodes and the network. If the node was only overloaded, this can cause a cascading failure, in the extreme with every node declaring the others dead.
  • Thought experiment: if every packet arrived within d or was lost, and a live node always handled a request within r, then 2d + r would be a sound timeout.
  • Real systems have neither guarantee. Asynchronous networks have unbounded delays, and most servers cannot bound handling time. Being fast most of the time is not enough: with a low timeout, one transient spike in round-trip times throws the system off balance.
Client Server ≤ d ≤ r ≤ d timeout = 2d + r Only valid if d and r are bounded; real networks and servers bound neither
With bounded delays, 2d + r would be a safe timeout. Asynchronous networks give no such bound.

Network congestion and queueing. Packet delay varies mostly because of queueing, much as road travel time varies with traffic:

  • When several nodes send to one destination, the switch queues the packets and feeds them onto the link one by one: network congestion. If the queue fills, packets are dropped and must be resent, even though the network works.
  • At the destination, if all CPU cores are busy, the OS queues the request until the application is ready, which can take arbitrarily long.
  • In VMs, the OS is often paused for tens of milliseconds while another VM uses the core. The hypervisor buffers incoming data meanwhile.
  • TCP flow control (congestion avoidance, backpressure) limits the sender's own rate, adding queueing before data even enters the network.
  • TCP treats an unacknowledged packet as lost after a timeout computed from observed round-trip times, then retransmits. The application never sees the loss, only the delay.
Port 1 Port 2 Port 4 Switch queue for port 3 Port 3 full queue: drop
Figure 8-2, simplified: several senders to one destination fill its switch queue.
  • Queueing delay is widest near maximum capacity: spare capacity drains queues, while high utilization builds long queues quickly.
  • In public clouds and multi-tenant datacenters, links, switches, NICs and CPUs are shared. Batch jobs such as MapReduce can saturate links, and a noisy neighbor makes delays highly variable.
  • So choose timeouts experimentally: measure the round-trip distribution over a long period and many machines, then trade detection delay against premature timeouts.
  • Better still, adapt continually to observed response times and jitter. The Phi Accrual failure detector does this (used in Akka and Cassandra), and TCP retransmission timeouts work similarly.

Synchronous Versus Asynchronous Networks

Why not make the network reliable in hardware? Compare it with the fixed-line telephone network, where delayed audio and dropped calls are very rare.

  • A phone call sets up a circuit: a fixed, guaranteed bandwidth along the whole route for the call's duration. Example: ISDN runs at 4,000 frames per second, and a call gets 16 bits per frame in each direction, so it is guaranteed 16 bits every 250 microseconds.
  • This is a synchronous network. Space is already reserved at each hop, so there is no queueing, and maximum end-to-end latency is fixed: bounded delay.

Can we not simply make network delays predictable?

  • A circuit is reserved bandwidth that nobody else can use. A TCP connection opportunistically uses whatever bandwidth is available and uses none while idle.
  • Ethernet and IP are packet-switched, with no concept of a circuit, so they suffer queueing and unbounded delay.
  • Packet switching is optimized for bursty traffic. Web pages, email and file transfers have no fixed bandwidth need; they just want to finish fast. With a circuit you would have to guess a bandwidth: too low wastes capacity and is slow, too high and the circuit cannot be set up. TCP adapts its rate to available capacity.
  • Hybrids exist. ATM supported both, and InfiniBand has link-layer end-to-end flow control (it can still see link congestion). QoS (prioritization and scheduling) plus admission control (rate-limiting senders) can emulate circuits or give statistically bounded delay.
Circuit (static) Packet (dynamic) call A idle idle idle each slot reserved, even if unused senders jostle for the wire bounded delay low utilization expensive queueing, unbounded delay high utilization cheap
Static partitioning buys bounded latency with wasted capacity; dynamic sharing buys utilization with variable delay.

Latency and Resource Utilization. Variable delay is a consequence of dynamic resource partitioning.

  • A wire between telephone switches carries up to 10,000 calls. It is divided statically: a lone call gets the same fixed slot even when the other 9,999 are unused.
  • The internet shares bandwidth dynamically, and switches pick which packet goes next moment by moment. The cost is queueing; the gain is maximum utilization, which makes each byte cheaper.
  • CPUs are the same: sharing a core between threads means waiting in the run queue, but it uses hardware better than fixed cycle allocations. Better utilization is also a big motivation for VMs.
  • Latency guarantees are possible with static partitioning (dedicated hardware, exclusive bandwidth) but cost more. Multi-tenancy with dynamic partitioning is cheaper but has variable delay.
  • Variable delay is a cost/benefit trade-off, not a law of nature. QoS is not enabled in multi-tenant datacenters, public clouds or the internet, so assume congestion, queueing and unbounded delay. There is no "correct" timeout; determine it experimentally.

Unreliable Clocks

Applications use clocks for durations (has this request timed out? p99 response time? queries per second over five minutes? time a user spent on the site?) and for points in time (when was the article published? when to send the reminder? when does the cache entry expire? log timestamps).

  • Messages take a variable time to travel, so it is hard to order events across machines.
  • Each machine's clock is a hardware device, usually a quartz crystal oscillator, and runs slightly fast or slow.
  • NTP (Network Time Protocol) adjusts clocks to time reported by a group of servers, which in turn get time from a more accurate source such as GPS.

Monotonic Versus Time-of-Day Clocks

Time-of-day clockMonotonic clock
ReturnsDate and time on a calendar (wall-clock time): seconds since the epoch (midnight UTC, 1 Jan 1970), ignoring leap secondsAn arbitrary counter (for example, nanoseconds since boot); only differences mean anything
APIsclock_gettime(CLOCK_REALTIME), System.currentTimeMillis()clock_gettime(CLOCK_MONOTONIC), System.nanoTime()
NTP effectSynced, so timestamps are (ideally) comparable across machines; can be forcibly reset and jump backwardNTP may slew the rate (default up to 0.05%) but never makes it jump
ResolutionHistorically coarse (10 ms steps on older Windows)Usually microseconds or better
Use forPoints in timeDurations and timeouts; never compare across machines
  • Jumps and ignored leap seconds make time-of-day clocks unsuitable for measuring elapsed time.
  • Multi-socket servers may have a timer per CPU. The OS tries to present a monotonic view, but take that guarantee with a pinch of salt.
  • Monotonic clocks are usually fine for timeouts in a distributed system, because they assume no cross-node synchronization.
real time clock value NTP reset: jumps back time-of-day monotonic rate slewed, never jumps
Time-of-day clocks may jump backward; monotonic clocks only move forward.

Clock Synchronization and Accuracy

Time-of-day clocks need NTP or another external source, and both hardware clocks and NTP are fickle:

  • Quartz drifts, varying with temperature. Google assumes 200 ppm: 6 ms drift if resynced every 30 s, 17 s if resynced once a day.
  • If a clock is too far from the NTP server, the client may refuse to sync, or the clock is forcibly reset and applications see time jump.
  • A node accidentally firewalled from NTP can go unnoticed for some time.
  • NTP is only as good as the network delay. Over the internet, a minimum error of 35 ms was achieved, with spikes to about a second; large delays can make the client give up.
  • Some NTP servers are wrong by hours. Clients query several servers and ignore outliers, but you are still betting correctness on a stranger's word.
  • Leap seconds make a 59- or 61-second minute and have crashed many large systems. Smearing (servers applying the adjustment gradually over a day) may be the best fix, though server behavior varies.
  • In VMs the clock is virtualized. While another VM uses the core, a VM pauses for tens of milliseconds, which looks like the clock jumping forward.
  • On devices you do not control (mobile, embedded), the clock cannot be trusted at all; users set wrong dates, for example to cheat time limits in games.
  • High accuracy is possible with enough investment. Draft MiFID II regulation requires high-frequency trading funds to be within 100 microseconds of UTC, to debug "flash crashes" and detect manipulation. This takes GPS receivers, PTP (Precision Time Protocol), careful deployment and monitoring.
  • A misconfigured NTP daemon or blocked NTP traffic lets drift error grow quickly.

Relying on Synchronized Clocks

  • Clocks look simple but have pitfalls: a day may not have 86,400 seconds, time-of-day clocks can move backward, and nodes can disagree widely. As with networks, robust software must be prepared for incorrect clocks.
  • Bad clocks go unnoticed. A bad CPU or network fails loudly, but a drifting clock lets most things keep working, so the likely result is silent, subtle data loss rather than a crash.
  • If software needs synchronized clocks, monitor clock offsets between all machines and declare dead (remove) any node that drifts too far.

Timestamps for ordering events. Figure 8-3 uses a multi-leader database. Client A writes x = 1 on node 1, which replicates to node 3. Client B increments x on node 3 (x = 2). Both writes then replicate to node 2. Each write is tagged with the origin node's time-of-day clock, and the skew is under 3 ms, better than you can expect in practice.

Node 1 Node 3 Node 2 A: x = 1 ts 42.004 B: x += 1 (x = 2) ts 42.003 LWW keeps 42.004: x = 1 B's increment lost
Figure 8-3, simplified: B's write is causally later but gets an earlier timestamp, so LWW drops it.
  • Node 2 sees x = 1 at 42.004 and x = 2 at 42.003, wrongly keeps x = 1, and drops B's increment.
  • This strategy is last write wins (LWW), widely used in multi-leader and leaderless databases such as Cassandra and Riak. Generating timestamps on the client instead does not fix it:
  1. Writes disappear: a node with a lagging clock cannot overwrite values from a fast-clock node until the skew has elapsed. Arbitrary amounts of data are dropped silently, with no error to the application.
  2. LWW cannot tell sequential writes in quick succession from truly concurrent ones. Causality tracking such as version vectors is needed.
  3. Two nodes can produce the same timestamp (especially at millisecond resolution). A tiebreaker such as a large random number is needed, and it can also violate causality.
  • "Most recent" depends on a local clock that may be wrong. Even with tight NTP, a packet sent at 100 ms (sender clock) can arrive at 99 ms (receiver clock), as if it arrived before it was sent.
  • NTP cannot be made accurate enough to prevent this: its accuracy is limited by network round-trip time, and correct ordering would need a clock much more accurate than the network delay being measured.
  • Logical clocks, based on incrementing counters, are a safer way to order events. They capture only relative order, not time. Time-of-day and monotonic clocks are physical clocks.

Clock readings have a confidence interval.

  • Microsecond or nanosecond resolution does not mean that accuracy. Quartz drift is easily several milliseconds even when syncing with a local NTP server every minute. Over the public internet, the best is probably tens of milliseconds, spiking past 100 ms under congestion.
  • So treat a reading as a range: for example, 95% confident the time is between 10.3 and 10.5 seconds past the minute. At ±100 ms the microsecond digits mean nothing.
  • Uncertainty can be computed. A local GPS or atomic (caesium) clock reports its error range. From a server, it is drift since the last sync, plus the server's uncertainty, plus the round-trip time.
  • Most APIs hide it: clock_gettime() does not say whether the error is five milliseconds or five years.
  • Exception: Google's TrueTime API in Spanner returns [earliest, latest]. The width depends partly on time since the last sync with an accurate source.

Synchronized clocks for global snapshots.

  • Snapshot isolation usually needs a monotonically increasing transaction ID: writes with a higher ID than the snapshot are invisible to it. On one node a counter suffices.
  • Across many machines and datacenters, a global ID needs coordination and must reflect causality (if B reads A's write, B's ID must be higher). With many small, fast transactions it becomes an untenable bottleneck. Generators like Twitter's Snowflake hand out blocks of IDs, but cannot guarantee causal order.
  • Could synchronized timestamps serve as IDs? Only if accuracy were known. Spanner does this with TrueTime: if intervals A and B do not overlap (A_latest < B_earliest), B definitely happened after A. Overlap means the order is unknown.
  • Spanner waits out the confidence interval before committing a read-write transaction, so any later reader's interval cannot overlap. To keep the wait short, Google puts a GPS receiver or atomic clock in each datacenter, giving sync within about 7 ms.
  • Clock-based transaction semantics are active research and not yet in mainstream databases outside Google.
time No overlap: B after A, certain A [earliest, latest] B [earliest, latest] Overlap: order unknown A B Spanner commit wait wait interval width (~7 ms)
TrueTime intervals: only non-overlapping intervals prove order, so Spanner waits until they cannot overlap.

Process Pauses

A single-leader-per-partition database must know whether a node is still leader. One option is a lease from the other nodes: a lock with a timeout, held by one node at a time and renewed periodically. If the holder fails, it stops renewing and another node takes over at expiry. The book's request loop:

while (true) {
    request = getIncomingRequest();
    // Ensure that the lease always has at least 10 seconds remaining
    if (lease.expiryTimeMillis - System.currentTimeMillis() < 10000) {
        lease = lease.renew();
    }
    if (lease.isValid()) {
        process(request);
    }
}
  • Problem 1: it compares an expiry set by another machine (for example, now + 30 s) with the local clock, so a few seconds of skew breaks it.
  • Problem 2: even with a local monotonic clock, it assumes little time passes between checking and process(request). If the thread pauses 15 seconds around lease.isValid(), the lease expires, another node becomes leader, and this thread processes the request unsafely without noticing until the next loop iteration.
Old leader lease valid paused 15 s (GC, VM...) lease expires process(request) New leader takes over, accepts writes
A pause between checking the lease and acting on it lets two nodes act as leader.

Pauses this long really happen:

  • Stop-the-world GC (for example, in the JVM) has lasted several minutes. Even "concurrent" collectors like HotSpot's CMS stop the world sometimes. Tuning helps, but robust guarantees must assume the worst.
  • VM suspend/resume can happen at any point for any length, including live migration, where pause length depends on how fast processes write memory.
  • Laptops and other end-user devices get suspended, for example when the lid closes.
  • OS context switches and hypervisor switches. CPU time taken by other VMs is steal time; under heavy load the paused thread may wait a while to run again.
  • Synchronous disk I/O, which can be hidden (the Java classloader lazily loading class files). I/O and GC pauses can combine. On network block devices such as Amazon's EBS, I/O also suffers network delay variability.
  • Swapping/paging: a memory access can page-fault to disk. Under pressure the OS may thrash, so paging is often disabled on servers (better to kill a process than to thrash).
  • SIGSTOP (Ctrl-Z) halts a process until SIGCONT, and an operations engineer might send it by accident.
  • All of these preempt a thread at any point without it noticing, like thread-safety problems on one machine. But mutexes, semaphores, atomic counters, lock-free structures and blocking queues do not translate: a distributed system has no shared memory, only messages over an unreliable network.
  • A node must assume it can be paused at any point, even mid-function. Meanwhile others may declare it dead, and it resumes without knowing it slept.

Response time guarantees.

  • Pause causes can be eliminated with enough effort. Hard real-time systems (aircraft, rockets, robots, cars) have deadlines whose violation can fail the whole system. You do not want an airbag delayed by a GC pause.
  • In embedded systems, "real-time" means designed and tested to meet timing guarantees in all circumstances. On the web it vaguely means pushing data or stream processing without hard constraints.
  • Real-time needs the whole stack: an RTOS with guaranteed CPU allocation, libraries with documented worst-case execution times, restricted or disallowed dynamic allocation (real-time GCs exist, but must not get too much work), and enormous testing.
  • This is very expensive and restricts languages and tools, so it is mostly used in safety-critical embedded devices. Real-time is not high-performance; throughput may be lower because timeliness comes first.
  • For most server-side systems real-time guarantees are not economical, so they live with pauses and clock instability.

Limiting the impact of garbage collection. Runtimes can track allocation rate and free memory, which gives them some flexibility over when to collect.

  • Treat GC as a brief planned outage. When the runtime warns of an upcoming pause, stop sending the node new requests, let it drain, then collect while it is idle. This hides pauses from clients and cuts high-percentile latency. Some latency-sensitive financial trading systems do this.
  • Variant: GC only short-lived objects (fast to collect) and restart processes periodically before long-lived objects need a full GC, one node at a time with traffic shifted away, like a rolling upgrade.
  • These reduce the impact of GC pauses but cannot fully prevent them.

Knowledge, Truth, and Lies

  • With no shared memory, an unreliable network, partial failures, unreliable clocks and pauses, a node cannot know anything for sure. It can only guess from the messages it receives, or does not receive. Network and node problems cannot be reliably distinguished.
  • We do not need to settle the philosophy. State the assumptions as a system model, design the system to meet them, and prove algorithms correct within that model. Reliable behavior is achievable even when the model guarantees little, though it is not straightforward.

The Truth Is Defined by the Majority

  • Asymmetric fault: a node receives everything, but its outgoing messages are dropped. The others time out and declare it dead while it is working fine ("I'm not dead!"), and nobody hears it.
  • A milder case: the node notices its messages are not acknowledged and realizes there is a network fault, but it still cannot stop being declared dead.
  • A GC case: a one-minute stop-the-world pause gets the node declared dead. It then resumes as if nothing happened, unaware that a minute has passed.
  • Moral: a node cannot trust its own judgment, and the system cannot rely on any single node. Algorithms use a quorum: decisions need a minimum number of votes, including the decision that a node is dead. A node declared dead by a quorum must step down.
  • Usually the quorum is an absolute majority (more than half). Three nodes tolerate one failure; five tolerate two. It is safe because there can be only one majority at a time, so two majorities cannot make conflicting decisions.
Majority (3 of 5): decision stands N1 N2 N3 N4 N5 "dead": steps down minority
A majority decides, even against a node that feels alive; only one majority can exist at a time.

The leader and the lock. Systems often need exactly one of something: one leader per partition (to avoid split brain), one holder of a lock on a resource (to avoid corrupting concurrent writes), one owner of a username.

  • A node believing it is "the chosen one" does not mean a quorum agrees. It may have been declared dead (network interruption, GC pause) and replaced.
  • If it keeps acting in that role and others believe it, the whole system can do the wrong thing.
  • Figure 8-4 shows a real bug HBase used to have. A storage file must be written by one client at a time, so a client gets a lease from a lock service first. Client 1 pauses and its lease expires. Client 2 gets the lease and writes. Client 1 resumes, still believes its lease is valid, and writes too, corrupting the file.
Client 1 Lock svc Client 2 Storage lease GC pause lease expires lease write write (stale) file corrupted
Figure 8-4, simplified: a client that wakes from a pause still thinks its expired lease is valid.

Fencing tokens. A node falsely believing it is the chosen one must not be able to disrupt the system. Fencing does this:

  • Each time the lock service grants a lock or lease, it returns a fencing token, a number that increases with every grant. Every write to storage must carry the client's current token.
  • Figure 8-5: client 1 gets token 33 and pauses, and its lease expires. Client 2 gets 34 and writes with it. Client 1 wakes and writes with 33. Storage has already processed 34, so it rejects 33.
  • With ZooKeeper as the lock service, the transaction ID zxid or node version cversion works as a token, since both are guaranteed to increase monotonically.
  • The resource must check tokens itself; clients checking their own lock status is not enough. If the resource lacks support, work around it (for example, put the token in the filename), but some check is required.
  • Server-side checking is a good thing: a service should not assume its clients behave well, because clients are often run by people with different priorities. It should protect itself from accidentally abusive clients.
Client 1 Lock svc Client 2 Storage token 33 pause token 34 write, 34 accepted write, 33 rejected: 33 < 34
Figure 8-5, simplified: storage accepts writes only in increasing token order, fencing off the stale client.

Byzantine Faults

  • Fencing catches nodes that err inadvertently. A node that wanted to subvert the system could just send a fake token.
  • The book assumes nodes are unreliable but honest: slow, unresponsive or outdated, but if they respond, they follow the protocol to the best of their knowledge.
  • A Byzantine fault is a node that "lies" with arbitrary faulty or corrupted responses (for example, claiming a message it never got). Reaching consensus in this setting is the Byzantine Generals Problem.
  • It generalizes the Two Generals Problem: two generals agreeing on a plan by messengers that can be delayed or lost. In the Byzantine version, n generals include unknown traitors who send false messages. (The name means "excessively complicated, devious", not anything about real Byzantine generals.)
  • Byzantine fault-tolerant: works correctly even if some nodes malfunction or attackers interfere with the network. This matters in:
    • Aerospace, where radiation can corrupt memory or CPU registers and failure is catastrophic, so flight control must tolerate Byzantine faults.
    • Multi-organization systems, where participants may cheat. Peer-to-peer networks like Bitcoin and other blockchains let mutually untrusting parties agree on transactions without a central authority.
  • In the book's systems, assume no Byzantine faults. Your organization controls the datacenter nodes, and radiation is low. BFT protocols are complicated, fault-tolerant embedded systems need hardware support, and the cost is impractical for most server-side data systems.
  • Web apps must expect malicious clients (browsers), hence input validation, sanitization and output escaping against SQL injection and XSS. The server is simply the authority, with no BFT protocol. BFT matters more in peer-to-peer networks, which have no such authority.
  • BFT does not help against bugs if every node runs the same software. Most BFT algorithms need a supermajority of more than two-thirds working (with 4 nodes, at most 1 may fail), so you would need four independent implementations.
  • It does not stop attackers either: compromise one node and you can likely compromise all of them. Authentication, access control, encryption and firewalls remain the main defenses.

Weak forms of lying. It is still worth guarding cheaply against invalid messages from hardware issues, bugs and misconfiguration (this is not full BFT):

  • Packets get corrupted. TCP/UDP checksums usually catch it but sometimes miss, so add application-level checksums.
  • Sanitize inputs in public apps: check value ranges, and limit string sizes to prevent denial of service through large allocations. Internal services should still sanity-check values (for example, in protocol parsing).
  • Configure NTP clients with multiple servers. The client estimates each server's error and checks that a majority agree on a time range, so a misconfigured server is excluded as an outlier.

System Model and Reality

Algorithms (for example, consensus in Chapter 9) must tolerate these faults without depending too heavily on hardware and software details. A system model formalizes which faults an algorithm may assume.

Timing modelAssumesRealistic?
SynchronousBounded network delay, pauses and clock error (known upper bounds, not zero)No: unbounded delays and pauses happen
Partially synchronousSynchronous most of the time, but bounds are sometimes exceeded by arbitrary amountsYes, for many systems
AsynchronousNo timing assumptions, not even a clock (no timeouts)Very restrictive to design for
Node modelAssumes
Crash-stopA node fails only by crashing, and is then gone forever
Crash-recoveryA node may crash and come back after an unknown time; stable storage survives crashes, in-memory state is lost
Byzantine (arbitrary)A node may do anything, including deceive others
node faults → Crash-stop Crash-recovery Byzantine Synchronous Partially sync Asynchronous most useful for real systems unrealistic restrictive
System models combine a timing model with a node-fault model; partially synchronous plus crash-recovery fits most real systems.

Correctness of an algorithm. Define correctness by properties, the way "sorted" means each element is smaller than the ones to its right. For fencing tokens:

  • Uniqueness: no two token requests return the same value.
  • Monotonic sequence: if request x completed before y began, then t_x < t_y.
  • Availability: a node that requests a token and does not crash eventually receives a response.

An algorithm is correct in a system model if it always satisfies its properties in every situation the model allows. But if every node crashes, nothing can make progress, which leads to the next distinction.

Safety and liveness. Uniqueness and monotonic sequence are safety properties; availability is a liveness property. Liveness definitions often contain "eventually", and eventual consistency is a liveness property.

SafetyLiveness
InformallyNothing bad happensSomething good eventually happens
When violatedAt a specific point in time, and it cannot be undoneMay not hold now, but can still be satisfied later
RequirementMust hold in all situations of the model, even if all nodes crash or the network failsMay carry caveats (for example, only if a majority is up and the network eventually recovers)
  • The informal definitions are subjective; the real definitions are precise and mathematical.
  • The partially synchronous model requires that the system eventually returns to a synchronous state: any network interruption lasts a finite time.
Safety duplicate token issued damage done, cannot undo Liveness request sent not yet satisfied eventually replied
A safety violation happens at an identifiable moment and is permanent; liveness can still be met in the future.

Mapping system models to the real world. Models are simplified abstractions, and reality bites back:

  • Crash-recovery assumes stable storage survives. But disks get corrupted or wiped by hardware errors or misconfiguration, and firmware bugs can fail to recognize correctly attached drives on reboot.
  • Quorum algorithms assume a node remembers what it claims to have stored. A node with amnesia breaks the quorum condition and thus correctness. A model where storage mostly survives would be harder to reason about.
  • Real implementations may still need code for "impossible" cases, even if it is just printf("Sucks to be you") and exit(666), leaving a human operator to clean up. This is arguably the difference between computer science and software engineering.
  • Abstract models are still very valuable. They distill real complexity into a manageable set of faults, and they let us prove properties hold.
  • A correct proof does not guarantee a correct implementation, but analysis finds problems that might otherwise hide until assumptions (for example, about timing) break. Theoretical analysis and empirical testing are equally important.

Summary

  • Any packet may be lost or arbitrarily delayed, and so may the reply. With no reply, you cannot know whether the message got through.
  • A node's clock may be badly out of sync despite NTP, may jump forward or back, and its error interval is usually unknown, so relying on it is dangerous.
  • A process may pause for a long time at any point (for example, stop-the-world GC), be declared dead, and resume without realizing it.
  • Partial failure is the defining characteristic of distributed systems. Anything involving other nodes may fail, go slow or time out, so tolerance must be built into the software.
  • Detection is hard. Most systems rely on timeouts, which cannot tell network from node failures, and variable delay causes false suspicion. Degraded "limping" nodes (a Gigabit NIC dropping to 1 Kb/s through a driver bug) can be harder to handle than dead ones.
  • Tolerating faults is hard too. There is no shared state or common knowledge, nodes cannot even agree on the time, and information flows only over the unreliable network. Major decisions need a quorum, not a single node.
  • If a problem fits on a single machine, keep it there and avoid opening Pandora's box; one computer can do a lot. But fault tolerance and low latency (data close to users) still need distribution.
  • Unreliability is not a law of nature. Hard real-time and bounded network delay are possible, but expensive and lower utilization. Most non-safety-critical systems choose cheap and unreliable over expensive and reliable.
  • Supercomputers stop entirely when a component fails. Distributed systems can, in theory, run forever by handling faults and maintenance per node, though a bad config pushed to every node still brings them down.
  • This chapter was about problems; Chapter 9 turns to algorithms that cope with them.
Chapter 9

Consistency and Consensus

General-purpose abstractions with strong guarantees (linearizability, ordering, consensus) that let applications ignore many distributed-system faults, and the limits of what can be built on an unreliable network.

Key takeaways

  • Linearizability makes replicated data look like one copy with atomic operations: a recency guarantee. It is easy to reason about but slow, and unavailable on the disconnected side of a network fault.
  • Linearizability is a single-object recency guarantee; serializability is a multi-object transaction isolation property. Both together = strict serializability.
  • Needed for: locks and leader election, hard uniqueness constraints, and cross-channel timing dependencies.
  • CAP really says: when partitioned, choose consistent (linearizable) or available. It is narrow and best avoided; linearizability is dropped mostly for performance, not fault tolerance.
  • Causality is a partial order; linearizability is a total order. Causal consistency is the strongest model that stays available and fast under network problems.
  • Lamport timestamps give a total order consistent with causality, but cannot tell you when the order is final. Total order broadcast can.
  • Linearizable CAS, total order broadcast, atomic commit, locks, membership and uniqueness constraints are all equivalent to consensus.
  • 2PC gives atomic commit but blocks if the coordinator dies; real consensus (Paxos, Raft, Zab, VSR) uses epochs and majority quorums. Use ZooKeeper/etcd rather than building your own.

Introduction

  • Assume every Chapter 8 fault: lost, reordered, duplicated or delayed packets; approximate clocks; nodes that pause or crash.
  • Best approach: find abstractions with useful guarantees, implement them once, let apps rely on them (as transactions do for crashes, concurrency and disk faults).
  • Key abstraction: consensus, getting all nodes to agree on something. Example: electing one new leader on failover. Two nodes both thinking they lead is split brain, which often loses data.
  • The chapter covers the range of guarantees, the limits of what is possible, then consensus algorithms. Informal intuitions only, no formal proofs.

Consistency Guarantees

  • Two replicas read at the same moment often differ, whatever the replication method (single-leader, multi-leader, leaderless).
  • Most replicated databases offer eventual consistency: stop writing, wait an unspecified time, and all reads return the same value. A better name is convergence.
  • It is a weak guarantee: nothing about when. Before convergence a read can return anything or nothing; you may not read your own write.
  • Hard for developers: a database looks like a variable but behaves very differently. Bugs appear only under faults or high concurrency, so testing rarely finds them.
  • Stronger models are easier to use correctly but may cost performance or fault tolerance.
  • Distributed consistency vs transaction isolation: related hierarchies but mostly independent. Isolation avoids races between concurrent transactions; consistency coordinates replica state despite delays and faults.
  • Chapter plan: linearizability, then ordering (causality, total order), then distributed transactions leading to consensus.
time Replica 1 Replica 2 Replica 3 x = 1 x = 0 x = 0 x = 1 x = 0 all x = 1 converged after unknown delay reads may disagree
Eventual consistency: replicas disagree for an unbounded time, then converge.

Linearizability

  • Idea: make the system appear to have only one copy of the data, with every operation atomic. Also called atomic consistency, strong consistency, immediate consistency or external consistency.
  • Once any client's write completes, every later read by any client must see that value, never a stale cache or replica. It is a recency guarantee.
  • Book example (Figure 9-1): Alice sees the 2014 World Cup final result and tells Bob. Bob reloads after hearing her, hits a lagging replica, and sees the game still in progress. That violates linearizability.
Leader Follower 1 Follower 2 lagging final score written Alice Bob sees final score game still running tells
Figure 9-1: Bob asks after hearing Alice, yet gets a stale replica.

What Makes a System Linearizable?

  • The object being read and written (key x) is called a register: one key, row or document.
  • Each request is a bar from send time to response time. The client only knows the database handled it somewhere inside that bar.
  • Operations: read(x) ⇒ v, write(x, v) ⇒ r (r = ok or error).
  • Figure 9-2: x starts at 0; C writes 1 while A and B poll.
    • A read that ends before the write starts must return 0.
    • A read that starts after the write ends must return 1.
    • A read overlapping the write is concurrent with it and may return 0 or 1.
  • That alone allows values to flip back and forth during a write (a regular register), which is not "one copy".
  • Extra rule (Figure 9-3): there is one instant inside the write when x atomically flips 0→1. Once any read has returned 1, all later reads must return 1, even if the write has not yet completed.
  • The diagram assumes a global clock on the horizontal axis; that is fine for analysis as long as the algorithm itself cannot read it.
A B C read ⇒ 0 read ⇒ 1 read ⇒ 1 read ⇒ 1 ! write(x, 1) ⇒ ok concurrent reads: 0 or 1 after A saw 1, B must see 1
Figures 9-2/9-3: overlap allows either value, but once one read sees 1 every later read must.
  • Figure 9-4 adds cas(x, v_old, v_new) ⇒ r: atomic compare-and-set, error if x ≠ v_old.
  • Mark each operation's effective instant inside its bar and join the marks: the result must be a valid sequential register history, and the line must always move forward in time.
  • Points the book draws from Figure 9-4:
    • B's read, sent before D's and A's writes, can still return A's 1: the three were concurrent, so the database may order them D, A, B.
    • B can read 1 before A gets its ok: the ok was just delayed in the network.
    • No transaction isolation is assumed; C reads 1 then 2 because B changed x in between. D's cas fails since x is no longer 0.
    • B's final read returning 2 is not linearizable: A already read 4 before that read began.
  • Linearizability can be tested (expensively) by recording all request/response timings and checking that some valid sequential order exists.
A B C D write(x,1) read ⇒ 4 read ⇒ 1 cas(1,2) ok read ⇒ 2 ✗ read ⇒ 1 read⇒2 cas(2,4) ok write(x,0) cas(0,3) error effective points joined left to right; B's last read sees 2 after A saw 4
Figure 9-4: each operation takes effect at one instant; the joined line must never go backward.
SerializabilityLinearizability
KindIsolation property of transactionsRecency guarantee on reads/writes
ScopeMultiple objects per transactionOne register (single object)
OrderSome serial order; may differ from actual run orderMust respect real-time order
Write skewPreventedNot prevented (unless e.g. materializing conflicts)
  • Both together: strict serializability or strong one-copy serializability (strong-1SR).
  • 2PL and actual serial execution are typically linearizable. SSI is not: it reads a consistent snapshot that by design excludes newer writes.

Relying on Linearizability

A sports score a few seconds stale does little harm. These cases do need linearizability:

Locking and leader election

  • Single-leader systems must avoid split brain. Electing via a lock (first to acquire it leads) only works if the lock is linearizable: all nodes agree who holds it.
  • ZooKeeper and etcd use consensus to provide linearizable operations fault-tolerantly; Apache Curator adds higher-level recipes. Fencing details still matter.
  • ZooKeeper and etcd writes are linearizable but default reads can be stale; ask for a linearizable read (etcd quorum read, ZooKeeper sync() first).
  • Oracle RAC uses a linearizable lock per disk page on the transaction critical path, so deployments use a dedicated cluster interconnect.

Constraints and uniqueness guarantees

  • Unique username, email or file path enforced at write time needs linearizability. It is like taking a lock on the name, or a CAS that sets it only if unclaimed.
  • Same for balance never negative, stock never oversold, one booking per seat: one up-to-date value all nodes agree on.
  • Loose constraints (overbook, then compensate) may not need it. Hard uniqueness constraints do; foreign key and attribute constraints do not.

Cross-channel timing dependencies

  • Bob only noticed staleness because of a second channel (Alice's voice).
  • Figure 9-5: web server stores a full-size photo in file storage, then puts a resize instruction on a message queue (photos are too big for most brokers). The resizer fetches the photo.
  • If storage is not linearizable, the queue can beat internal replication: the resizer sees an old image or none, and full-size and thumbnail stay permanently inconsistent.
  • Linearizability is the simplest fix. If you control the second channel, read-your-writes style approaches also work, at extra complexity.
Web server File storage Message queue Image resizer 1 store photo 3 send msg 4 fast 5 fetch: stale? two channels race queue vs replication
Figure 9-5: file storage and message queue form two channels; without linearizability the resizer can read a stale photo.

Implementing Linearizable Systems

  • Simplest: really keep one copy. Not fault-tolerant: lose that node, lose access.
  • Usual approach is replication. Can each method be linearizable?
ReplicationLinearizable?Why
Single-leaderPotentiallyReads from leader or synchronous followers can be. Not if snapshot isolation is used or there are bugs; a delusional leader or async failover losing writes breaks it.
Consensus algorithmsYesLike single-leader but prevent split brain and stale replicas (ZooKeeper, etcd).
Multi-leaderNoConcurrent writes on many nodes, async replication, conflicts to resolve.
Leaderless (Dynamo-style)Probably notLWW on clocks (Cassandra) is almost certainly not; sloppy quorums ruin it; even strict quorums can fail.
  • Partitioning a single-leader database (one leader per partition) does not affect linearizability, since it is a single-object guarantee.

Linearizability and quorums

  • Figure 9-6: n = 3, w = 3, r = 2. Writer sets x = 1. A reads two nodes, one already has 1, returns 1. B starts after A finishes, reads two other nodes, both still 0, returns 0.
  • w + r > n holds, yet it is not linearizable (the Alice and Bob case again).
  • Fix at a performance cost: readers do synchronous read repair before returning, writers read a quorum's latest state before writing. Riak skips synchronous read repair; Cassandra waits for it but LWW breaks linearizability under concurrent writes to a key.
  • Only read and write can be made linearizable this way; linearizable CAS needs consensus.
  • Safest assumption: Dynamo-style leaderless systems are not linearizable.
Writer Replica 1 Replica 2 Replica 3 write x = 1 to all three (w = 3) x=1 arrive late A: r=2 ⇒ 1 B: r=2 ⇒ 0 reads R1, R2 reads R2, R3
Figure 9-6: strict quorum (w + r > n) yet B, starting after A, returns the older value.

The Cost of Linearizability

  • Figure 9-7: two datacenters; the link between them breaks while each datacenter and its clients still work.
  • Multi-leader: each datacenter keeps going; writes queue and sync when the link returns.
  • Single-leader: writes and linearizable reads must go to the leader's datacenter. Clients that can only reach the follower datacenter can do neither (stale reads only) until the link is fixed.
Datacenter 1 Leader clients OK Datacenter 2 Follower no writes, stale reads ✕ link down linearizable ⇒ DC 2 unavailable; available ⇒ not linearizable
Figure 9-7: a network interruption forces a choice between linearizability and availability.

The CAP theorem

  • This applies to any linearizable database and any unreliable network, even inside one datacenter:
    • Require linearizability: disconnected replicas must wait or return errors, i.e. become unavailable.
    • Do not require it: each replica can process requests independently (e.g. multi-leader) and stay available, but not linearizable.
  • Named by Eric Brewer in 2000; the trade-off was known since the 1970s. A rule of thumb that pushed engineers toward shared-nothing designs and helped spark NoSQL.
  • The two choices are sometimes labelled CP and AP; the book says this classification is flawed and best avoided.
  • "Network partition" here is a network fault, distinct from the book's use of partitioning for sharding.

Linearizability and network delays

  • Few systems are linearizable. Even multi-core RAM is not: each core has its own cache and store buffer, so another core may read an old value unless a memory barrier/fence is used.
  • That trade-off is for performance, not fault tolerance; CAP is irrelevant inside one computer. Many distributed databases drop linearizability for the same reason.
  • Linearizability is slow all the time, not only during faults. Attiya and Welch prove response time is at least proportional to the uncertainty of network delay, so on variable networks it is inevitably high. Weaker models can be much faster.

Ordering Guarantees

  • A linearizable register implies operations run in one well-defined order (the joined line in Figure 9-4).
  • Ordering recurs throughout the book: the leader fixes the order of writes in the replication log; serializability means transactions act as if in some serial order; clocks and timestamps try to decide which write came later.
  • Ordering, linearizability and consensus turn out to be deeply connected.

Ordering and Causality

  • One reason ordering matters: it preserves causality. Examples from earlier chapters:
    • Consistent prefix reads: seeing an answer before its question breaks cause and effect (a causal dependency).
    • Multi-leader: an update can overtake the insert of the row it updates.
    • Concurrent writes: A before B, B before A, or concurrent. Happened-before is causality; concurrent means neither knew of the other.
    • Snapshot isolation's "consistent snapshot" means consistent with causality: if it contains an answer it contains the question. Read skew violates causality.
    • Write skew (on-call doctors): going off call depends causally on observing who is on call. SSI detects it by tracking causal dependencies.
    • Bob's stale read after hearing Alice, and the image resizer, are causality violations.
  • Cause before effect, send before receive, question before answer. Chains of read-then-write define the causal order.
  • A system that obeys it is causally consistent. Snapshot isolation provides this.

The causal order is not a total order

  • Total order: any two elements comparable (5 < 13). Partial order: some pairs incomparable (sets {a, b} and {b, c}).
  • Linearizability = total order: one timeline, no concurrent operations; every request handled atomically at one point.
  • Causality = partial order: causally related operations are ordered, concurrent ones are incomparable. The timeline branches and merges, like Git history.
Linearizable: total order 1 2 3 4 one timeline Causal: partial order A B C D B ∥ C branch and merge B, C concurrent
Linearizability puts all operations on one line; causality leaves concurrent operations incomparable.

Linearizability is stronger than causal consistency

  • Linearizability implies causality, even across multiple channels (Figure 9-5), with no timestamps passed around. That is why it is simple and appealing.
  • But it hurts performance and availability, especially with large network delays (geo-distribution).
  • Middle ground: causal consistency is the strongest consistency model that does not slow down due to network delays and stays available during network failures. CAP does not apply to it.
  • Many systems that seem to need linearizability really need only causality. Research databases preserving causality with eventual-consistency-like performance exist, but little has reached production yet.

Capturing causal dependencies

  • If A happened before B, every replica must process A before B; a replica waits for missing predecessors. Concurrent operations may go in any order.
  • Need to know a node's "knowledge": did it see X when it wrote Y?
  • Same techniques as detecting concurrent writes, but across the whole database, not one key: generalized version vectors.
  • The database must know which version the app read: hence passing the prior version number back on write, and SSI checking at commit whether the data read is still current.

Sequence Number Ordering

  • Tracking all causal dependencies is often impractical: clients read lots before writing, and you can't tell which reads the write depends on.
  • Instead use sequence numbers or timestamps from a logical clock (counters per operation), not a time-of-day clock.
  • Compact (a few bytes) and give a total order. We can make that total order consistent with causality: if A happened before B, A gets the lower number; concurrent operations are ordered arbitrarily.
  • A total order that ignores causality is easy but useless (e.g. comparing random UUIDs).
  • Single-leader: the leader increments a counter per write in the replication log. Followers applying in log order are always causally consistent, even when lagging.

Noncausal sequence number generators

Without a single leader (multi-leader, leaderless, partitioned), common methods:

MethodHowWhy it breaks causality
Per-node numbersOne node odd, one even; or reserve bits for node IDNodes run at different rates, so one counter lags the other
Physical clock timestampsHigh-resolution time-of-day (used by LWW)Clock skew: a causally later op can get a lower timestamp
Preallocated blocksA takes 1–1,000, B takes 1,001–2,000A later op may draw from the lower block
  • All three scale better than a single leader and give unique, roughly increasing numbers, but are not consistent with causality.
  • Spanner makes physical timestamps causal by waiting out the clock uncertainty interval before commit; most clocks cannot give that uncertainty metric.

Lamport timestamps

  • Proposed by Leslie Lamport in 1978. Each node has a unique ID and a counter of operations processed. Timestamp = (counter, node ID).
  • Order: higher counter wins; on a tie, higher node ID wins. Unrelated to physical time but a total order.
  • Key idea: every node and client tracks the maximum counter seen and sends it on every request. A node receiving a larger maximum jumps its counter up to it.
  • Figure 9-8: client A gets counter 5 from node 2, sends 5 to node 1 (whose counter is 1). Node 1 jumps to 5, so its next operation is 6.
  • Every causal dependency increases the timestamp, so the order is consistent with causality.
  • Versus version vectors: those detect concurrency vs dependency; Lamport timestamps always force a total order and cannot tell you which. Lamport timestamps are more compact.
Client A Node 1 Node 2 Client B (1, 1) (4, 2) (5, 2) max = 5 sends max 5 1 → 5, op (6, 1) counter jumps to max seen
Figure 9-8: carrying the max counter on every request keeps the total order consistent with causality.

Timestamp ordering is not sufficient

  • Example: unique usernames. Idea: lower Lamport timestamp wins.
  • Works after the fact, once all operations are collected. It fails when a node must decide now: it can't know whether another node is concurrently claiming the name with a lower timestamp.
  • Checking every node first halts the system if any node is down or unreachable: not fault-tolerant.
  • You also need to know when the total order is finalized, so nobody can insert a claim ahead of yours. That is total order broadcast.

Total Order Broadcast

  • On one CPU core the order is just execution order. Getting all nodes to agree on one order is hard.
  • Single-leader replication sequences everything on the leader; open problems are scaling past one leader and failover. In the literature: total order broadcast or atomic broadcast (also total order multicast; "atomic" here is unrelated to ACID).
  • Partitioned databases with a leader per partition usually order only within a partition, so no cross-partition consistent snapshots or foreign keys. Total order across partitions needs extra coordination.
  • Two safety properties, which must hold despite node or network faults:
    • Reliable delivery: if a message reaches one node it reaches all.
    • Totally ordered delivery: every node gets messages in the same order.
  • During a network outage nothing is delivered; retries get messages through later, still in order.

Using total order broadcast

  • ZooKeeper and etcd implement it, a hint at its link to consensus.
  • State machine replication: every message is a write, every replica applies the same writes in the same order, so replicas stay consistent (apart from lag).
  • Serializable transactions: each message is a deterministic stored-procedure transaction, executed in the same order everywhere.
  • The order is fixed at delivery time: no inserting a message before already-delivered ones. That makes it stronger than timestamp ordering.
  • Equivalent view: it builds a log; delivering = appending; all nodes read the same sequence.
  • Lock service with fencing tokens: each lock request is a log message; its sequence number is the monotonically increasing token (zxid in ZooKeeper).
Log m1 m2 m3 m4 append order fixed once delivered Replica A m1 m2 m3 m4 Replica B m1 m2 m3 m4 Replica C m1 m2 (lagging) same messages, same order, delivery time not guaranteed
Total order broadcast is a log: every node delivers the same messages in the same order.

Implementing linearizable storage using total order broadcast

  • Not the same thing: total order broadcast is asynchronous (fixed order, no timing promise); linearizability is a recency guarantee.
  • Formally a plain linearizable read-write register is easier (implementable in the asynchronous crash-stop model); adding CAS or increment-and-get makes it equivalent to consensus.
  • Unique usernames via a linearizable CAS register per name (initially null), built on the log:
    1. Append a message tentatively claiming the username.
    2. Read the log until your own message comes back.
    3. If the first claim for that name is yours, commit (perhaps by appending again) and acknowledge; otherwise abort.
  • All nodes see the same first claim, so they agree on winner and losers. The same approach can give serializable multi-object transactions on a log.
  • Acknowledging right after enqueueing, without waiting, gives something like the x86 multi-core memory model: neither linearizable nor sequentially consistent.
  • This gives linearizable writes only. Reads from an asynchronously updated store may be stale: sequential consistency (also called timeline consistency), slightly weaker. To make reads linearizable:
    • Sequence the read through the log: append a message, perform the read when it is delivered (etcd quorum reads work somewhat like this).
    • Fetch the latest log position linearizably, wait until delivered up to it, then read (ZooKeeper sync()).
    • Read from a replica updated synchronously on writes (chain replication).
other msg U1 claims name U2 claims name first claim ⇒ commit later claim ⇒ abort 1 append 2 wait for own msg 3 check first claim every node sees the same order, so all agree on the winner
Linearizable compare-and-set (unique username) built on total order broadcast.

Implementing total order broadcast using linearizable storage

  • The reverse: given a linearizable register with atomic increment-and-get (or CAS), for each message increment-and-get, attach the value as sequence number, send to all nodes (resending lost ones). Recipients deliver in sequence order.
  • Unlike Lamport timestamps, these numbers have no gaps: after delivering 4 and receiving 6, a node knows to wait for 5. This is the key difference between total order broadcast and timestamp ordering.
  • Making that counter fault-tolerant (network cuts, node failure) inevitably leads to a consensus algorithm.
  • Proven: linearizable CAS (or increment-and-get) registers and total order broadcast are both equivalent to consensus. Solve one and you can transform it into the others.

Distributed Transactions and Consensus

  • Consensus: get several nodes to agree on something. Looks simple; many broken systems were built believing that. Even researchers took decades to understand it.
  • Situations needing agreement:
    • Leader election: all nodes must agree who leads, even under network faults; otherwise split brain, diverging data, data loss.
    • Atomic commit: a transaction spanning nodes or partitions must commit everywhere or abort everywhere.
  • Atomic commit differs slightly in form (commit only if all vote yes; consensus may pick any proposed value), but the two reduce to each other. Nonblocking atomic commit is harder than consensus.
  • Plan: atomic commit and 2PC (a consensus algorithm, but not a good one), then better ones: Zab (ZooKeeper), Raft (etcd).

Atomic Commit and Two-Phase Commit (2PC)

  • Atomicity: either all writes durable (commit) or all rolled back (abort). It keeps failed transactions from leaving half-updated state, and keeps secondary indexes consistent with primary data.

From single-node to distributed atomic commit

  • Single node: the storage engine writes data durably (e.g. WAL), then a commit record. On recovery, commit record present = committed, absent = rolled back.
  • The deciding moment is when the disk finishes writing the commit record. One device on one node makes the commit atomic.
  • Multi-node cases: multi-object transactions in a partitioned database, term-partitioned secondary indexes. Most NoSQL stores don't support this; some clustered relational systems do.
  • Just sending commit to every node can leave some committed and some aborted:
    • Some nodes hit a constraint violation or conflict.
    • Some commit requests are lost and time out.
    • Some nodes crash before writing the commit record.
  • A commit must be irrevocable: once visible, other transactions rely on it (basis of read committed). So a node commits only when sure all others will.
  • A later compensating transaction can undo effects, but that is a separate transaction and the application's problem.

Introduction to two-phase commit

  • Classic algorithm for atomic commit across nodes. Used inside some databases and exposed to apps as XA transactions (e.g. via Java Transaction API) or WS-AtomicTransaction for SOAP.
  • New component: the coordinator (transaction manager), often a library in the application process (e.g. in a Java EE container), sometimes a separate service. Examples: Narayana, JOTM, BTM, MSDTC.
  • Database nodes in the transaction are participants. App reads/writes on them normally; at commit the coordinator runs:
    • Phase 1: send prepare to all: "can you commit?"
    • Phase 2: all yes ⇒ commit; any no ⇒ abort to all.
  • The book compares it to a wedding: the minister asks each partner, and only after both say "I do" pronounces them married.
Coordinator Database 1 Database 2 locks held prepare yes commit point commit ok phase 1 phase 2
Figure 9-9: a successful two-phase commit; participants hold locks until the outcome arrives.

A system of promises

  1. App gets a globally unique transaction ID from the coordinator.
  2. App runs a single-node transaction on each participant, tagged with that ID. Any failure here: coordinator or participant may abort.
  3. At commit, coordinator sends prepare (with the ID) to all. Any failure or timeout ⇒ abort to all.
  4. A participant answering yes guarantees it can commit under all circumstances: data on disk, conflicts and constraints checked. It gives up the right to abort without yet committing.
  5. With all answers in, the coordinator decides (commit only if all yes) and writes the decision to its log on disk: the commit point.
  6. It then sends commit/abort and retries forever until it succeeds. A participant that crashed commits on recovery, since it voted yes.
  • Two points of no return: a yes vote, and the coordinator's decision. Single-node commit merges both into writing one commit record.

Coordinator failure

  • Before prepare: participants may safely abort. After voting yes: a participant cannot abort alone and must wait. It is in doubt (uncertain).
  • Figure 9-10: coordinator decides commit, database 2 receives it, coordinator crashes before telling database 1. Database 1 can neither abort (inconsistent with 2) nor commit (someone might have aborted) on timeout.
  • Participants could compare notes, but that is not part of 2PC. The only way to finish is for the coordinator to recover and read its log; transactions without a commit record there are aborted.
  • So the 2PC commit point is a regular single-node atomic commit on the coordinator.
Coordinator Database 1 Database 2 prepare yes decide commit committed ✕ crash in doubt: commit or abort? commit never reaches DB 1
Figure 9-10: the coordinator crashes after yes votes; database 1 is stuck in doubt.

Three-phase commit

  • 2PC is a blocking atomic commit protocol: it can wait on coordinator recovery.
  • 3PC aims to be nonblocking but assumes bounded network delay and response times; with unbounded delays and pauses it cannot guarantee atomicity.
  • Nonblocking atomic commit needs a perfect failure detector; timeouts aren't one. So 2PC is still used.

Distributed Transactions in Practice

  • Mixed reputation: important safety guarantee, but criticized for operational pain, killing performance and overpromising. Many cloud services skip them.
  • MySQL distributed transactions are reported over 10 times slower than single-node ones. Cost comes from extra disk forcing (fsync) for crash recovery and extra network round-trips.
  • Two different kinds often conflated:
Database-internalHeterogeneous
ParticipantsNodes of one distributed database, same software (VoltDB, MySQL Cluster NDB)Different technologies: databases from different vendors, message brokers
ProtocolAny, with technology-specific optimizationsMust share a standard atomic commit protocol
In practiceOften works quite wellMuch more challenging

Exactly-once message processing

  • Acknowledge a queue message only if the database transaction processing it commits, by committing ack and writes atomically together, even across unrelated broker and database.
  • If either fails both abort and the message is safely redelivered: effectively processed exactly once despite retries.
  • Requires every affected system to support the same protocol. An email server without 2PC could send the email twice on retry.
Message queue Consumer Database deliver writes one atomic commit: ack + DB writes either fails ⇒ both abort ⇒ message redelivered effectively exactly once
Exactly-once processing: atomically commit the message ack and the database writes.

XA transactions

  • X/Open XA (eXtended Architecture), from 1991: standard for 2PC across heterogeneous technologies. Supported by PostgreSQL, MySQL, DB2, SQL Server, Oracle, and brokers ActiveMQ, HornetQ, MSMQ, IBM MQ.
  • Not a network protocol: a C API to a transaction coordinator. In Java EE it is JTA, supported by JDBC and JMS drivers.
  • An XA-capable driver asks the API whether an operation is part of a distributed transaction, informs the server, and exposes callbacks for prepare, commit and abort.
  • The coordinator is often a library in the application process. It tracks participants, collects prepare responses, logs decisions on local disk.
  • If the app process or machine dies, the coordinator dies too; prepared participants are in doubt until that server restarts and the library reads its log. The database can't contact the coordinator directly; everything goes through the client library.

Holding locks while in doubt

  • Transactions hold row-level exclusive locks on modified rows (no dirty writes); with 2PL also shared locks on rows read.
  • These can't be released until commit or abort. Coordinator down 20 minutes ⇒ locks held 20 minutes; log lost ⇒ held forever, until an administrator steps in.
  • Other transactions touching those rows block (some databases block reads too), so large parts of the app can become unavailable.

Recovering from coordinator failure

  • Orphaned in-doubt transactions do happen (log lost or corrupted by a bug). They sit forever holding locks; rebooting databases doesn't help, since correct 2PC keeps those locks across restarts.
  • Only fix: an administrator inspects each participant and applies the same outcome manually, usually under outage pressure.
  • XA's heuristic decisions let a participant decide unilaterally; "heuristic" is a euphemism for probably breaking atomicity. Emergency use only.

Limitations of distributed transactions

  • The coordinator is itself a kind of database (it stores outcomes) and needs that level of care.
  • Unreplicated coordinator = single point of failure; many implementations aren't highly available by default.
  • Coordinator inside the app server makes the server stateful: its logs are as important as the databases.
  • XA is a lowest common denominator: no cross-system deadlock detection, doesn't work with SSI.
  • Database-internal transactions are less limited (distributed SSI is possible), but 2PC still needs all participants to respond, so it amplifies failures.
  • Alternatives without heterogeneous transactions come in Chapters 11 and 12.

Fault-Tolerant Consensus

  • Formalism: one or more nodes propose values; the algorithm decides one. Example: several customers want the last seat; each node proposes its customer ID; the decision says who gets it.
  • Required properties (this variant is uniform consensus):
    • Uniform agreement: no two nodes decide differently.
    • Integrity: no node decides twice.
    • Validity: a decided value was proposed by some node (rules out "always decide null").
    • Termination: every node that doesn't crash eventually decides.
  • Agreement + integrity = everyone decides the same, irrevocably. Without fault tolerance the first three are easy: a hardcoded "dictator" node. That fails when it dies, exactly 2PC's coordinator problem.
  • Termination formalizes fault tolerance: progress even if some nodes fail. It is a liveness property; the other three are safety properties.
  • Model: a crashed node never returns (the book's example: datacenter destroyed by a landslide). Any algorithm that waits for recovery fails termination, so 2PC is not consensus in this sense.
  • Any consensus algorithm needs a majority of nodes working for termination; that majority forms a quorum. Safety still holds if a majority fails: an outage stops progress but can't cause invalid decisions.
  • Most algorithms assume no Byzantine faults. Byzantine-tolerant consensus is possible if fewer than one-third of nodes are faulty (not covered).

Consensus algorithms and total order broadcast

  • Best known: Viewstamped Replication (VSR), Paxos, Raft, Zab. Similar but not identical. Implementing your own is not advisable.
  • They decide a sequence of values, i.e. they are total order broadcast algorithms. Total order broadcast = repeated rounds of consensus, one per message:
    • Agreement ⇒ same messages, same order everywhere.
    • Integrity ⇒ no duplicates.
    • Validity ⇒ no corrupt or fabricated messages.
    • Termination ⇒ no lost messages.
  • VSR, Raft and Zab implement total order broadcast directly (more efficient); for Paxos this is Multi-Paxos.

Single-leader replication and consensus

  • Single-leader replication is essentially total order broadcast. Why no consensus in Chapter 5? Because of how the leader is chosen.
  • Manually chosen leader = a dictatorial "consensus algorithm": works in practice but fails termination (needs humans).
  • Automatic election and failover gets closer to fault-tolerant total order broadcast, but electing a leader needs consensus, and these consensus algorithms need a leader. Apparent circularity.

Epoch numbering and quorums

  • The protocols don't guarantee a unique leader, only a unique leader per epoch: ballot number (Paxos), view number (VSR), term number (Raft).
  • When the leader seems dead, nodes vote with an incremented epoch. Epochs are totally ordered; on conflict the higher epoch wins.
  • Before deciding anything a leader must confirm no higher-epoch leader exists. It can't trust its own belief; it sends each proposal and waits for a quorum (usually a majority) to approve. A node approves only if it knows no higher epoch.
  • Two votes: elect a leader, then approve its proposals. The quorums must overlap: some node in a successful proposal vote also took part in the latest election. If none reports a higher epoch, the leader still leads and can decide.
  • Versus 2PC: the coordinator isn't elected; consensus needs only a majority, not every participant; and consensus defines recovery to a consistent state after a new leader takes over.
5 nodes: election quorum and proposal quorum overlap N1 N2 N3 N4 N5 leader elected, epoch e approved proposal N3 is in both: it would reveal any higher epoch higher epoch always wins a conflict
Majority quorums for election and for each proposal must share at least one node.

Limitations of consensus

  • Big benefits: agreement, integrity, validity in an uncertain world, progress while a majority works; total order broadcast and thus fault-tolerant linearizable atomic operations.
  • Costs:
    • Voting before deciding is a form of synchronous replication; many accept async replication's risk of losing data on failover for speed.
    • Needs a strict majority: 3 nodes tolerate 1 failure, 5 tolerate 2. Under a network split only the majority side progresses.
    • Mostly fixed membership; dynamic membership extensions are far less understood.
    • Relies on timeouts. With variable delays (geo-distribution) false leader-failure suspicions cause frequent elections and terrible performance, though safety is fine.
    • Network sensitivity: Raft has edge cases where one consistently unreliable link makes leadership bounce or the leader keep resigning, so no progress. Robust algorithms are an open research problem.

Membership and Coordination Services

  • ZooKeeper and etcd look like key-value stores (read/write keys, iterate), but app developers rarely use them directly; you get them through HBase, Hadoop YARN, OpenStack Nova, Kafka.
  • They hold small data that fits in memory (still written to disk), replicated via fault-tolerant total order broadcast.
  • ZooKeeper is modeled on Google's Chubby lock service and adds:
    • Linearizable atomic operations: CAS-based locks, usually leases with expiry so a failed client releases them.
    • Total ordering of operations: monotonically increasing transaction ID (zxid) and version number (cversion) serve as fencing tokens.
    • Failure detection: long-lived sessions with heartbeats; session declared dead after the session timeout; locks can auto-release (ephemeral nodes).
    • Change notifications: clients watch keys to learn when others join or fail, without polling.
  • Only the linearizable atomic operations really need consensus; the combination is what makes it useful.
ZooKeeper ensemble 3 or 5 nodes vote locks, zxid, sessions, watches App node App node App node App node … thousands e.g. "node 10.1.1.23 leads partition 7": slow-changing data only
A small fixed ensemble runs consensus on behalf of many clients: outsourced coordination.

Allocating work to nodes

  • Choosing a leader/primary among instances (single-leader databases, job schedulers, other stateful systems), with takeover on failure.
  • Assigning partitions of a resource (database, message streams, file storage, actor system) to nodes, rebalancing as nodes join, fail or leave.
  • Done with atomic operations, ephemeral nodes and notifications, apps can recover from faults automatically. Not easy even with Apache Curator, but far better than writing consensus from scratch, which has a poor success record.
  • Voting across thousands of app nodes would be inefficient; ZooKeeper runs on a fixed 3 or 5 nodes and serves many clients, outsourcing consensus, ordering and failure detection.
  • Data should change slowly (minutes or hours), e.g. which node leads a partition. Not for runtime state changing thousands or millions of times per second; for replicating that use tools like Apache BookKeeper.

Service discovery

  • ZooKeeper, etcd and Consul are used to find which IP address serves a service: services register endpoints on startup in cloud environments where VMs come and go.
  • Service discovery may not need consensus. DNS uses layers of caching, its reads are not linearizable, and slight staleness is usually fine; availability matters more.
  • Leader election does need consensus, so a consensus system may also tell others who the leader is. Some support read-only caching replicas that receive the decision log asynchronously, don't vote, and serve non-linearizable reads.

Membership services

  • Part of research dating to the 1980s (e.g. air traffic control). Determines which nodes are currently live members of a cluster.
  • Failure can't be detected reliably, but failure detection plus consensus gives agreement on who is alive. A live node may still be declared dead.
  • Agreement is what matters: "leader = lowest-numbered member" only works if all nodes agree on the membership.

Summary

  • Linearizability: replicated data appears as a single copy with atomic operations. Easy to understand (like a variable in a single-threaded program) but slow, especially with large network delays.
  • Causality orders events by cause and effect; it is weaker than linearizability (branching and merging history, some operations concurrent), has no coordination overhead and is much less sensitive to network problems.
  • Capturing causal order (e.g. Lamport timestamps) is not enough for some things: a node accepting a username must know nobody else is concurrently registering it. That leads to consensus.
  • Consensus: all nodes agree on a decision, irrevocably. Many problems are equivalent to it:
ProblemWhat must be decided
Linearizable compare-and-set registerWhether to set the value, given the current value
Atomic transaction commitCommit or abort a distributed transaction
Total order broadcastThe order to deliver messages
Locks and leasesWhich racing client acquired it
Membership/coordination serviceWhich nodes are alive vs dead (session timed out), given a failure detector
Uniqueness constraintWhich of several conflicting records is allowed
Consensus Linearizable CAS Atomic commit Total order broadcast Locks and leases Membership service Uniqueness constraint solve one, transform into the others
All six problems reduce to consensus and to each other.
  • All are easy on one node or with one decision-maker: a single-leader database gets linearizable ops, uniqueness and a totally ordered log this way.
  • If the leader fails or is unreachable, three options:
    1. Wait for it to recover (many XA/JTA coordinators). Fails termination: may block forever.
    2. Manual failover: humans pick a new leader (many relational databases); consensus by "act of God", as slow as humans.
    3. Automatic election: needs a consensus algorithm; use a proven one.
  • A leader avoids consensus per write but still needs it for leadership and changes: it "kicks the can down the road".
  • ZooKeeper-like tools provide outsourced consensus, failure detection and membership. Hard to use, but better than your own algorithms; use them for anything fault-tolerant that reduces to consensus.
  • Not everything needs consensus: leaderless and multi-leader systems usually skip global consensus and live with conflicts and branching/merging histories.
  • Theory papers, despite unrealistic assumptions, show what can and cannot be done and where systems are subtly flawed.
Part III

Derived Data

Parts I and II assumed one database. Real applications combine several datastores, indexes, caches and analytics systems, and must move data between them. Part III is about integrating many data systems into one coherent architecture.

Systems of Record and Derived Data

System of record source of truth · normalized user input written here first transform / process CacheIndexes · materialized viewsDenormalized values · summaries
Derived data is redundant and recreatable from the source; it exists for fast reads and other "points of view".
  • System of record (source of truth): holds the authoritative version. New data is written here first; each fact is stored exactly once, typically normalized. If another system disagrees, the system of record is right by definition.
  • Derived data: the result of transforming data from another system. If lost, it can be recreated from the source. Examples: caches, denormalized values, indexes, materialized views, predictive summaries from usage logs.
  • Derived data is technically redundant but often essential for read performance; it is commonly denormalized, and one source can feed several derived datasets.
  • The distinction depends on how you use a tool, not on the tool. Being explicit about which data is derived from which clarifies inputs, outputs and dependencies across the whole architecture: the running theme of Part III.

Overview of Chapters

  • Chapter 10: batch-oriented dataflow systems such as MapReduce, and the principles they give for large-scale data systems.
  • Chapter 11: the same ideas applied to data streams, for lower delays.
  • Chapter 12: how these tools might be used to build reliable, scalable and maintainable applications in the future.
Chapter 10

Batch Processing

Offline systems that take a large, bounded input, run a job over it and produce derived output: from Unix pipelines to MapReduce on a distributed filesystem to modern dataflow engines.

Key takeaways

  • Batch jobs are measured by throughput, not response time. Input is bounded, so a job knows when it is finished.
  • The Unix ideas carry over: immutable inputs, output that becomes another program's input, small tools composed through a uniform interface, logic separated from wiring.
  • MapReduce = mapper extracts key/value, framework partitions, sorts and shuffles by key, reducer processes all values for one key. HDFS plays the role of the filesystem.
  • Joins in batch: sort-merge (reduce-side, no assumptions about inputs), broadcast hash (small side in memory), partitioned hash and map-side merge (inputs already partitioned/sorted alike).
  • Write batch output as fresh immutable files (search indexes, key-value store files), never record-by-record into a live database. This gives easy rollback and human fault tolerance.
  • Hadoop vs MPP databases: Hadoop offers diversity of storage (raw data, schema-on-read), diversity of processing (arbitrary code), and task-level retry built for frequent preemption.
  • Dataflow engines (Spark, Tez, Flink) run a whole workflow as one job, skip needless sorts and avoid materializing intermediate state to HDFS; they recompute lost data, so operators should be deterministic.
  • Graph algorithms use the Pregel / BSP model; high-level declarative APIs let optimizers pick join algorithms and use columnar, vectorized execution, so batch engines and MPP databases are converging.

Introduction

Parts I and II assumed request/response. The book distinguishes three kinds of system:

  • Services (online systems): wait for a request, answer quickly. Measured by response time; availability matters.
  • Batch processing systems (offline systems): take a large input, run a job, produce output. Jobs take minutes to days, usually run on a schedule (e.g. daily). Measured by throughput.
  • Stream processing systems (near-real-time / nearline): consume inputs and produce outputs like batch, but act on events shortly after they happen, so latency is lower. Built on batch ideas; covered in Chapter 11.
Service (online) Client Server response time Batch (offline) Input Job Output throughput Stream (nearline) Processor low latency bounded input (batch) vs unbounded events (stream)
Online services wait for requests; batch jobs crunch a fixed input; stream jobs process events soon after they occur.
  • MapReduce (published 2004) was called "the algorithm that makes Google so massively scalable" and was reimplemented in Hadoop, CouchDB and MongoDB.
  • Lower-level than older warehouse parallel systems, but a big step in scale on commodity hardware. Its importance is declining; it still shows why and how batch processing is useful.

Batch Processing with Unix Tools

Running example: a web server appends one line per request to an access log (nginx default format). Each line holds client IP, time, request line, status, bytes sent, referrer and user agent.

$remote_addr - $remote_user [$time_local] "$request"
$status $body_bytes_sent "$http_referer" "$http_user_agent"

Simple Log Analysis

Goal: the five most popular pages. A Unix pipeline does it:

cat /var/log/nginx/access.log |
  awk '{print $7}' |
  sort             |
  uniq -c          |
  sort -r -n       |
  head -n 5
  • awk '{print $7}' takes the 7th whitespace field, the requested URL.
  • sort makes repeated URLs adjacent; uniq -c collapses adjacent duplicates and prefixes a count.
  • sort -r -n orders by count, largest first; head -n 5 keeps the top five.
  • Processes gigabytes in seconds and is easy to tweak (e.g. $1 ranks client IPs instead).
access.log awk $7 sort uniq -c sort -r -n head -n 5 map: URL group reduce: count 2nd sort pipes stream data via small in-memory buffers
The log-analysis pipeline; the same shape (extract key, sort, aggregate) reappears as MapReduce.

Chain of commands versus custom program

  • The same job can be a short Ruby program: a hash table counts (default 0), split each line and take field index 6, increment, then sort by count and print the top five.
  • Less concise than the pipeline but readable; preference is partly taste. The real difference is the execution flow, visible on large inputs.

Sorting versus in-memory aggregation

  • The working set (memory needing random access) depends only on the number of distinct URLs. For most small to mid-sized sites it fits in about 1 GB, so a hash table works even on a laptop.
  • If the working set exceeds memory, sorting wins: sort chunks in memory, write sorted segment files, merge them (as in SSTables and LSM-trees). Mergesort's sequential access suits disks.
  • GNU sort spills to disk automatically and parallelizes across CPU cores, so the pipeline scales without running out of memory. The bottleneck becomes reading the input from disk.
In-memory hash table log lines /a.html : 4 /b.html : 9 /c.css : 2 fine if distinct keys fit in RAM Sort, spill, merge chunk 1 chunk 2 chunk 3 sorted segments merged sequential disk I/O, any data size
Hash-table aggregation needs the distinct keys in memory; sort-based aggregation spills sorted runs to disk and merges them.

The Unix Philosophy

  • The 1978 statement of the Unix philosophy, paraphrased: (1) make each program do one thing well, and build new tools rather than bloating old ones; (2) expect output to feed some unknown next program, so keep it clean, avoid rigid columnar or binary formats and interactive input; (3) build and try software early, within weeks, and rebuild clumsy parts; (4) build tools to lighten work, even throwaway ones.
  • sort does one thing well (arguably better than most standard libraries, which neither spill to disk nor use multiple threads), yet is barely useful alone; it gains power combined with tools like uniq.

A uniform interface

  • To plug any output into any input, every program must share one I/O interface. In Unix it is the file (file descriptor): an ordered sequence of bytes.
  • The same interface represents real files, pipes and Unix sockets, stdin/stdout, device drivers (/dev/audio, /dev/lp0) and TCP sockets.
  • By convention many tools treat bytes as ASCII text with records separated by \n. The choice is arbitrary (ASCII record separator 0x1E would arguably be better); what matters is everyone agreed.
  • Field parsing is vaguer (whitespace, tabs, CSV); {print $7} is less readable than a named field would be.
  • Few systems compose this well; even same-model databases rarely exchange data easily (Balkanization of data).

Separation of logic and wiring

  • Programs read stdin and write stdout; the shell user decides where those connect. Pipes link one process's stdout to the next's stdin through a small in-memory buffer, without writing the stream to disk.
  • The program does not know or care where data comes from or goes: loose coupling, late binding, inversion of control. Your own tool (e.g. user-agent to browser name, IP to country code) can join a pipeline just by using stdin/stdout.
  • Limits: multiple inputs/outputs are tricky, and you cannot pipe output into a network connection.

Transparency and experimentation

  • Inputs are treated as immutable, so you can rerun commands with different options without damage.
  • You can stop the pipeline anywhere and pipe into less to inspect it, which helps debugging.
  • You can write one stage's output to a file and restart later stages from it without rerunning everything.
  • Biggest limitation: Unix tools run on a single machine. That is where Hadoop comes in.
file / pipe program logic stdin to stdout your own tool stdin to stdout less / file bytes, \n bytes, \n bytes, \n the shell wires inputs and outputs; programs only hold logic
Every tool speaks the same interface (a byte stream of newline-separated records), and wiring is left to the shell.

MapReduce and Distributed Filesystems

  • MapReduce is like Unix tools spread over potentially thousands of machines: blunt, brute-force, surprisingly effective. One job is comparable to one Unix process: one or more inputs, one or more outputs.
  • A job normally does not modify its input and has no side effects beyond its output. Output files are written once, sequentially, never modified in place.
  • Instead of stdin/stdout, jobs read and write files on a distributed filesystem. In Hadoop it is HDFS (Hadoop Distributed File System), an open source reimplementation of Google File System (GFS).
  • Others: GlusterFS, QFS; object stores (S3, Azure Blob Storage, OpenStack Swift) are similar, but usually separate storage from compute, while HDFS can run tasks where the data lives.
  • HDFS is shared-nothing (ordinary machines on a datacenter network), unlike shared-disk NAS/SAN appliances with custom hardware.
  • A daemon on each machine exposes its local disks over the network. A central NameNode tracks which file blocks live on which machine, creating one big filesystem across all disks.
  • Blocks are replicated across machines, either full copies or erasure coding (e.g. Reed–Solomon), which recovers lost data with less storage overhead. Like RAID, but over a normal network without special hardware.
  • Largest deployments: tens of thousands of machines, hundreds of petabytes, because commodity hardware is far cheaper than storage appliances.
NameNode block locations Machine 1 (daemon) Machine 2 (daemon) Machine 3 (daemon) B1 B2 B1 B3 B2 B3 each block replicated on several machines (or erasure-coded)
HDFS: a daemon per machine serves its local disks; the NameNode maps file blocks to machines.

MapReduce Job Execution

MapReduce follows the same four steps as the log example:

  1. Read input files and split them into records (one log line, \n separator). Done by the input format parser.
  2. Call the mapper to extract a key and value from each record (awk '{print $7}': URL as key, empty value).
  3. Sort all key-value pairs by key (the first sort). Implicit: mapper output is always sorted before reaching the reducer.
  4. Call the reducer over the sorted pairs; equal keys are adjacent, so values combine with little state (uniq -c).
  • Mapper: called once per input record; emits zero or more key-value pairs; keeps no state between records, so each record is independent.
  • Reducer: the framework collects all values for one key and calls the reducer with an iterator over them; it emits output records.
  • A second sort (the ranking step) needs a second MapReduce job reading the first job's output. The mapper prepares data for sorting; the reducer processes sorted data.

Distributed execution of MapReduce

  • MapReduce parallelizes across machines without parallel code from you; mappers and reducers see one record at a time.
  • Mappers/reducers are usually code: Java classes in Hadoop, JavaScript in MongoDB and CouchDB.
  • Parallelism comes from partitioning: the input is an HDFS directory and each file or block is a partition handled by its own map task. Input files are typically hundreds of megabytes.
  • The scheduler tries to run each mapper on a machine holding a replica of its input (if it has spare RAM and CPU): putting the computation near the data, saving network transfer.
  • Number of map tasks = number of input blocks; number of reduce tasks is set by the job author. A hash of the key picks the reducer, so equal keys meet in one place.
  • Sorting is staged: each map task partitions its output by reducer and writes each partition as a sorted file on its local disk (SSTable-like).
  • When a mapper finishes, reducers download their partition's sorted files from it. Partitioning by reducer, sorting and copying is the shuffle (no randomness involved, despite the name).
  • The reducer merges these files in sort order, is called with a key and an iterator over its records, and writes output to the distributed filesystem.
HDFS input map tasks reduce tasks HDFS output block 1 block 2 block 3 m 1 r1 r2 r3 files m 2 r1 r2 r3 files m 3 r1 r2 r3 files r 1 r 2 r 3 part 1 part 2 part 3 shuffle: partition by hash(key), sort, copy, merge
Figure 10-1, simplified: three mappers each write one sorted file per reducer; each reducer fetches and merges its partition.

MapReduce workflows

  • One job is limited: it can count views per URL but not rank the most popular, which needs a second sort. So jobs are chained into workflows.
  • Hadoop has no special workflow support: chaining is by directory name (job 1 writes a directory, job 2 reads it). To the framework they are two independent jobs.
  • More like writing each command's output to a temp file than like a Unix pipe.
  • A job's output counts only when the job succeeds (partial output of failed jobs is discarded), so a job starts only after the jobs producing its inputs finish.
  • Workflow schedulers handle these dependencies: Oozie, Azkaban, Luigi, Airflow, Pinball. Workflows of 50 to 100 jobs are common for recommendation systems, and many teams read each other's output.
  • Higher-level tools (Pig, Hive, Cascading, Crunch, FlumeJava) set up multi-stage workflows and wire them automatically.

Reduce-Side Joins and Grouping

  • Joins are needed for foreign keys, document references and graph edges; denormalization reduces but rarely removes them (book covers equi-joins).
  • Databases use indexes for queries touching few records. MapReduce has no indexes in the usual sense: it reads all input files, a full table scan.
  • That is outrageously expensive for a few records but reasonable for analytic aggregates over many records, especially in parallel.
  • In batch, a join means resolving every occurrence of an association in the dataset (all users at once), not looking up one user.

Example: analysis of user activity events

  • Left: a log of activity events (clickstream) of logged-in users. Right: a database of user profiles. In star-schema terms, events are the fact table and users a dimension.
  • Task: correlate activity with profile data, e.g. which pages are popular with which age groups. Events hold only the user ID; embedding full profiles in every event would be wasteful.
  • Naive: query the remote user DB per event. Throughput is capped by round-trip time and parallel queries could overwhelm the DB.
  • Good batch throughput needs computation local to one machine. Remote queries also make the job nondeterministic, since the remote data may change.
  • Better: copy the user database (e.g. from a backup via ETL) into the same distributed filesystem as the events, then let MapReduce bring related records together.
Activity events (fact) user_id url time 104 /x.html 10:01 173 /y.html 10:02 104 /z.html 10:05 User database (dimension) user_id date_of_birth 104 1989-.. 173 1994-.. join on user_id: which pages are popular with which ages
Figure 10-2, simplified: events carry only a user ID, so they must be joined with user profiles.

Sort-merge joins

  • One set of mappers reads events (key = user ID, value = event); another reads the user database (key = user ID, value = date of birth).
  • Partitioning and sorting by key puts a user's record and all their events adjacent in one reducer's input.
  • Secondary sort: arrange for the user record to come first, then events in timestamp order.
  • The reducer runs once per user ID: store the date of birth in a local variable, then iterate the events emitting (viewed-url, viewer-age). Later jobs can compute age distributions per URL.
  • Only one user record is in memory at a time and no network requests are made. Called a sort-merge join: mapper output is sorted by key, reducers merge both sorted sides.
user events user DB mapper id : event mapper id : birth date reducer input, id 104 birth date (first) event 10:01 event 10:05 url, viewer age (output) secondary sort partition + sort by user ID brings both sides together; reducer joins
Figure 10-3, simplified: a reduce-side sort-merge join on user ID; each input may be split across many parallel mappers.

Bringing related data together in the same place

  • Mappers and sorting gather everything needed for one user ID into a single reducer call, so the reducer can be simple, single-threaded, high-throughput and low-memory.
  • Think of mappers as "sending messages" to reducers: the key acts as a destination address. All pairs with the same key reach the same destination.
  • MapReduce separates network communication (getting data to the right machine) from application logic. Contrast databases, where fetches often happen deep inside application code.

GROUP BY

  • The same pattern implements grouping, usually followed by aggregation: count records (COUNT(*)), sum a field (SUM(fieldname)), or pick the top k by a ranking function.
  • Mappers emit the grouping key; partitioning and sorting gather each group in one reducer. Grouping and joining look very similar on MapReduce.
  • Sessionization: collate all events of one user session to see the sequence of actions, e.g. for A/B testing (did users on the new site version buy more?) or judging marketing.
  • A user's events are scattered over many servers' logs; group by session cookie or user ID.

Handling skew

  • The pattern breaks down when one key has huge amounts of data. In a social network most users have a few hundred connections but a few celebrities have millions of followers. Such records are linchpin objects or hot keys.
  • One reducer gets far more work (skew / hot spot). A job finishes only when all tasks do, so later jobs wait for the slowest reducer.
  • Pig skewed join: a sampling job first finds hot keys. During the join, mappers send hot-key records to one of several reducers chosen at random; the other input's records for that key are replicated to all those reducers. Spreads work at the cost of replication.
  • Crunch sharded join: similar, but hot keys are specified explicitly.
  • Hive skewed join: hot keys declared in table metadata, stored in separate files, and joined with a map-side join.
  • For grouping with a hot key, aggregate in two stages: stage 1 sends records to random reducers that each output a compact partial aggregate; stage 2 combines them into one value per key.
hot-key records (celebrity replies) other join input (celebrity profile) reducer A reducer B reducer C random reducer replicated to all work split 3 ways
Skewed join (Pig): hot-key records go to random reducers; the other side's matching records are copied to each of them.

Map-Side Joins

  • The joins above do the join logic in reducers: reduce-side joins. Mappers just prepare input (extract key/value, assign partition, sort).
  • Upside: no assumptions about the input. Downside: sorting, copying to reducers and merging are expensive, and data may hit disk several times depending on memory buffers.
  • If you can make assumptions about the input, a map-side join is faster: a cut-down job with no reducers and no sorting; each mapper reads one input block and writes one output file.

Broadcast hash joins

  • For a large dataset joined with one small enough to fit entirely in memory in each mapper.
  • If the user database in Figure 10-2 were small, each mapper loads it into an in-memory hash table at startup, then scans activity events and looks up each user ID.
  • There is one map task per block of the large input, and each loads the whole small input. "Broadcast": the small input goes to every partition of the large one; "hash": it uses a hash table.
  • Supported by Pig ("replicated join"), Hive ("MapJoin"), Cascading and Crunch; also used in warehouse query engines such as Impala.
  • Alternative: a read-only index on local disk; hot parts stay in the page cache, nearly as fast without fitting in memory.

Partitioned hash joins

  • If both inputs are partitioned the same way, apply the hash join to each partition independently. Example: partition events and users by the last decimal digit of user ID (10 partitions each); mapper 3 loads users ending in 3 and scans events for those users.
  • Each mapper reads one partition from each input, so each hash table is smaller.
  • Works only if both inputs have the same number of partitions, the same key and the same hash function, which is reasonable when earlier MapReduce jobs produced them. Hive calls these bucketed map joins.
Broadcast hash join small: all users mapper 1 hash table mapper 2 hash table mapper 3 hash table events blk 1 events blk 2 events blk 3 Partitioned hash join users *0 users *3 users *9 mapper 0 mapper 3 mapper 9 events *0 events *3 events *9 partition = last digit of user ID
Map-side joins: broadcast copies the whole small input to every mapper; partitioned loads only the matching partition.

Map-side merge joins

  • If inputs are partitioned the same way and sorted by the same key, size no longer matters: a mapper reads both files incrementally in ascending key order and matches equal keys, as a reducer would.
  • Usually earlier jobs produced that layout; a separate map-only join still makes sense if the sorted data serves other purposes too.

MapReduce workflows with map-side joins

  • The join type shapes the output: reduce-side output is partitioned and sorted by the join key; map-side output is partitioned and sorted like the large input (one map task per block of it, for broadcast or partitioned joins).
  • Map-side joins assume more about size, sorting and partitioning, so you must know the dataset's physical layout: not just encoding and directory, but number of partitions and the keys used for partitioning and sorting.
  • In Hadoop this metadata is often kept in HCatalog and the Hive metastore.
JoinWhereRequiresOutput layout
Sort-mergeReducersNothing about inputsBy join key
Broadcast hashMappersSmall side fits in memory (or local read-only index)Like large input
Partitioned hashMappersSame partition count, key, hash functionLike large input
Map-side mergeMappersSame partitioning and sorted by same keyLike large input

The Output of Batch Workflows

  • Batch is neither OLTP (index lookups) nor analytics (reports). It scans large inputs like analytics, but its output is often a structure, not a report.

Building search indexes

  • Google's original use of MapReduce: building search-engine indexes with a workflow of 5 to 10 jobs. Google later moved away from it, but Hadoop MapReduce remains a good way to build Lucene/Solr indexes.
  • A full-text index (simplified): a term dictionary mapping each keyword to its postings list of document IDs. Real ones also need data for relevance ranking, misspellings and synonyms.
  • For a fixed document set: mappers partition documents, each reducer builds its partition's index, index files go to the distributed filesystem. Document-partitioned indexes parallelize very well.
  • Querying is read-only, so index files are immutable once built.
  • On change: rerun everything and swap files (costly but simple: documents in, indexes out), or build incrementally with Lucene segment files and merging.

Key-value stores as batch process output

  • Batch jobs build classifiers (spam filters, anomaly detection) and recommenders (people you may know, related products). Output is often a database the web app queries by user or product ID.
  • Writing to the production database record by record from mappers/reducers works but is a bad idea:
    • A network request per record is orders of magnitude slower than batch throughput, even with client batching.
    • Many parallel tasks writing at batch rates can overwhelm the database and hurt its query performance, causing operational problems elsewhere.
    • It breaks MapReduce's clean all-or-nothing output guarantee: externally visible side effects expose partial results and must cope with task retries and speculative execution.
  • Better: build a brand-new database inside the job, write it as files to the output directory, then bulk-load them into read-only serving servers. Supported by Voldemort, Terrapin, ElephantDB and HBase bulk loading.
  • Extracting a key and sorting by it is most of the work of building an index anyway. Read-only, write-once files need simple data structures, e.g. no WAL.
  • Voldemort keeps serving the old files while copying new ones to local disk, then atomically switches; on trouble it switches back, since the old files are still there and immutable.
HDFS input batch job sort by key new DB files immutable read-only server old files new files atomic switch no per-record writes to a live DB rollback = switch back to old files
Key-value stores as batch output (e.g. Voldemort): build files in the job, bulk-load them, switch atomically.

Philosophy of batch process outputs

  • As in Unix, dataflow is explicit: input unchanged, previous output fully replaced, no other side effects. You can rerun freely while tweaking or debugging. MapReduce output follows the same philosophy, which aids performance and maintenance:
  • Buggy code producing bad output? Roll back the code and rerun, or switch back to the old output kept in another directory. Databases with read-write transactions lack this: rolling back code does not repair bad data. This is human fault tolerance.
  • Easy rollback lets features move faster than where mistakes are irreversible (minimizing irreversibility, good for Agile).
  • Failed map/reduce tasks are rescheduled on the same input. A code bug fails the job after a few attempts; a transient fault is tolerated. Safe only because inputs are immutable and failed tasks' output is discarded.
  • The same files can feed many jobs, including monitoring jobs comparing output to the previous run.
  • Like Unix, logic is separated from wiring (input/output directories), so one team writes a job that does one thing well and others decide where and when it runs.
  • Difference from Unix: Unix tools parse untyped text ({print $7}); Hadoop cuts such low-value parsing by using structured formats such as Avro and Parquet, with schema-based encoding and schema evolution.

Comparing Hadoop to Distributed Databases

  • Hadoop is a bit like a distributed Unix: HDFS is the filesystem, MapReduce a quirky process that always runs sort between map and reduce.
  • The algorithms were not new: massively parallel processing (MPP) databases (Gamma database machine, Teradata, Tandem NonStop SQL) had them over a decade earlier.
  • Biggest difference: MPP databases run analytic SQL in parallel; MapReduce plus a distributed filesystem is more like a general-purpose OS that runs arbitrary programs.

Diversity of storage

  • Databases force a data model; distributed filesystem files are just bytes in any model and encoding: records, text, images, video, sensor readings, sparse matrices, feature vectors, genome sequences.
  • Hadoop made it possible to dump data into HDFS indiscriminately and decide how to process it later. MPP databases need careful up-front modeling and import into proprietary storage.
  • In practice, making data available quickly, even raw, is often worth more than ideal up-front modeling.
  • Like a data warehouse, collecting an organization's data in one place enables joins across previously separate datasets. Raw collection with schema design later speeds this up: a data lake or enterprise data hub.
  • Interpretation shifts from producer to consumer (schema-on-read), helpful when they are different teams. There may be no single ideal model, only different views; raw data allows many transformations: the sushi principle, "raw data is better".
  • So Hadoop is often used for ETL: dump raw OLTP data, clean and transform it with MapReduce into relational form, import into an MPP warehouse. Modeling still happens, decoupled from collection.

Diversity of processing models

  • MPP databases are monolithic: storage layout, query planning, scheduling and execution tuned together, giving very good performance for their target queries. SQL is expressive and usable from graphical tools (e.g. Tableau) without code.
  • Not everything fits SQL: ML and recommendation systems, full-text indexes with relevance ranking, image analysis, feature engineering, translation models, fraud risk functions. These need code.
  • MapReduce lets engineers run their own code over large datasets. You can build SQL on top (Hive) or write batch processes that are not SQL at all.
  • Hadoop's openness allowed further models when MapReduce proved limiting, all sharing one cluster and the same HDFS files, so no data moves between specialized systems.
  • The ecosystem includes OLTP databases like HBase and MPP-style analytic databases like Impala; neither uses MapReduce, but both store data on HDFS.

Designing for frequent faults

  • Batch jobs are less fault-sensitive than online systems: failures do not hit users immediately and jobs can be rerun.
  • MPP databases usually abort the whole query on a node crash and resubmit; fine for queries of seconds to minutes. They also keep as much as possible in memory (e.g. hash joins).
  • MapReduce retries at the granularity of a single task and eagerly writes to disk, partly for fault tolerance, partly assuming data will not fit in memory. Suited to large, long jobs likely to hit at least one task failure, where rerunning the whole job would be wasteful.
  • Why, if hardware rarely fails? Google's mixed-use datacenters run online services and batch on the same machines, with container-enforced allocations and priced priorities.
  • Low-priority work is overcommitted and reclaimed by preemption, improving utilization; low-priority MapReduce tasks can be killed at any time.
  • At Google, an hour-long MapReduce task has about a 5% chance of being terminated for a higher-priority process, over an order of magnitude more than hardware failures, reboots and similar. A job of 100 tasks of 10 minutes each has a greater than 50% risk that at least one task is killed.
  • So frequent termination is tolerated for utilization, not because hardware is unreliable.
  • Open source schedulers preempt less: YARN's CapacityScheduler preempts to balance queues, but general priority preemption was not supported in YARN, Mesos or Kubernetes at the time of writing. Without frequent termination, MapReduce's design choices make less sense.
MPP databasesHadoop / MapReduce
StorageUp-front modeling, proprietary formatAny bytes; schema-on-read, data lake
ProcessingSQL, tightly integrated optimizerArbitrary code; many models on one cluster
FaultsAbort and rerun whole queryRetry individual tasks
Memory/diskKeep data in memory (hash joins)Write eagerly to disk
Best forSeconds-to-minutes analytic queriesHuge, long jobs under frequent preemption

Beyond MapReduce

  • MapReduce was hugely hyped in the late 2000s but is only one programming model; data volume, structure and processing type may favour other tools.
  • A good learning tool: simple to understand, not to use (you implement joins from scratch), hence Pig, Hive, Cascading and Crunch on top.
  • The execution model itself has problems that extra abstraction does not fix. MapReduce is very robust (huge data, unreliable multi-tenant clusters, frequent terminations, it finishes, slowly), but other tools can be orders of magnitude faster for some work.
  • Stream processing (Chapter 11) can be seen as another way of speeding up batch processing.

Materialization of Intermediate State

  • Each MapReduce job is independent; its only contact points are input and output directories, and an external scheduler starts job 2 after job 1 finishes.
  • Fine for widely published datasets: a well-known location gives loose coupling.
  • But often one job's output feeds exactly one other job by the same team. Those files are just intermediate state, and 50–100-job recommendation workflows have lots of it.
  • Writing intermediate state out to files is materialization (eagerly computing and writing a result rather than computing on demand). Unix pipes instead stream it incrementally through a small buffer.

Downsides of fully materializing, compared with pipes:

  • A job starts only when all tasks of preceding jobs finish; piped processes run concurrently. Straggler tasks, from skew or uneven load, delay the whole workflow.
  • Mappers are often redundant: they reread a file a reducer just wrote and prepare it for the next partition/sort. If reducer output were partitioned and sorted like mapper output, reducers could chain directly.
  • Intermediate files in a distributed filesystem are replicated across nodes, often overkill for temporary data.

Dataflow engines

  • Spark, Tez and Flink handle a whole workflow as one job rather than independent subjobs. Because they model the flow of data through stages explicitly, they are dataflow engines.
  • Functions, called operators, need not alternate map and reduce. Ways to connect operators:
    • Repartition and sort by key, as in the shuffle: enables sort-merge joins and grouping.
    • Partition several inputs the same way but skip sorting: saves effort for partitioned hash joins, where order is irrelevant.
    • Send one operator's output to all partitions of the join operator: broadcast hash joins.
  • Based on research systems Dryad and Nephele. Advantages over MapReduce:
    • Expensive work like sorting happens only where required, not by default between every stage.
    • No unnecessary map tasks: mapper work can fold into the previous reduce operator, since a mapper does not change partitioning.
    • All joins and dependencies are declared, so the scheduler can optimize locality, e.g. place consumer next to producer and exchange data via a shared memory buffer instead of the network.
    • Intermediate state usually lives in memory or local disk, not replicated HDFS. MapReduce did this for mapper output; dataflow engines generalize it.
    • Operators start as soon as their input is ready, without waiting for the whole previous stage.
    • Existing JVM processes are reused for new operators, unlike MapReduce's new JVM per task.
  • They compute the same things as MapReduce workflows, usually significantly faster. Pig, Hive or Cascading workflows can switch from MapReduce to Tez or Spark by configuration, without code changes.
  • Tez is a thin library on the YARN shuffle service; Spark and Flink have their own network layer, scheduler and APIs.
MapReduce workflow (two jobs) HDFS map sort reduce HDFS x3 map sort reduce replicated intermediate files; job 2 waits for every task of job 1 Dataflow engine (one job, DAG of operators) HDFS operator 1 sort if needed operator 3 HDFS intermediate data in memory / local disk, pipelined input and final output still materialized on HDFS
MapReduce materializes every intermediate dataset to replicated HDFS; dataflow engines pipeline operators and sort only where needed.

Fault tolerance

  • Materializing to a distributed filesystem makes intermediate state durable, so MapReduce simply restarts a failed task elsewhere on the same input.
  • Spark, Flink and Tez avoid writing intermediate state to HDFS, so if a machine dies its lost state is recomputed from data still available (an earlier stage, or the original HDFS input).
  • The framework must track how each piece of data was computed: input partitions and operators applied. Spark uses the resilient distributed dataset (RDD) to track ancestry; Flink checkpoints operator state to resume a failed operator.
  • Recomputation needs to know if operators are deterministic. If lost data was already sent downstream and the recomputed version differs, downstream cannot reconcile; with nondeterministic operators the usual fix is to kill and rerun downstream operators too.
  • Avoid such cascading faults by making operators deterministic. Nondeterminism creeps in easily: hash-table iteration order, random numbers in probabilistic algorithms, the system clock, external data sources. Fix e.g. with pseudorandom numbers from a fixed seed.
  • If intermediate data is much smaller than the source, or very CPU-intensive to compute, materializing is cheaper.

Discussion of materialization

  • MapReduce is like writing each command's output to a temp file; dataflow engines look like Unix pipes. Flink especially is built around pipelined execution: pass output incrementally without waiting for complete input.
  • Sorting must consume its whole input before emitting anything (the last record may have the lowest key), so sort operators accumulate state at least temporarily. Much else can be pipelined.
  • Final output must go somewhere durable, usually the distributed filesystem. So inputs and final outputs remain materialized on HDFS; inputs are immutable and output fully replaced. The gain is skipping intermediate writes.

Graphs and Iterative Processing

  • Batch graph processing analyses a whole graph offline, common in recommendation engines and ranking.
  • Example: PageRank estimates a web page's popularity from the pages linking to it; it feeds the ordering of web search results.
  • Naming confusion: dataflow engines arrange operators as a DAG (the flow is a graph, data is relational tuples). In graph processing, the data is a graph.
  • Many graph algorithms traverse one edge at a time, joining a vertex with its neighbour to propagate information, repeating until no edges remain or a metric converges. Example: listing all North American locations by following "within" edges (Figure 2-6), a transitive closure.
  • A graph can be stored as vertex and edge files, but "repeat until done" cannot be expressed in plain MapReduce (one pass). So it is run iteratively: a scheduler runs one batch step, checks the completion condition (no more edges, or change below a threshold), and repeats if not done.
  • This is very inefficient in MapReduce: each iteration reads the entire input and writes an entirely new output, even if little of the graph changed.

The Pregel processing model

  • The bulk synchronous parallel (BSP) model optimizes batch graph processing. Implemented by Apache Giraph, Spark's GraphX and Flink's Gelly; also called the Pregel model after Google's Pregel paper.
  • As mappers "send messages" to reducers by key, in Pregel one vertex sends messages to another, typically along edges.
  • Each iteration calls a function for each vertex with all messages sent to it, like a reducer call. The difference: a vertex keeps its state in memory across iterations, so it handles only new messages. Parts of the graph with no messages do no work.
  • Resembles the actor model (vertex = actor), except vertex state and messages are fault-tolerant and durable, and communication runs in fixed rounds: every iteration delivers all messages from the previous one.
Iteration n Iteration n+1 A B C msg barrier A B C per vertex, per round receive messages update in-memory state send to vertex IDs checkpoint state at end of iteration only vertices with mail do work
Pregel/BSP: messages sent in one iteration are delivered in the next, after a barrier; vertex state stays in memory.

Fault tolerance

  • Vertices communicate only by messages, not direct queries, so messages can be batched and there is less waiting. The only wait is between iterations: all messages of one iteration must be delivered before the next starts.
  • Even if the network drops, duplicates or delays messages, Pregel implementations guarantee each message is processed exactly once at its destination in the next iteration, and recover from faults transparently.
  • Achieved by checkpointing all vertex state to durable storage at the end of an iteration. On node failure, roll the whole computation back to the last checkpoint; if the algorithm is deterministic and messages are logged, only the lost partition need be recovered.

Parallel execution

  • A vertex sends to a vertex ID without knowing its machine; the framework partitions the graph and routes messages.
  • Because code deals with one vertex at a time ("thinking like a vertex"), partitioning can be arbitrary. Ideally chatty vertices are colocated, but that is hard, so graphs are often just partitioned by arbitrary vertex ID.
  • Result: heavy cross-machine communication; intermediate state (messages) is often bigger than the graph, and network overhead can slow distributed graph algorithms significantly.
  • So if the graph fits in one machine's memory, a single-machine (maybe single-threaded) algorithm will likely beat a distributed batch job. If it fits on one machine's disks, single-machine frameworks such as GraphChi are viable. Only when it exceeds one machine is a distributed approach like Pregel unavoidable; efficient parallel graph algorithms are ongoing research.

High-Level APIs and Languages

  • Execution engines have matured to store and process many petabytes on clusters of over 10,000 machines. With operations at that scale considered more or less solved, focus moved to the programming model, efficiency, and broader problem coverage.
  • Hive, Pig, Cascading and Crunch became popular because hand-written MapReduce is laborious; with Tez they could move to a dataflow engine without rewriting jobs. Spark and Flink have their own high-level dataflow APIs, often inspired by FlumeJava.
  • These APIs use relational-style building blocks: join on a field, group by key, filter, aggregate (count, sum, etc.), implemented internally with the join and grouping algorithms of this chapter.
  • They also allow interactive, incremental use in a shell, echoing the Unix philosophy.

The move toward declarative query languages

  • With joins expressed as relational operators, the framework can analyse inputs and pick the best join algorithm itself. Hive, Spark and Flink have cost-based query optimizers that do this and can reorder joins to minimize intermediate state.
  • Otherwise MapReduce and its successors differ from fully declarative SQL: they are built on function callbacks that can run arbitrary code, letting you use libraries for parsing, natural language, image analysis, numerical and statistical algorithms.
  • MPP databases' user-defined functions are often cumbersome and poorly integrated with package managers (Maven, npm, Rubygems).
  • Declarative features help beyond joins too. Calling a callback per record just to filter or select fields costs significant CPU. Expressed declaratively, the optimizer can use column-oriented storage and read only needed columns.
  • Hive, Spark DataFrames and Impala use vectorized execution: tight, cache-friendly inner loops without function calls. Spark generates JVM bytecode; Impala uses LLVM to generate native code.
  • With declarative APIs and optimizers, batch frameworks look more like MPP databases and reach comparable performance, while keeping the flexibility of arbitrary code and arbitrary data formats.

Specialization for different domains

  • Recurring patterns deserve reusable building blocks; business reporting is only one domain.
  • Statistical and numerical algorithms for ML (classification, recommendation): Mahout implements ML on MapReduce, Spark and Flink; MADlib does similar inside a relational MPP database (Apache HAWQ).
  • Spatial algorithms such as k-nearest neighbors (similarity search in multi-dimensional space); approximate search for genome analysis (similar but not identical strings).
  • As batch systems gain built-in functionality and declarative operators, and MPP databases become more programmable, the two converge: all are systems for storing and processing data.
Batch frameworks arbitrary code any data format + optimizers, columnar MPP databases declarative SQL tuned execution + programmability store and process data cost-based joins, vectorized execution, ML and spatial libraries
Declarative APIs push batch frameworks toward MPP-like performance while MPP databases grow more programmable.

Summary

  • Unix design principles carry into MapReduce and dataflow engines: immutable inputs, outputs meant for an unknown next program, small tools that "do one thing well".
  • Uniform interface: files and pipes in Unix, the distributed filesystem in MapReduce. Dataflow engines add pipe-like transport, but job input and final output usually stay on HDFS.
  • Partitioning: mappers follow input blocks; their output is repartitioned, sorted and merged into reducer partitions to bring records with the same key together. Dataflow engines sort only when required.
  • Fault tolerance: MapReduce writes to disk often, so single tasks recover easily but fault-free runs are slower. Dataflow engines keep more in memory and recompute more on failure; deterministic operators limit that.
  • Joins: sort-merge (same key reaches one reducer call), broadcast hash (small input as a hash table in every mapper), partitioned hash (same key, hash function and partition count, joined per partition).
  • Callbacks are assumed stateless with no external side effects, so tasks retry safely, failed output is discarded and only one successful attempt per partition becomes visible. Output equals a fault-free run, far stronger than online services writing to databases as a side effect.
  • A batch job derives output from bounded input without modifying it, so it knows when it is done. Stream processing (Chapter 11) handles unbounded input, where a job never completes.
Chapter 11

Stream Processing

Batch processing assumes bounded input. Real data is unbounded and arrives over time, so this chapter treats event streams as the incrementally processed counterpart of batch data: how they are transmitted, how they relate to databases, and how to process them continuously.

Key takeaways

  • An event is a small immutable record of something that happened; producers write it once, many consumers read it; related events form a topic.
  • AMQP/JMS brokers assign and delete individual messages (task queues). Log-based brokers (Kafka) assign partitions, keep messages, preserve order and allow replay.
  • Dual writes race and partially fail; CDC makes every derived system a follower of one database's change log.
  • Event sourcing stores immutable application-level events; state is derived. The truth is the log; the database is a cache of it.
  • Separate write form from read views (CQRS) to add views and evolve safely.
  • Window by event time, not processing time, and plan for stragglers.
  • Joins: stream-stream, stream-table, table-table; all keep state from one input, and cross-stream order makes them time-dependent.
  • Exactly-once (effectively-once) needs microbatching or checkpointing plus atomic commit or idempotent writes.

Introduction

  • Batch input is bounded; sorting cannot emit output until all input is read. Real data is unbounded, so batch jobs cut it into chunks (a day, an hour) and show changes late.
  • Processing every event as it happens is stream processing. A stream is data made available incrementally (stdin, TCP, Java FileInputStream, video delivery).

Transmitting Event Streams

  • A record is an event: small, self-contained, immutable, usually timestamped (page view, purchase, sensor reading, web log line), encoded as text, JSON or binary.
  • A producer (publisher, sender) generates an event once; many consumers (subscribers, recipients) may process it. Related events are grouped into a topic or stream, the counterpart of a filename.
  • Polling a datastore gets expensive as frequency rises (fewer polls return anything); consumers should be notified. Database triggers are too limited, so specialized tools exist.

Messaging Systems

  • A producer sends a message containing the event; it is pushed to consumers. Unlike a Unix pipe or TCP connection (one sender, one receiver), a messaging system lets many producers write to a topic and many consumers read it: the publish/subscribe model.
  • Two questions distinguish systems:
    1. Producers faster than consumers? Drop, buffer in a queue (and what happens when it outgrows memory?), or apply backpressure (block the sender, as pipes and TCP do).
    2. Nodes crash? Durability needs disk and/or replication, at a cost; accepting loss buys throughput and latency.
  • Loss tolerance depends on the app: a periodic sensor can lose a point; counting events needs reliable delivery.

Direct messaging from producers to consumers

  • UDP multicast: financial feeds (stock prices) where latency matters; application protocols recover lost packets, so producers must remember what they sent.
  • Brokerless libraries (ZeroMQ, nanomsg): pub/sub over TCP or IP multicast.
  • StatsD, Brubeck: metrics over unreliable UDP; counters are correct only if every message arrives, so they are approximate at best.
  • Webhooks: a service registers a callback URL with another; the producer makes an HTTP/RPC request to it on each event.
  • Downside: apps must expect loss; these assume both sides are always online, and a crashed producer loses its retry buffer.

Message brokers

  • A message broker (message queue) is essentially a database optimized for message streams. It runs as a server; producers and consumers are clients.
  • Clients can come, go and crash; durability moves to the broker (memory or disk). Slow consumers usually get unbounded queueing.
  • Consumers are asynchronous: the producer waits only for the broker to buffer the message, not for processing.

Message brokers compared to databases

Some brokers even take part in 2PC (XA/JTA), but practical differences remain:

AspectDatabaseTraditional message broker
RetentionKeeps data until explicitly deletedDeletes a message once delivered; unsuited for long-term storage
Working setCan be largeAssumes short queues; long queues (spilling to disk) slow each message and cut throughput
Selecting dataSecondary indexes, searchSubscribe to topics matching a pattern
Change awarenessQuery is a point-in-time snapshot; you are not told when it goes staleNo arbitrary queries, but notifies clients when new data arrives

This traditional view is captured in the JMS and AMQP standards, implemented by RabbitMQ, ActiveMQ, HornetQ, Qpid, TIBCO EMS, IBM MQ, Azure Service Bus and Google Cloud Pub/Sub.

Multiple consumers

  • Load balancing: each message goes to one consumer, so consumers share the work; useful when messages are expensive to process. (AMQP: several clients on one queue; JMS: shared subscription.)
  • Fan-out: each message goes to all consumers, so independent consumers "tune in" without affecting each other, like several batch jobs reading one file. (JMS topic subscriptions; AMQP exchange bindings.)
  • Combine them: two consumer groups each get every message, but within a group only one node gets each message.
(a) Load balancing (b) Fan-out Producer Topic Consumer 1 Consumer 2 m1, m3 m2, m4 Producer Topic Consumer 1 Consumer 2 m1..m4 m1..m4
Figure 11-1: load balancing shares a topic's messages; fan-out delivers every message to every consumer.

Acknowledgments and redelivery

  • Consumers send an acknowledgment when done; without one (connection closed or timed out) the broker redelivers to another consumer. The ack may simply have been lost, which needs atomic commit to handle.
  • Load balancing + redelivery reorders messages: consumer 2 crashes on m3 while consumer 1 handles m4; m3 is redelivered to consumer 1, which sees m4, m3, m5. This happens even though JMS and AMQP require brokers to preserve order.
  • Fix: a separate queue per consumer (no load balancing). Reordering is harmless for independent messages but matters with causal dependencies.
Producer Consumer 1 Consumer 2 m1 m2 m3 m4 m5 m1 m4 m3 m5 m2 m3 crash no ack: redeliver order: m4, m3
Figure 11-2: consumer 2 crashes on m3; redelivery to consumer 1 puts m3 after m4.

Partitioned Logs

  • Brokers have a transient messaging mindset: even durable ones delete after delivery. Databases keep data until explicitly deleted.
  • AMQP/JMS consumption is destructive, so you cannot rerun a consumer like a batch job, and a new consumer sees only messages sent after it registered.
  • Log-based message brokers combine durable database-style storage with low-latency notification.

Using logs for message storage

  • A log is an append-only sequence of records on disk (as in log-structured storage and WALs, Chapter 3, and replication, Chapter 5).
  • Producer appends to the end; consumer reads sequentially and, at the end, waits for a notification of new appends (like tail -f).
  • To exceed one disk's throughput, partition the log; partitions live on different machines and are read and written independently. A topic is a group of partitions carrying messages of one type.
  • Each message gets a monotonically increasing offset; a partition is totally ordered, but there is no ordering across partitions.
  • Kafka, Amazon Kinesis Streams, Twitter's DistributedLog (Google Cloud Pub/Sub is similar but JMS-style). Despite writing everything to disk they reach millions of messages per second by partitioning, with replication for fault tolerance.
Producer A Producer B Topic = partitions P0 P1 P2 0 1 2 3 4 5 0 1 2 3 0 1 2 3 4 append at end Consumer X Consumer Y numbers = offsets; order only within a partition
Figure 11-3: producers append to topic-partition logs; consumers read them sequentially.

Logs compared to traditional messaging

  • Fan-out is trivial: reading does not delete, so many consumers read independently.
  • Load balancing assigns whole partitions to nodes in a consumer group; each node reads its partitions sequentially, single-threaded.
  • Downsides of this coarse scheme:
    • Number of consumers sharing a topic is at most the number of partitions.
    • A slow message holds up later ones in its partition (head-of-line blocking).

Consumer offsets

  • Everything below a consumer's offset is processed, so the broker only periodically records offsets, not per-message acks; this and batching raise throughput.
  • The offset is like the log sequence number in single-leader replication: broker = leader, consumer = follower, able to reconnect and resume without skipping writes.
  • If a consumer fails, another in the group takes its partitions from the last recorded offset; messages processed but not yet recorded are processed twice (handled later in the chapter).

Disk space usage

  • The log is split into segments; old segments are deleted or archived. A consumer whose offset points into a deleted segment misses messages.
  • So the log is a bounded circular (ring) buffer, but on disk, so very large.
  • Back-of-envelope: a 6 TB drive at 150 MB/s sequential write fills in about 11 hours at full speed. The ratio holds with many drives. Real deployments rarely use full bandwidth, so buffers of days or weeks are typical.
  • Throughput stays constant regardless of retention; memory-first brokers slow down once they spill to disk.

When consumers cannot keep up with producers

  • In the drop/buffer/backpressure taxonomy, a log is buffering with a large, fixed-size buffer. A consumer too far behind loses the oldest messages.
  • Monitor consumer lag and alert; the big buffer gives an operator time to fix it.
  • A lagging consumer affects only itself, so you can safely consume a production log for testing. A stopped consumer leaves only its offset (traditional brokers keep filling queues for dead consumers).
deleted segment segment 2 segment 3 active segment head fast consumer slow consumer lag to monitor offset here = missed
A log is a large on-disk ring buffer: each consumer has its own offset; only a consumer that lags past retention loses data.

Replaying old messages

  • In a log, consuming is read-only, like reading a file. The only side effect (apart from output) is the offset moving, and the consumer controls it.
  • You can start a copy of a consumer at yesterday's offsets, write output elsewhere, and reprocess a day's messages, as often as you like with different code.
  • Like batch: a repeatable transformation, so experimentation and recovery from bugs are easier.

Databases and Streams

  • Apply streaming ideas to databases: a write to a database is an event. A replication log is a stream of write events that followers apply.
  • State machine replication: if every replica processes the same deterministic events in the same order, all end in the same state. That is another event stream.

Keeping Systems in Sync

  • Apps combine an OLTP database, cache, full-text index and warehouse, each with its own copy, which must stay in sync. Warehouses use batch ETL.
  • If full dumps are too slow, some use dual writes: app code writes to each system in turn.
  • Race: client 1 sets X=A, client 2 sets X=B; the DB ends at B, the index at A. Permanently inconsistent, silently (unless you use something like version vectors).
  • Partial failure: one write fails; preventing it is expensive atomic commit.
  • DB and index each have their own leader, so conflicts arise. Better: the DB as sole leader and the index as its follower.
Client 1 Database Search index Client 2 X=A X=B X=B X=A final X=B final X=A
Figure 11-4: interleaved dual writes leave the database and search index permanently different.

Change Data Capture

  • Replication logs were long an undocumented internal detail. Change data capture (CDC): observe all data changes written to a database and extract them in a form other systems can replicate, ideally as a stream right away.
  • Apply the change log, in order, to a search index and it matches the database. Derived systems are just consumers of the change stream.
Database leader CDC X=A Y=C X=B change log (ordered) Search index Cache Data warehouse followers
Figure 11-5: changes taken in write order from one database and applied in the same order to other systems.

Implementing change data capture

  • Log consumers are derived data systems: another view onto the system of record. CDC makes one database the leader and the others followers.
  • A log-based broker suits transport because it preserves order (avoiding the Figure 11-2 reordering).
  • Implementations: triggers writing to a changelog table (fragile, heavy overhead) or parsing the replication log (more robust, but schema changes are a challenge).
  • At scale: LinkedIn's Databus, Facebook's Wormhole, Yahoo!'s Sherpa. Bottled Water (PostgreSQL WAL decoding), Maxwell and Debezium (MySQL binlog), Mongoriver (MongoDB oplog), GoldenGate (Oracle).
  • CDC is usually asynchronous: the source commits without waiting for consumers. A slow consumer barely affects it, but all replication lag problems apply.

Initial snapshot

  • Full history is usually truncated, yet a new index needs the whole database. So start from a consistent snapshot that corresponds to a known log offset, then apply changes after it. Some CDC tools do this; others leave it manual.

Log compaction

  • Alternative to repeated snapshots. Principle (from hash-indexed storage engines): periodically, in the background, drop older records for a key and keep only the latest. A tombstone (null value) marks a deletion and removes the key at compaction.
  • Disk use tracks current contents, not write count. For CDC: if every change has a primary key and each update replaces the previous value, keeping the latest write per key is enough.
  • To rebuild a derived system, start a consumer at offset 0 of the compacted topic and scan; it holds the latest value for every key, a full copy with no new snapshot of the source.
  • Supported by Apache Kafka; it lets the broker serve as durable storage, not just transient messaging.
Log before k1: a k2: b k1: c k3: d k2: null k1: e background compaction Log after k3: d k1: e k2 tombstone removes k2; older k1 values discarded. Reading from offset 0 yields a full copy of current state.
Log compaction: keep only the most recent value per key; size tracks current data, not write history.

API support for change streams

  • Change streams are becoming first-class. RethinkDB: queries subscribe to notifications when their results change. Firebase and CouchDB: sync via a change feed available to apps. Meteor: uses the MongoDB oplog to update the UI.
  • VoltDB: transactions export data as a stream; the stream is modeled as a table that transactions insert into but cannot query; consumers read committed tuples in commit order.
  • Kafka Connect integrates CDC tools for many databases with Kafka, feeding derived systems and stream processors.

Event Sourcing

  • A technique from the domain-driven design (DDD) community. Like CDC, it stores all changes to application state as a log of change events, but at a different level of abstraction.
Change data captureEvent sourcing
How the app writesMutable database; update and delete freelyAppend immutable events to an event log; updates/deletes discouraged or banned
Event levelLow-level state changes, extracted from the replication logApplication-level things that happened
App awarenessApp need not know CDC existsApp logic is built on the events
OrderingExtracted in true write order (no Figure 11-4 race)Order of the event log
  • Recording actions, not their effects, eases evolution and debugging and guards against bugs.
  • Example: "student cancelled their course enrollment" states intent neutrally. "One row deleted from enrollments, one reason added to feedback" bakes in assumptions about later use. A new feature such as "offer the place to the next person on the waiting list" chains off the existing event.
  • Similar to the chronicle data model and to the fact table of a star schema.
  • Use Event Store, a conventional database or a log-based broker.

Deriving current state from the event log

  • Users want current state (cart contents), so apps transform the log (the write form) into state (the read form) with deterministic logic.
  • Log compaction differs:
    • CDC: an update event holds the whole new record, so the latest event per key decides the value; older ones can be discarded.
    • Event sourcing: events express intent, not the resulting state; later events don't override earlier ones, so you need the full history. Compaction is not possible in the same way.
  • Apps store snapshots of derived state to avoid full reprocessing, but only as a performance optimization; the intent is to keep all raw events forever and reprocess when needed.

Commands and events

  • A user request first arrives as a command, which may fail (an integrity check). Once validated and accepted it becomes an event: durable, immutable, a fact.
  • Example: registering a username or reserving a seat requires checking it is free; then an event records that this user ID took it. Later cancellation is a separate event; the fact of the earlier reservation stays true.
  • Consumers cannot reject an event; others may already have seen it. So command validation must be synchronous, before the event, e.g. a serializable transaction that validates and publishes atomically.
  • Alternative: split into a tentative reservation event and a later confirmation event, so validation can be asynchronous.

State, Streams, and Immutability

  • Immutability gives batch, event sourcing and CDC their power. Databases store changing current state, yet every state is the result of the events that mutated it: available seats from processed reservations, a balance from credits and debits, a response-time graph from individual requests.
  • Mutable state and an append-only log of immutable events are two sides of the same coin. The changelog is the evolution of state over time.
  • Mathematically: state = the integral of the event stream over time; the change stream = the derivative of state. (The analogy is limited; a second derivative of state is not meaningful.)
  • Storing the changelog durably makes state reproducible. Treat the log as the system of record and all mutable state as derived.
  • Pat Helland's view, paraphrased: the database holds a cache of the latest record values from the log. The truth is the log; the database is a cache of a subset of it.
  • Log compaction bridges the two: keep only the latest version of each record.
Event stream immutable changelog Application state mutable, current integrate over time differentiate by time the truth is the log; the database is a cache
Figure 11-6: current state and the event stream are related like integral and derivative.

Advantages of immutable events

  • Accounting: an append-only ledger; accounts are derived by summing. Mistakes get a compensating entry (a refund), never an erasure.
  • If buggy code writes bad data, an immutable log makes diagnosis and recovery much easier than destructive overwrites.
  • Events hold more than current state: an item added then removed from a cart cancels out for fulfillment, but analytics learns the customer considered it. A delete-on-remove database loses that.

Deriving several views from the same event log

  • Separating mutable state from the immutable log lets you derive many read-oriented views from one log, like multiple stream consumers.
  • Examples: Druid ingests from Kafka; Pistachio uses Kafka as a commit log; Kafka Connect sinks export to many stores.
  • An explicit log-to-database step eases evolution: build a new read-optimized view for a new feature beside the existing systems, without modifying them. Running old and new side by side is often easier than a complex schema migration; shut the old one down later.
  • Separating the write form from several read forms is command query responsibility segregation (CQRS). It drops the fallacy that data must be written in its query form; denormalized views are fine because the translation keeps them consistent.
  • Twitter home timelines are such a read-optimized, highly denormalized cache (your tweets copied into every follower's timeline), kept in sync by the fan-out service.
Commands Event log write-optimized View 1: current state View 2: search index New view (new feature) replay from start
CQRS: write once to the event log; derive any number of read-optimized, possibly denormalized views.

Concurrency control

  • Biggest downside of event sourcing and CDC: consumers are asynchronous, so a user may write and then not see it in a log-derived view (the read-your-writes problem).
  • Fix: update the view in the same transaction as the append (same store or distributed transaction), or use total order broadcast.
  • But logs also simplify concurrency: multi-object transactions often exist because one action changes data in many places. Design an event as a self-contained description of a user action, so the action is a single, easily atomic append.
  • If the log and state are partitioned the same way (an event for a customer in partition 3 only updates state partition 3), a single-threaded consumer needs no write concurrency control: the log fixes a serial order per partition. Events spanning partitions need more work (Chapter 12).

Limitations of immutability

  • Feasibility depends on churn. Mostly-append workloads are easy. High update/delete rates on a small dataset make history huge, cause fragmentation, and make compaction and GC performance crucial.
  • Sometimes data must really be deleted for administrative reasons: privacy rules after account closure, removal of erroneous data, containing a leak. Appending a "deleted" event is not enough; you must rewrite history. Datomic calls this excision; Fossil calls it shunning.
  • True deletion is hard (copies in SSDs, filesystems, immutable backups); it mostly makes data harder to retrieve.

Processing Streams

  • Streams come from user activity, sensors and database writes, and travel via direct messaging, brokers and event logs. Three things to do with one:
    1. Write it to a store (database, cache, index) for others to query; good for keeping a database in sync, especially if the stream consumer is its only writer. The streaming version of batch outputs.
    2. Push it to users: email alerts, push notifications, real-time dashboards; a human is the final consumer.
    3. Process input streams into output streams, possibly through a multi-stage pipeline ending in 1 or 2.
  • Option 3 code is an operator or job: reads input read-only, writes output append-only, and partitions and parallelizes as in batch.
  • The crucial difference: a stream never ends. Sorting is meaningless, so sort-merge joins cannot be used; and restarting from the beginning after a crash is not viable for a job running for years.

Uses of Stream Processing

Long used for monitoring: fraud detection (block a likely stolen card), trading on price rules, factory machine malfunctions, military signs of attack. These need sophisticated pattern matching.

Complex event processing

  • CEP (1990s): search streams for event patterns, much as a regex searches a string for character patterns.
  • Patterns are written in a declarative language like SQL or a GUI; the engine consumes inputs, keeps an internal state machine, and emits a complex event on a match.
  • Roles are reversed versus a database: a database stores data and treats queries as transient; CEP stores queries long-term and lets events flow past them.
  • Implementations: Esper, IBM InfoSphere Streams, Apama, TIBCO StreamBase, SQLstream. Samza is adding SQL for declarative stream queries.

Stream analytics

  • Focus on aggregations and statistics over many events rather than specific sequences:
    • Rate of an event type per time interval.
    • Rolling average of a value over a period.
    • Comparing to earlier intervals (trends; alerts on unusually high or low values versus the same time last week).
  • Computed over fixed intervals, e.g. average QPS and p99 response time over the last 5 minutes; a few minutes smooths second-to-second noise but stays timely. The interval is a window.
  • May use probabilistic algorithms: Bloom filters (set membership), HyperLogLog (cardinality), percentile estimators. Approximate but much less memory.
  • Frameworks: Apache Storm, Spark Streaming, Flink, Concord, Samza, Kafka Streams. Hosted: Google Cloud Dataflow, Azure Stream Analytics.

Maintaining materialized views

  • Keeping caches, indexes and warehouses current from a change stream is maintaining materialized views: an alternative, efficiently queryable view updated whenever the data changes.
  • Event-sourced state is one too. The window must reach back to the beginning of time, which clashes with window-oriented analytics frameworks; Samza and Kafka Streams support it via Kafka log compaction.

Search on streams

  • Search for individual events matching complex criteria such as full-text queries.
  • Examples: media monitoring matches news feeds against standing queries about companies or topics; real-estate sites notify users when a new listing matches their criteria. Elasticsearch's percolator is one option.
  • Conventional search indexes documents then queries them. Stream search inverts this: queries are stored and documents run past them, as in CEP.
  • With many queries, index the queries too, to narrow candidates.

Message passing and RPC

Message-passing systems (e.g. the actor model) use messages but are not usually considered stream processors:

Actor frameworksStream processing
Mainly for concurrency and distributed execution of communicating modulesMainly a data management technique
Communication often ephemeral and one-to-oneEvent logs are durable and multi-subscriber
Arbitrary patterns, including cyclic request/responseUsually acyclic pipelines; each stream is the output of one job from well-defined inputs
  • Crossover: Storm's distributed RPC interleaves user queries with stream events. Actor frameworks can process streams but often lack delivery guarantees on crashes.

Reasoning About Time

  • Windows like "the last five minutes" are tricky. A batch job crunches a year of history in minutes; it must use the timestamps in the events, not the machine clock. That also makes it deterministic: same input, same result.
  • Many stream frameworks window by the local clock, processing time. Simple, and fine if event-to-processing delay is negligible; it breaks with significant processing lag.

Event time versus processing time

  • Delays come from queueing, network faults, contention, restarts and reprocessing. They also reorder: a request to server A then one to B, but B's event reaches the broker first.
  • Analogy: the Star Wars films were released IV, V, VI (1977, 1980, 1983), then I, II, III (1999, 2002, 2005), then VII (2015). Episode number = event timestamp; viewing date = processing time.
  • Confusing them gives bad data: a rate counter redeployed and down for a minute processes the backlog on restart; by processing time this looks like a spike, though the real rate was steady.
By event time: steady rate By processing time: dip then false spike processor down backlog time
Figure 11-7: windowing by processing time creates artifacts when the processing rate varies.

Knowing when you're ready

  • With event-time windows you can never be sure all events for a window have arrived. Counting per minute: events for minute 37 trickle in while most now fall in 38 and 39. When do you close 37?
  • Time out after a quiet period, but some events may be buffered elsewhere or delayed by the network: stragglers. Two options:
    1. Ignore them (usually a small share); track dropped events as a metric and alert if it grows.
    2. Publish a correction with stragglers included; you may need to retract the earlier output.
  • A special message can declare "no more events with timestamp earlier than t," which consumers use to trigger windows. With many producers, each with its own threshold, consumers track each producer, which makes adding or removing producers trickier.

Whose clock are you using, anyway?

  • Events buffered at several points complicate timestamps. A mobile app used offline buffers events and sends them hours or days later; they look like extreme stragglers.
  • The meaningful time is the user interaction on the device clock, but device clocks can't be trusted (wrong by accident or on purpose). The server receive time is more accurate but less meaningful.
  • Fix: log three timestamps:
    1. When the event occurred (device clock).
    2. When it was sent to the server (device clock).
    3. When the server received it (server clock).
  • Timestamp 3 minus timestamp 2 estimates the device-server clock offset (assuming network delay is negligible); apply it to timestamp 1 (assuming the offset didn't change between occurrence and sending).
Device clock Server clock 1: occurred 2: sent 3: received offline: buffered hours offset = 3 - 2 true event time = 1 + offset
Logging three timestamps lets you estimate and correct the device clock offset.

Types of windows

  • Tumbling window: fixed length, each event in exactly one window. 1-minute: 10:03:00-10:03:59, then 10:04:00-10:04:59. Implement by rounding each timestamp down to the minute.
  • Hopping window: fixed length, overlapping for smoothing. 5-minute with 1-minute hop: 10:03:00-10:07:59, then 10:04:00-10:08:59. Implement as 1-minute tumbling windows aggregated over neighbors.
  • Sliding window: all events within some interval of each other. A 5-minute sliding window groups 10:03:39 and 10:08:12 (under 5 minutes apart), which fixed-boundary windows would split. Implement with a time-sorted buffer, evicting expired events.
  • Session window: no fixed duration; groups a user's events that occur close together, ending after inactivity (e.g. 30 minutes). Common in website analytics (sessionization).
events Tumbling Hopping overlap Sliding any span of length 5 min Session session 1 session 2 inactive gap
Window types: tumbling (fixed, disjoint), hopping (fixed, overlapping), sliding (relative to events), session (ends on inactivity).

Stream Joins

  • Streams need joins as batch does, made harder because new events can appear any time. Three types: stream-stream, stream-table, table-table.

Stream-stream join (window join)

  • Example: search trend detection. Log an event per search (query and results) and per click on a result; join them by session ID to compute click-through rate per URL. Advertising needs similar analysis.
  • The click may never come (abandoned search), or come seconds, days or weeks later; it may even arrive before the search due to network delay. Choose a window, e.g. join if at most one hour apart.
  • Embedding search details in clicks misses searches with no click, so it is not equivalent.
  • Implementation: keep state, e.g. all events in the last hour indexed by session ID. On each event, add it to its index and check the other; on a match emit "result clicked"; when a search expires unmatched, emit "results not clicked".

Stream-table join (stream enrichment)

  • Join activity events (with a user ID) to user profiles continuously: enriching the events.
  • A remote query per event is slow and may overload the database; instead keep a local copy (in-memory hash table or local disk index), like a map-side hash join.
  • Unlike batch's snapshot, the copy must stay current: subscribe to the profile database's CDC changelog too. It is really a stream-stream join where the table side's window reaches back to the "beginning of time" (newer records overwrite older) and the activity side may have none.

Table-table join (materialized view maintenance)

  • Twitter timeline: iterating over everyone a user follows at read time is too expensive, so keep a per-user timeline cache ("inbox"); reading is one lookup. Maintaining it requires:
    • User u tweets: add to the timeline of every follower of u.
    • A tweet is deleted: remove it from all timelines.
    • u1 follows u2: add u2's recent tweets to u1's timeline.
    • u1 unfollows u2: remove u2's tweets from u1's timeline.
  • Inputs: tweet events and follow events; the processor keeps each user's follower set. Equivalently, it maintains a materialized view of a query joining tweets and follows; timelines are a cache of its result, updated whenever either table changes:
SELECT follows.follower_id AS timeline_id,
  array_agg(tweets.* ORDER BY tweets.timestamp DESC)
FROM tweets
JOIN follows ON follows.followee_id = tweets.sender_id
GROUP BY follows.follower_id
  • (Footnote: treating streams as derivatives of tables and a join as a product, the change stream obeys the product rule (u·v)′ = u′v + uv′: tweet changes join current followers; follower changes join current tweets.)
Stream-stream search events click events state: last hourby session ID clicked / not Stream-table activity events profile CDC local profile DBwindow: all time enriched events Table-table tweet changes follow changes tweets + followerslatest state timeline changes
All three joins keep state built from one input and query it with events from the other.

Time-dependence of joins

  • Order of state-maintaining events matters (follow then unfollow differs from the reverse). Partitioned logs order within a partition but not across streams or partitions.
  • So which activity events join with the old profile and which with the new? If state changes over time, what point in time does the join use?
  • Example: invoice tax rates depend on country, product type and date of sale. When reprocessing history, join with the rate at the time of sale, not today's.
  • If cross-stream order is undetermined, the join is nondeterministic: rerunning on the same input can interleave differently and give different results.
  • Data warehouses call this a slowly changing dimension (SCD), often fixed by giving each version of the joined record a unique ID (a new ID per tax rate change, recorded on the invoice). The join becomes deterministic, but log compaction is impossible, since all versions must be kept.

Fault Tolerance

  • Batch restarts failed tasks and discards their output (immutable input, separate output files, visible only on success), so each record appears processed once: exactly-once semantics, more accurately effectively-once.
  • Streams can't wait for a task to finish, because a stream never finishes.

Microbatching and checkpointing

  • Microbatching (Spark Streaming): split the stream into small blocks, each a mini batch job. Batch size is typically around one second: smaller means more scheduling and coordination overhead; larger means longer delay before results appear.
  • It implies a processing-time tumbling window equal to the batch size.
  • Checkpointing (Apache Flink): periodically write rolling checkpoints of state to durable storage. A crashed operator restarts from the latest checkpoint and discards output since then. Checkpoints are triggered by barriers in the stream, like microbatch boundaries but without forcing a window size.
  • Both give exactly-once within the framework. Once output leaves it (database writes, external broker messages, emails), it can't be discarded; a restart repeats the side effect.
barrier barrier crash checkpoint output discarded restart from checkpoint
Flink-style checkpointing: barriers trigger state snapshots; after a crash, resume from the last one and discard later output.

Atomic commit revisited

  • All effects of processing an event must happen atomically, if and only if processing succeeds: downstream and external messages (email, push), database writes, operator state, and input acks (consumer offset moves). This is exactly-once via distributed transactions.
  • Efficient in restricted settings: Google Cloud Dataflow, VoltDB, planned for Kafka. Unlike XA they stay inside the framework rather than spanning technologies, and amortize overhead over several messages per transaction.

Idempotence

  • Goal: discard partial output of failed tasks so retries don't take effect twice. Besides distributed transactions, use idempotence.
  • An idempotent operation has the same effect done many times as once. Setting a key to a fixed value is idempotent; incrementing a counter is not.
  • Make an operation idempotent with metadata: Kafka messages have persistent, monotonically increasing offsets. Store the offset of the triggering message with each value written to an external database; then you can tell if an update was already applied. Storm's Trident state handling works similarly.
  • Assumptions: a restarted task replays the same messages in the same order (log brokers do this); processing is deterministic; no other node concurrently updates the same value.
  • On failover, fencing may be needed to block a node thought dead but still alive.
msg offset 42 replay: offset 42 Processor deterministic External DB value + last offset 42 42 seen: skip same order on replay, no concurrent writers, fencing on failover
Storing the triggering offset with each write makes a non-idempotent update safe to retry.

Rebuilding state after a failure

  • Windowed aggregates and join tables must be recoverable.
  • Option 1: keep state in a remote, replicated datastore; but a remote query per message is slow.
  • Option 2: keep state local and replicate it periodically; a recovering task reads the replica and resumes without loss.
    • Flink: periodic operator-state snapshots to durable storage such as HDFS.
    • Samza and Kafka Streams: send state changes to a dedicated log-compacted Kafka topic, like CDC.
    • VoltDB: process each input message redundantly on several nodes.
  • Option 3: rebuild from input, no replication: replay a short window's events, or rebuild a CDC-maintained local database copy from the log-compacted change stream.
  • No universal best: network may beat disk latency or match its bandwidth, and this shifts as technology evolves.

Summary

  • Stream processing is batch processing done continuously on unbounded input; brokers and event logs play the role of the filesystem.
  • AMQP/JMS broker: assigns and acks individual messages, deleting them after ack. Suits asynchronous RPC such as a task queue, where order doesn't matter and old messages are never reread.
  • Log-based broker: assigns each partition to one consumer, in fixed order; parallelism via partitions; consumers checkpoint offsets; messages stay on disk for rereading. Resembles replication logs and log-structured storage, and suits jobs producing derived state or streams.
  • Streams come from user activity, sensors and data feeds, and from database writes: capture the changelog via CDC or event sourcing; log compaction keeps a full database copy in the stream.
  • Consuming the change log keeps indexes, caches and analytics current, and replaying from the start builds fresh views.
  • Uses: event patterns (CEP), windowed aggregation (stream analytics), derived data (materialized views). Time is hard: processing time vs event time, and stragglers.
  • Joins: stream-stream (related events within a window, e.g. one user's actions within 30 minutes; may be a self-join), stream-table (enrich events from a changelog-maintained local copy), table-table (each change joins the other side's latest state, giving a stream of changes to the join's materialized view).
  • Exactly-once needs finer-grained recovery than discarding all output: microbatching, checkpointing, transactions or idempotent writes.
Chapter 12

The Future of Data Systems

The final chapter turns from how systems are to how they should be: the author's openly first-person proposals for applications that are robust, correct, evolvable and good for people, built from the ideas of all earlier chapters.

Key takeaways

  • No one tool fits every access pattern, so apps compose several systems; keeping them in sync is the hard part.
  • Choose a system of record, fix a total order of writes in a log, and derive indexes, caches and models from it (CDC or event sourcing).
  • Across heterogeneous systems, an async log with idempotent consumers beats XA distributed transactions: faults stay local.
  • Reprocessing history lets schemas evolve gradually and reversibly; one engine for batch and stream avoids the lambda architecture's duplication.
  • "Unbundling the database": org-wide dataflow is one big database; caches, indexes and views just move the boundary between the write path and the read path.
  • Correctness needs end-to-end measures, e.g. a client-generated request ID carried to the database.
  • Split consistency into timeliness (may lag) and integrity (must hold). Dataflow keeps integrity without coordination; many constraints can be checked late and fixed by apology.
  • Trust, but verify: audit data end to end. Engineers must also weigh the ethics of predictive analytics and tracking.

Data Integration

  • Every problem has several solutions with different trade-offs (log-structured vs B-tree vs column storage; single-leader vs multi-leader vs leaderless).
  • One product doing everything is likely poor at all of it; even "general-purpose" databases target a usage pattern.
  • Two challenges: map products to the circumstances they fit, and, since one dataset is used in many ways, stitch several tools together.

Combining Specialized Tools by Deriving Data

  • Typical pair: OLTP database + full-text search index. PostgreSQL's built-in search suits simple apps; serious search needs specialist tools, which make poor systems of record.
  • More copies follow: warehouses, batch/stream systems, caches, denormalized objects, ML and recommendation pipelines, change notifications.
  • "99% of people only need X" says more about the speaker than the tool; integration needs appear when you look at dataflow across the whole organization.

Reasoning about dataflows

  • Be explicit: where is data written first, and which representation derives from which?
  • Write to the system of record, capture changes with change data capture (CDC), apply them to the index in the same order. If CDC is the index's only input, the index is consistent with the source (barring bugs).
  • Dual writes from the app to both systems let concurrent writes land in different orders; nobody is in charge of ordering, so the systems can diverge permanently.
  • Funnel all input through one system that fixes a total order (state machine replication via total order broadcast). CDC vs event sourcing matters less than having one order.
  • Log-driven updates can be deterministic and idempotent, so fault recovery is easy.
Application Database system of record CDC log Search index Cache Warehouse writes one total order derived systems apply changes in log order; no dual writes
Derive every other representation from one ordered log of the system of record.

Derived data versus distributed transactions

Distributed transactionsLog-based derived data
OrderingLocks (2PL)Log order
Exactly-once effectAtomic commitDeterministic retry + idempotence
TimingUsually linearizable (read your own writes)Asynchronous; no such guarantee by default
  • XA works where people pay its cost, but has poor fault tolerance and performance; a better protocol is unlikely to be widely adopted soon.
  • Author's view: log-based derived data is the most promising integration approach, but "eventual consistency, deal with it" is not enough guidance. A middle ground comes in "Aiming for Correctness".

The limits of total ordering

  • Throughput: a total order needs one leader; partition the log beyond one machine and cross-partition order is ambiguous.
  • Geography: a leader per datacenter (sync cross-DC coordination is slow) leaves cross-DC events unordered.
  • Microservices: each service owns its state, so events from different services have no defined order.
  • Offline clients: local state updated immediately means clients and servers see different orders.
  • Total ordering is total order broadcast = consensus. Most algorithms assume one node handles the whole stream; scaling beyond one node and across regions is open research.

Ordering events to capture causality

  • Unrelated concurrent events can be ordered arbitrarily; updates to one object can be ordered by routing its ID to one partition.
  • Subtle case: a user unfriends their ex, then messages friends about the ex. With friends and messages stored separately, a notifier may see the message first and notify the ex. The notification is a join, with the timing problems of joins.
  • No simple fix. Starting points: logical timestamps (order without coordination, but recipients handle out-of-order events and extra metadata); log what the user saw with an ID that later events reference; conflict resolution (fine for state, useless for external side effects like notifications).
User Friends store 1. unfriend Message store 2. send message Notifier Ex arrives late arrives first wrong notify
Causal order lost across two stores: the notification is a join that sees the events in the wrong order.

Batch and Stream Processing

  • Integration means getting data into the right form in the right places; batch and stream processors do it, producing search indexes, materialized views, recommendations and metrics.
  • Core difference: unbounded vs finite input. Engines are converging: Spark does streams as microbatches; Apache Flink does batch on a stream engine. Performance differs (microbatching may do poorly on hopping or sliding windows).

Maintaining derived state

  • Batch is functional in flavor: deterministic pure functions, immutable inputs, append-only outputs. Streams add managed, fault-tolerant state.
  • Clear inputs and outputs aid fault tolerance and make org-wide dataflows easier to reason about.
  • Derived systems could update synchronously, but asynchrony is what makes log-based systems robust: faults stay local, whereas distributed transactions abort on any participant failure and spread it.
  • Cross-partition secondary indexes (term- or document-partitioned) are also most reliable and scalable when maintained asynchronously.

Reprocessing data for application evolution

  • Streams give low-delay updates; batch reprocesses history into new views.
  • Without reprocessing, schema evolution is limited to simple additions (optional field, new record type); with it, you can restructure into a completely different model.
  • Railways: after England standardized gauge in 1846, lines were converted by adding a third rail so both train types could run during the transition. It is costly, so odd gauges survive (BART).
  • Derived views allow gradual evolution: run old and new schemas as two views on the same data, shift a few users, grow the share, drop the old view. Each step is reversible, so you can move faster.
Event log Old view old schema New view reprocessed Users 95% 5%, growing each step reversible; drop old view at the end
Gradual migration: two views derived from the same data, traffic shifted step by step (percentages illustrative).

The lambda architecture

  • Append immutable events (like event sourcing) and derive read-optimized views, using two systems in parallel: batch (Hadoop MapReduce) for a corrected view and stream (Storm) for a fast approximate one.
  • Rationale: batch is simpler and less buggy; stream processors were seen as less reliable; streams can use approximate algorithms, batch exact ones.
  • It popularized views derived from immutable events and reprocessing. Problems:
    • Same logic in two frameworks; tools like Summingbird help with code, not with operating two systems.
    • Outputs must be merged at read time: easy for tumbling-window aggregates, hard for joins, sessionization or non-time-series.
    • Full reprocessing is costly, so batch runs incrementally (e.g. hourly), reintroducing stragglers and cross-batch windows and making it as complex as the stream layer.

Unifying batch and stream processing

One system for both, which needs:

  • Replay of history through the live engine (log-based brokers; stream processors reading HDFS).
  • Exactly-once semantics: output as if no faults, discarding failed tasks' partial output.
  • Event-time windowing, since processing time is meaningless on replay (Apache Beam's API, run on Flink or Google Cloud Dataflow).
Lambda Events Batch (exact, slow) Stream (approx) Merge Reads Unified History + live One engine replay, exactly-once, event time One view
Lambda runs two pipelines and merges them; a unified engine handles reprocessing and live events with one codebase.

Unbundling Databases

  • Databases, Hadoop and operating systems all store, process and query data ("information management"); Hadoop is somewhat like a distributed Unix. Differences remain: filesystems struggle with 10 million small files; databases handle 10 million records easily.
  • Unix: thin, low-level hardware abstraction (pipes, byte files). Relational databases: high-level abstraction (SQL, transactions) hiding disk structures, concurrency and recovery; a short query draws on optimizers, indexes and replication.
  • The tension dates to the early 1970s; the author reads NoSQL as Unix-style low-level abstraction applied to distributed OLTP. This section tries to combine both.

Composing Data Storage Technologies

  • Database features seen in the book: secondary indexes, materialized views (precomputed query cache), replication logs, full-text indexes.
  • Chapters 10 and 11 built the same things outside databases: batch-built search indexes, view maintenance, CDC to derived systems.

Creating an index

  • CREATE INDEX scans a consistent snapshot, sorts the indexed values, writes the index, applies the backlog of writes since the snapshot, then keeps it current.
  • That is like bootstrapping a follower replica or CDC with an initial snapshot: the database reprocesses existing data into a new derived view.

The meta-database of everything

  • An organization's dataflow looks like one huge database: batch, stream and ETL jobs act as index and view maintenance; processors are elaborate triggers and stored procedures; derived systems are index types run by different teams on different machines.
Federated database (polystore): unify readsUnbundled database: unify writes
IdeaOne query interface over many enginesPlug stores together (CDC, event logs) so every change reaches every place
ExamplePostgreSQL foreign data wrapperIndex maintenance unbundled across technologies
TraditionRelational: integrated, high-level, complex insideUnix: small tools, uniform low-level API (pipes), composed by a shell
GapNo answer for syncing writesNo high-level composition language yet
Federated: unify reads Unbundled: unify writes Query interface Store A Store B Store C Event log Database Index Cache reads flow up writes flow down
Federation and unbundling are two sides of composing diverse stores into one system.

Making unbundling work

  • Federated reads mean mapping data models: manageable. Syncing writes is harder, so that is the focus.
  • Distributed transactions across heterogeneous stores are, in the author's view, the wrong tool. Inside one system transactions are fine (some stream processors use them for exactly-once); across technologies with no standard protocol, an ordered log with idempotent consumers is simpler and more robust.
  • Loose coupling, twice over: (1) system level: a slow or failed consumer is buffered by the log and catches up later, while synchronous transactions escalate local faults; (2) human level: teams build and run components independently behind clear interfaces, and logs are strong enough (durable, ordered) yet general.

Unbundled versus integrated systems

  • Databases remain necessary: processor state, serving outputs, and specialized engines such as MPP warehouses.
  • Every extra system brings a learning curve and operational quirks; an integrated product may perform better and more predictably on its workload. Building for scale you don't need is premature optimization.
  • Unbundling is about breadth, not depth. If one product meets all requirements, use it.

What's missing?

  • No unbundled equivalent of the Unix shell: a declarative language for composing stores and processors.
  • Wish: mysql | elasticsearch as the unbundled CREATE INDEX, indexing everything and applying all future changes with no custom code. Also declarative materialized views as caches (even recursive graph queries); early research like differential dataflow.

Designing Applications Around Dataflow

  • Also called "database inside-out" (after the author's 2014 talk): a design pattern, not a grand architecture, drawing on Oz, Juttle, Elm (FRP), Bloom; "unbundling" is Jay Kreps's term.
  • Spreadsheets recompute dependent cells when inputs change; data systems should likewise refresh indexes, views and aggregates automatically. VisiCalc did this in 1979; data systems must add fault tolerance, scale, durability and integration across teams and technologies.

Application code as a derivation function

  • Each derived dataset has a transformation: secondary index (pick and sort values); full-text index (language detection, segmentation, stemming, spelling, synonyms, inverted index); ML model (features and statistics from training data); cache (data shaped for the UI, rebuilt when the UI changes).
  • Indexes are built in (CREATE INDEX); full-text needs tuning; ML feature engineering is very app-specific. Custom derivations need custom code, where triggers, stored procedures and UDFs have been an afterthought.

Separation of application code and state

  • Databases are poor hosts for app code: weak dependency management, version control, rolling upgrades, monitoring, network calls. Mesos, YARN, Docker and Kubernetes do that job better. Let some parts specialize in storage, others in running code.
  • Stateless services keep logic out of the database and state out of the app ("separation of Church and state", a joke about Alonzo Church's lambda calculus having no mutable state).
  • The database then acts as a shared mutable variable you can read but not subscribe to; observing changes means polling (the observer pattern is hand-built). Change streams are only emerging.

Dataflow: Interplay between state changes and application code

  • Code reacts to state changes in one place by producing state changes elsewhere (like change-log subscriptions, actors, 1980s tuple spaces). Unbundling applies trigger- and index-style updates to caches, search, ML and analytics via stream processing.
  • This is not async job queuing: order matters (views from one log must agree; many brokers reorder on redelivery; dual writes are out) and no message may be lost (one loss desyncs a view forever; in-memory actor state dies with the machine).
  • Stable ordering and fault-tolerant processing are demanding but far cheaper than distributed transactions. Operators compose like piped Unix tools: streams of state changes in, streams out.

Stream processors and services

  • Microservices (synchronous REST) win on organizational scalability. Stream operators share that, but communicate through one-way async streams, with better fault tolerance and performance.
  • Exchange-rate example: microservices query a rate service per purchase; dataflow subscribes to rate updates in advance and stores them locally, so a purchase does a local lookup. Faster, and survives the rate service failing: the most reliable network request is none. RPC becomes a stream-table join. (A local cache in a microservice must be kept fresh by polling or subscribing, which is dataflow.)
  • The join is time-dependent: reprocessing later needs the historical rate either way.
Microservices (RPC) Purchase service Rate service request per purchase down = fail Dataflow (stream-table join) Rate updates Local rates DB Purchase processor Purchase events local no network
Replacing a synchronous call with a subscription: the rate is joined from a local copy.

Observing Derived State

  • Write path: eager, precomputed work that updates every derived dataset as data arrives (like eager evaluation). Read path: work done only when a user asks (like lazy evaluation).
  • The derived dataset is where they meet (Figure 12-1), trading write-time work against read-time work.
Document updates Log Search index User queries write path (eager) read path (lazy) paths meet here
Figure 12-1, simplified: in a search index, writes (document updates) meet reads (queries).

Materialized views and caching

  • Search index: writes update entries for every term; reads look up terms and apply AND/OR logic.
  • No index: cheap writes, grep-style full scans on read. Precompute all queries: trivial reads but infinite work and storage (finite but exponential in terms for a finite corpus). Cache common queries: a materialized view that must update when new documents match.
  • Caches, indexes and materialized views shift the boundary between write and read paths. This is the Chapter 1 Twitter timeline example, where celebrities got a different boundary: full circle.
more read work more write work No index grep all docs Index work on both Cache common materialized view Precompute all infinite where the derived dataset sits = the write/read boundary
Indexes, caches and materialized views move the boundary between write-time and read-time work.

Stateful, offline-capable clients

  • The stateless-client, authoritative-server model is so common it feels inevitable, but single-page apps and mobile apps now hold local state and storage.
  • Offline-first apps work against an on-device database and sync in the background, a big win on slow cellular links.
  • On-device state is a cache of server state: pixels are a materialized view of client model objects, which replicate remote state.

Pushing state changes to clients

  • A loaded page is a stale cache until reload or polling (RSS is basic polling). Server-sent events and WebSockets let servers push changes.
  • This extends the write path to the end user: initial state via the read path, then a change stream. Offline gaps are handled like log consumer offsets; each device subscribes to a small stream.

End-to-end event streams

  • Elm and React/Flux/Redux already manage client state from event streams, like event sourcing. Let servers push events into that pipeline and changes flow from one device to another's UI in under about a second.
  • Messaging and games already work this way. Others don't because request/response is baked into databases, libraries and protocols; few stores offer subscriptions.
  • The author argues for moving to publish/subscribe dataflow for responsiveness and offline support: design for subscribing to changes, not only querying.
Device A user action Event log Stream processors Derived state Device B UI updates push (WebSocket / SSE) end-to-end write path, about 1 s
Extending the write path to end-user devices: subscribe, don't just query.

Reads are events too

  • Usually writes go via the log and reads hit the store directly. Some processors expose queryable state, becoming simple databases.
  • Go further: send reads as events through the same processor, which emits results to an output stream. That is a stream-table join; reads route to the right partition as joins copartition by key.
  • A one-off read joins and is forgotten; a subscription is a persistent join with past and future events.
  • Logging reads records what users saw (e.g. a shop's shipping estimate and stock status before a purchase), aiding causality and provenance, at extra storage and I/O cost (open research). If reads are already logged for operations, it's a small step.
Write events Read events Stream operator state partition stream-table join Read results one-off read: join then forget; subscribe: persistent join
Reads as events: queries are joined against state inside the stream processor, and can be logged for provenance.

Multi-partition data processing

  • Overkill for single-partition reads, but useful for queries spanning partitions, reusing stream routing and joins. Storm distributed RPC counted who saw a URL on Twitter (union of tweeters' follower sets).
  • Fraud checks join a purchase with reputation scores for IP, email, billing and shipping addresses, each partitioned differently.
  • MPP databases do this internally and are simpler if they fit; queries-as-streams helps beyond off-the-shelf limits.

Aiming for Correctness

  • Stateless services recover by fix-and-restart; stateful systems remember mistakes (more or less) forever.
  • Transactions (atomicity, isolation, durability) have been the correctness tool for about four decades, but are weaker than they look (weak-isolation confusion). Some systems drop them for messier models (leaderless replication); "consistency" is poorly defined.
  • It is hard to know if an app is safe at a given isolation level or replication config; simple designs pass at low concurrency and fail under faults. Kyle Kingsbury's Jepsen tests found big gaps between claimed and actual guarantees.
  • Serializability and atomic commit work but usually cost single-datacenter deployment and limited scale and fault tolerance. Transactions stay, but are not the last word.

The End-to-End Argument for Databases

  • Serializable transactions don't stop an app bug from writing wrong data or deleting data. This is why the book favors immutable, append-only data, though immutability alone is not a cure-all.

Exactly-once execution of an operation

  • On failure you drop the message (loss) or retry (possible duplicate). Processing twice is corruption: double charges, double counts.
  • Exactly-once (effectively-once): the final effect equals a fault-free run despite retries. Best tool: idempotence, which may need extra metadata (operation IDs applied) and fencing on failover.

Duplicate suppression

  • TCP sequence numbers dedupe and reorder packets, but only within one connection. If the network fails after COMMIT is sent but before the reply, the client can't tell if it committed.

Example 12-1, a non-idempotent transfer:

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance + 11.00 WHERE account_id = 1234;
UPDATE accounts SET balance = balance - 11.00 WHERE account_id = 4321;
COMMIT;
  • A retry on a new connection can move $22 instead of $11. The textbook atomicity example is not actually correct; real banks don't work this way.
  • 2PC lets a coordinator reconnect and resolve in-doubt transactions, but the browser-to-server hop remains: a POST succeeds, the reply is lost on a weak link, the user resubmits. Post/Redirect/Get doesn't help on timeout. To server and database it's a new request.
Browser POST, retry App server Database UNIQUE(id) HTTP hop TCP / txn hop dedupe here only dedupe here only request ID carried end to end
Per-hop duplicate suppression misses user retries; only an end-to-end operation ID catches them.

Operation identifiers

  • Generate a unique ID (UUID in a hidden form field, or a hash of the form fields) and pass it down to the database, allowing at most one operation per ID.

Example 12-2, deduplicating with a unique request ID:

ALTER TABLE requests ADD UNIQUE (request_id);
BEGIN TRANSACTION;
INSERT INTO requests
  (request_id, from_account, to_account, amount)
  VALUES('0286FDB8-D7E1-423F-B40B-792B3608036C', 4321, 1234, 11.00);
UPDATE accounts SET balance = balance + 11.00 WHERE account_id = 1234;
UPDATE accounts SET balance = balance - 11.00 WHERE account_id = 4321;
COMMIT;
  • A duplicate ID fails the INSERT and aborts the transaction. Uniqueness constraints hold even at weak isolation, unlike app-level check-then-insert.
  • The requests table is an event log: balance updates could be derived downstream, exactly once, again keyed by request ID.

The end-to-end argument

  • Saltzer, Reed and Clark (1984), paraphrased: some functions can only be done fully and correctly by the applications at the endpoints; a lower layer can offer only a partial version, useful for performance.
  • Duplicate suppression: TCP and stream-processor exactly-once can't stop a user resubmitting; an ID passed from client to database can.
  • Checksums: Ethernet, TCP and TLS miss software bugs and disk corruption; you need end-to-end checksums. Encryption: WiFi passwords and TLS each cover one segment; only end-to-end encryption and authentication cover all.
  • Low-level features still reduce higher-level problems (HTTP needs TCP ordering); they just aren't sufficient.

Applying end-to-end thinking in data systems

  • Apps need their own end-to-end measures such as duplicate suppression, and no good abstraction yet hides them.
  • Transactions collapse many failures into commit or abort, a big simplification but not enough. They are expensive across heterogeneous systems, and skipping them means hand-rolled fault tolerance that, the author suspects, is usually wrong, losing or corrupting data.
  • Wanted: abstractions for app-specific end-to-end correctness that also perform and operate well at scale.

Enforcing Constraints

  • Focus on uniqueness: usernames, emails, file names, seat bookings. Similar: non-negative balances, no overselling stock, no overlapping room bookings.

Uniqueness constraints require consensus

  • Choosing among concurrent conflicting requests is consensus. Usually a single leader decides; tolerating its failure brings consensus back.
  • Scale by partitioning on the unique value (request ID; hash of username).
  • Async multi-master replication can accept conflicting writes, so it's out. Rejecting violations immediately requires synchronous coordination.

Uniqueness in log-based messaging

  • A log is total order broadcast; one partition is consumed by a single thread, so with the log partitioned by the unique value the processor decides deterministically who came first:
  1. Each username claim is appended to the partition for hash(username).
  2. The processor checks a local table of taken names, then emits success or rejection to an output stream.
  3. The client waits on the output stream for its answer.
  • Same as linearizable storage via total order broadcast; scales by adding partitions. General rule: route potentially conflicting writes to the same partition and process them sequentially, with arbitrary validation logic (like Bayou in the 1990s).
Client 1: "ann" Client 2: "ann" Partition hash("ann") Processor single thread local: taken names 1: success 2: rejected clients watch the output stream
Uniqueness via a partitioned log: all claims on one name go to one partition and are decided in order.

Multi-partition request processing

  • Example 12-2 may touch three partitions (request ID, payee, payer). Atomic commit across them forces a total order with all their other transactions and hurts throughput.
  • Same correctness without atomic commit:
  1. The client assigns a request ID; the transfer is appended to a partition chosen by that ID.
  2. A processor emits a debit for payer A (partitioned by A) and a credit for payee B (partitioned by B), both carrying the request ID.
  3. Downstream processors dedupe by request ID and apply the balance changes.
  • Logging the request as one message avoids a two-partition atomic commit: single-object writes are atomic almost everywhere.
  • A crashed step-2 processor resumes from its checkpoint, may re-emit, but deterministically emits the same instructions, which step 3 dedupes.
  • To block overdrafts, add a processor partitioned by payer that validates before requests enter the log.
Client req ID Request log by req ID Processor deterministic Debit A part. by A Credit B part. by B Acct A dedupe Acct B dedupe 1 atomic write no atomic commit across partitions; req ID makes retries harmless
A multi-partition transfer as two differently partitioned stages instead of a distributed transaction.

Timeliness and Integrity

  • Transactions are typically linearizable; async stream stages are not. A client may wait on an output stream, but correctness doesn't depend on waiting; waiting only reports the outcome.
  • "Consistency" conflates two things:
TimelinessIntegrity
MeaningUsers see up-to-date stateNo loss, no contradictory or false data; derived views correct
If violatedTemporary; wait and retryPermanent; needs explicit check and repair
ExamplesLinearizability (CAP), read-after-writeIndex matches table; ACID "consistency"
Slogan"Eventual consistency""Perpetual inconsistency"
  • Integrity usually matters far more. A card purchase missing from the last 24 hours is normal lag; a statement that doesn't add up, or money charged but never paid to the merchant, is an integrity failure.
"Consistency" Timeliness up-to-date reads violated: eventual Integrity no loss, no false data violated: perpetual can relax must keep
Dataflow systems decouple the two: weak timeliness, strong integrity.

Correctness of dataflow systems

  • ACID bundles timeliness and integrity; event dataflow decouples them: no timeliness unless consumers wait, but integrity is central, preserved by exactly-once delivery and dedup.
  • Integrity without distributed transactions comes from: (1) the write as a single atomic message (event sourcing); (2) all other updates via deterministic derivation; (3) a client request ID through every stage; (4) immutable messages and periodic reprocessing to recover from bugs.

Loosely interpreted constraints

  • Strict uniqueness needs consensus on one node per partition, but many apps accept weaker forms:
    • Duplicate username or seat: apologize and ask one party to choose again: a compensating transaction.
    • Oversold stock: reorder, apologize, discount; you need this already for, say, forklift damage.
    • Airlines and hotels overbook deliberately and compensate; weather and strikes need apology processes anyway.
    • Overdrafts: fee and repayment; daily withdrawal limits bound risk.
  • Apologies are often cheap (correction email, refund); ATM cash is not. Accepting that cost is a business decision. If acceptable, write optimistically and check afterwards, but validate before hard-to-undo actions.
  • These apps need integrity (no lost bookings, matching credits and debits), not timely constraint enforcement, much like write-conflict resolution.

Coordination-avoiding data systems

  • Since dataflow keeps integrity without atomic commit or cross-partition coordination, and many constraints can be loose, systems can avoid coordination yet keep strong integrity, with better performance and fault tolerance.
  • Example: multi-leader across datacenters with async replication; each region runs independently; weak timeliness, strong integrity.
  • Serializable transactions still help at small scope for derived state; XA isn't needed. Add coordination only where required (strict constraints before unrecoverable actions).
  • Coordination cuts inconsistency apologies but can add outage apologies; you can't reach zero, so find the sweet spot.

Trust, but Verify

  • Reasoning rests on a system model: crashes, power loss and network faults happen; lost fsynced data, corrupted memory or a wrong CPU multiply are assumed not to. Reality is probabilistic, not binary.
  • Disks rot; network corruption can slip past TCP checksums. The author saw crash reports explainable only by memory bit-flips; rowhammer flips bits in healthy memory via access patterns. Rare, but possible.

Maintaining integrity in the face of software bugs

  • Bugs evade low-level checksums. The author has seen MySQL fail a uniqueness constraint and PostgreSQL's serializable level allow write skew; less mature software is worse.
  • App code gets far less testing than databases and often misuses foreign keys and uniqueness constraints. ACID consistency assumes bug-free transactions; misuse (unsafe weak isolation) voids it.

Don't just blindly trust what they promise

  • Corruption is eventually inevitable, so detect it: checking integrity is auditing, prized in finance because mistakes are expected.
  • HDFS and Amazon S3 continually read back files, compare replicas and move files between disks to catch silent corruption. Read your data to know it's there; test restoring backups.

A culture of verification

  • Few systems continually audit themselves; the author hopes for self-validating systems.
  • ACID culture bred blind trust. When NoSQL normalized weaker guarantees and less mature storage spread, blind trust continued, now more dangerous.

Designing for auditability

  • Transaction logs show what changed, not why; the deciding app logic was transient.
  • Event sourcing records input as one immutable event and derives state deterministically: same log + same code = same state.
  • Explicit dataflow gives clear provenance: hash the event log, rerun derivations (or a redundant one in parallel) and compare. It also enables reproducing exact circumstances: time-travel debugging.
Event log immutable hash check Derivation Rerun derivation Derived state Fresh result Equal?
Auditing a dataflow system: hash the log, re-derive the state, compare.

The end-to-end argument again

  • Without full trust in components, check integrity periodically, or corruption surfaces only after costly downstream damage.
  • Check end to end: verifying a whole pipeline implicitly covers every disk, network, service and algorithm on it.
  • Like automated tests, continuous audits catch bugs early and let you change systems and adopt new storage with confidence, so you move faster.

Tools for auditable data systems

  • Few systems prioritize auditability. Audit tables are hard to keep trustworthy; signing a log with a hardware security module proves no tampering, not that the right transactions went in.
  • Cryptocurrencies, blockchains and ledgers (Bitcoin, Ethereum, Ripple, Stellar) are, from a data view, distributed databases whose replicas, run by mutually untrusting parties, check each other and agree via consensus.
  • The author doubts their Byzantine fault tolerance claims, finds proof of work extraordinarily wasteful, and notes Bitcoin's low throughput (mostly political and economic causes), but finds the integrity checking interesting.
  • Merkle trees (trees of hashes) efficiently prove a record is in a dataset; certificate transparency uses them for TLS certificates. Such auditing may spread if made scalable with low overhead.

Doing the Right Thing

  • Every system has a purpose and consequences beyond it; engineers must consider them and choose what world to build.
  • Many datasets are about people; treat them with humanity, respect and dignity.
  • Ethics codes (the ACM Software Engineering Code of Ethics) exist but are rarely applied, so privacy is often handled cavalierly. Technology is not good or bad in itself; its use is, and the responsibility is ours.

Predictive Analytics

  • Forecasting weather or disease differs from predicting whether a person reoffends, defaults or files costly claims: these hit individuals directly.
  • Organizations default to "no" when in doubt, since a missed opportunity is cheap. Someone labeled risky (rightly or wrongly) may then be shut out of jobs, travel, insurance, housing and finance: "algorithmic prison", without proof of guilt or real appeal.

Bias and discrimination

  • Algorithms aren't inherently fairer or worse than people, but they infer rules from data; the patterns are opaque, and biased input is learned and amplified.
  • Laws bar using protected traits (ethnicity, age, gender, sexuality, disability, beliefs), yet proxies leak them: in segregated areas, postal code or IP address predicts race.
  • Expecting fair output from biased data is unrealistic ("money laundering for bias"). Prediction extrapolates the past; a better future needs human moral imagination. Data and models should be tools, not masters.

Responsibility and accountability

  • Who is accountable when an algorithm errs: a self-driving car crash, discriminatory credit scoring? Can you explain your model to a judge?
  • Credit scores use relevant facts (your borrowing history) and allow corrections; ML scoring uses wider, opaque inputs. A score asks "how did you behave?"; prediction asks "how did people like you behave?", which stereotypes (location as a proxy for race and class) and leaves misbucketed people little recourse.
  • Statistics can be right overall and wrong for individuals (an 80-year average life expectancy doesn't mean you die at 80).
  • Blind faith in data is dangerous. We need accountable, transparent algorithms that don't reinforce bias, and ways to fix mistakes. Analytics can target aid to those in need, or help predatory firms sell high-cost loans and worthless degrees.

Feedback loops

  • Recommenders can create echo chambers breeding stereotypes, misinformation and polarization, already seen in elections.
  • Self-reinforcing loops: employers using credit scores in hiring push a worker hit by misfortune into a spiral: missed payments, lower score, no job, deeper poverty, lower score.
  • Systems thinking (the whole system, people included) predicts many such effects: does it amplify inequality or counter injustice? Beware unintended consequences.
Misfortune Missed payments Lower score Fewer job offers Poverty score used in hiring
The book's credit-score-in-hiring example of a self-reinforcing feedback loop.

Privacy and Tracking

  • Data the user explicitly enters for a service makes the user the customer. Tracking as a side effect gives the service interests that may conflict with the user's.
  • Some tracking helps users: click data for ranking, "people who liked X also liked Y", A/B tests.
  • In ad-funded services, advertisers are the customers: tracking deepens, retention lengthens, profiles grow. The author calls this surveillance.

Surveillance

  • Try replacing "data" with "surveillance" in common phrases ("surveillance warehouse", "surveillance scientists"); the book jokes about its own title too.
  • We have built the largest mass-surveillance infrastructure ever; IoT puts internet-connected microphones (phones, TVs, assistants, baby monitors, toys) in nearly every room, often with terrible security. Repressive regimes could only dream of this; here corporations collect it.
  • "Nothing to hide" works only for those aligned with power. Benign-seeming uses blur with predictive analytics: car insurance tied to trackers, health cover tied to fitness devices. Smartwatch motion data can even reveal typed passwords.

Consent and freedom of choice

  • "Users agreed to the terms" fails: they barely understand what is collected, policies obscure it, and derived datasets merging everyone's data are beyond understanding. Data about one user also exposes non-users.
  • The exchange is one-way and non-negotiable; the service sets the terms.
  • Opting out is costly when a service is essential to social life (smartphones, Facebook, Google) and network effects apply. Only the privileged can afford to decline; for others surveillance is inescapable.

Privacy and use of data

  • "Privacy is dead" is false: privacy is a decision right, the freedom to choose what to reveal to whom.
  • Surveillance transfers that right to the collector ("trust us"). Companies keep findings secret to avoid seeming creepy; intimate facts surface indirectly, e.g. ad targeting by illness, so users lose agency even without reidentification.
  • Firms manage perceptions rather than intrusiveness, often poorly (a true fact can still trigger painful memories). Expect data to be wrong or inappropriate and build ways to handle that; such judgment is human.
  • Privacy settings govern what other users see, not what the service does internally. This mass transfer of privacy rights is historically unprecedented: surveillance used to be manual and costly, and trusted relationships (doctor, attorney) are legally constrained.

Data as assets and power

  • Behavioral "data exhaust" is really the core asset of ad-funded services; the app is a lure. Data brokers secretly buy, infer and resell personal data; startups are valued by "eyeballs".
  • Governments obtain it through deals, coercion, compulsion or theft; bankrupt firms sell it; breaches are frequent. Critics call it a "toxic asset".
  • Weigh benefits against misuse by criminals, foreign intelligence, insiders, future management or future governments; installing tools that could enable a police state is poor civic hygiene.
  • Watching others while avoiding scrutiny is power; tech firms gain much covert power outside public oversight.
Users Free service the lure Behavioral data (asset) Advertisers tracked breaches governments bankruptcy sale "data exhaust" is really the core asset, and a toxic one
In an ad-funded service the behavioral data is the asset, and it carries risks if it leaks or is compelled.

Remembering the Industrial Revolution

  • Data defines the information age as industry defined the Industrial Revolution, which brought growth but also pollution, harsh labor and child labor until safeguards (environmental, workplace, food rules) arrived. Costs rose; society gained.
  • The book cites Bruce Schneier likening data to the information age's pollution and privacy to its environmental challenge, on which future generations will judge us. The author: we should make them proud.

Legislation and self-regulation

  • The 1995 European Data Protection Directive limits collection to specified, explicit, legitimate purposes and to data adequate, relevant and not excessive for them.
  • That clashes with Big Data's collect-everything, explore-for-new-uses philosophy, so its effectiveness is doubtful; new rules are in development.
  • Companies call regulation a drag on innovation, partly fairly (medical data could save lives); balance is hard.
  • Needed: a culture shift. Treat users as humans, not metrics; self-regulate; educate users. Individual control of data is like a national park: unprotected, it suffers a tragedy of the commons. Surveillance is not inevitable.
  • Concrete starts: purge data once it is no longer needed (solvable despite immutability) and enforce access with cryptographic protocols, not just policy.

Summary

  • No single tool serves every use case, so apps compose systems, integrated by batch processing and event streams that carry changes between them.
  • Some systems are systems of record; indexes, views, ML models and summaries are derived through transformations.
  • Asynchronous, loosely coupled derivation keeps a fault in one area from spreading.
  • Expressing dataflow as transformations aids evolution and recovery: change or fix the code, rerun it over the full input.
  • This mirrors database internals, hence unbundling: compose loosely coupled components into an application.
  • Derived state can be observed downstream, all the way to end-user devices, for live-updating, offline-capable UIs.
  • Strong integrity scales with async processing: end-to-end operation IDs for idempotence, asynchronous constraint checks; clients wait or risk an apology. More scalable and robust than distributed transactions, and closer to real business processes.
  • Dataflow plus async checks avoids most coordination, keeping integrity and performance across regions and faults. Audits verify integrity.
  • Data can also harm: hard-to-appeal decisions, discrimination, exploitation, normalized surveillance, exposed intimate details, breaches, unintended consequences.
  • Engineers are responsible for working toward a world that treats people with humanity and respect.

Condensed from Designing Data-Intensive Applications by Martin Kleppmann (O'Reilly, 2017). Parts I-III (complete book), 12 chapters.