Designing Data-Intensive ApplicationsParts I-III (complete book) · condensed, chapter by chapter
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.

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