Part 07›
✎

09. Scaling the System#

Level: Practitioner · Reading time: 15 min · Exercise: 45 min Prerequisites: Deploying a Model, where inference appears as a function without state.

In one sentence: After this chapter you can tell which parts of an ML feature need to scale, do the arithmetic that shows by how much, and name the standard building blocks for each part.

Why this matters#

The head of support asks: "Can triage handle ten times the volume?"

The honest answer needs arithmetic, not a purchase order. Ten times 50,000 tickets a day is still under six requests a second at peak. One copy of the classifier handles that.

The same question about the LLM version has a different answer. Each request holds an accelerator chip, a processor built for model arithmetic, for about a second. This chapter shows how to reach both answers with numbers.

The core idea#

Scalability is the ability of a system to handle more work when you give it more resources.

Kästner gives three ways to get capacity (chapter 12): use a more efficient algorithm, use a faster machine, or use more machines. The first two work for a while. Then they grow expensive and hit physical limits. Real scalability almost always comes from the third: distribution, splitting storage and computation across many machines.

A kitchen with one cook who cannot keep up has the same three answers: a better recipe, a faster cook, more cooks. The comparison breaks at coordination. Cooks see each other and talk. Machines coordinate over a network that is slow and that can fail without a visible sign. So "more machines" costs design as well as money.

Where ML features need scale#

Kästner names four places:

Where What grows What you need
Training data Rows to store, clean and encode Distributed storage and data processing
Telemetry Logged predictions and outcomes Distributed storage and data processing
Inference Requests per second, each holding hardware Many copies of a stateless service behind a load balancer
Training Days of accelerator time for one job Splitting one job across machines

For scale, his reference point is Google Photos, which reported in 2020 that it held more than 4 trillion photos for over a billion users and received 28 billion new photos a week, about 46 thousand uploads a second. His back-of-envelope arithmetic shows why one machine cannot serve that. At 3 megabytes per photo, uploads arrive at 135 gigabytes per second. A disk writes about 100 megabytes per second, so storing them alone takes about 1,400 disks at once. A fast object-detection model needs 20 to 50 milliseconds per image, so keeping up takes at least 2,780 parallel processes. Run an updated model over all stored photos with one process and the job lasts 2,536 years. You will probably never need that scale. The ideas are the same at any size.

The building blocks to recognize#

Storage. The book names three common forms of data (chapter 12). Relational data sits in tables with a fixed shape, described by a schema, and is queried in SQL. Document data sits in key-value collections, often as JSON, with nested objects and little enforced structure. Unstructured data is plain files such as logs, with no index, so finding something means reading everything. Two ideas distribute any of them:

Kästner's observation for ML is that slightly stale or inconsistent data is usually acceptable as noise, which makes scaling much easier.

Two storage designs are worth recognizing. A data warehouse is a separate database that holds data cleaned into one uniform shape for analysis. It is updated in batches, say nightly, and mostly read. Filling it is called extract, transform, load (ETL). A data lake keeps raw data as it arrived, on the bet that it will be useful later in ways nobody can predict yet. Without notes on what is there, a lake becomes what Kästner calls a data swamp or a data graveyard.

Processing. Four strategies cover most needs:

Strategy How it works Optimized for Example
Service Answers each request as it arrives Low response time The triage inference service
Batch Runs one long computation over all the data and writes the results Throughput The nightly training run
Stream Processes events from a queue as they arrive Throughput with little delay Scoring each new comment within seconds
Lambda architecture Batch recomputes everything on a schedule. Stream keeps the results fresh in between. Services answer queries Both A weekly full retrain, with small updates between runs

Three ideas in the book explain the shape of this table. Batch jobs move the computation to the data, because moving a model is cheaper than moving petabytes. A stream cannot promise that every event is handled exactly once. The developer chooses at-least-once, which may repeat work, or at-most-once, which may lose events. Tagging a photo twice is harmless. Charging a print order twice is not. And the speed layer of the lambda architecture works with approximations. Kästner notes that a model updated incrementally can be worse than one retrained from scratch, because it is hard to unlearn a changed training example. It is still better than a stale model.

Figure 1. The lambda architecture: a batch layer and a speed layer feed one serving layer.

flowchart LR
    D["New data"] --> Q["Queue of all events"]
    Q --> B["Batch layer recomputes everything on a schedule"]
    Q --> S["Speed layer updates results with approximations"]
    B --> M["Serving layer holds both results"]
    S --> M
    M --> A["Services answer queries"]

A query is answered from two results merged: the exact batch result and the approximate stream result for whatever arrived since the last batch run.

Training. Training a large model is a distributed job in its own right. For GPT-3, released in 2020, Kästner reports an estimate of 355 years of sequential training, done instead on 10,000 GPUs with 285,000 CPU cores behind them, at an estimated cost of nearly 5 million US dollars for one run. Kästner's picture of distributed training is the parameter server. Each worker machine learns from a slice of the data. A central server collects and merges the adjustments. Workers send only the changes above a threshold, because all of GPT-3's parameters would amount to 700 gigabytes after every batch. Merging partial updates adds noise, one reason training is not reproducible (chapter 06).

Caching. A cache keeps the result of an expensive computation and reuses it. Kästner uses it in three places: predictions for inputs that repeat (chapter 07), feature vectors (the feature store in the same chapter), and values derived from a data lake, such as aggregates, kept in a database so that the raw data is not processed again (chapter 12). A feature built on an LLM caches the same way, for example the numerical form of a stored document. A cache goes stale the moment the model changes. So every cache needs an invalidation rule, such as the model version in the cache key.

How it works, step by step#

Capacity planning is estimating the load, the cost per unit and the needed resources before you build.

  1. Write the load: the average and the peak, per second. Then write, for each function, how late its result may be. In the photo service a user expects an upload to appear at once and will not notice if search lags for a new image, so only the first needs a service.
  2. Measure the cost of one unit on one copy: requests per second, memory, bytes per logged event.
  3. Multiply into budgets for compute, storage and network.
  4. Find the bottleneck. Kästner notes that it is often the database.
  5. Take the cheap options first: a more efficient model, a faster machine, a cache.
  6. Distribute what is left. Services without state scale by adding copies. Data scales by partitioning and replication. Big jobs scale through batch or stream processing.
  7. Leave the door open. Even if you delay the infrastructure, design so that machines can be added later.

Worked example#

The script needs Python 3.10 or newer and nothing else.

# capacity.py — back-of-envelope load for the triage feature
import math

TICKETS_PER_DAY, PEAK_FACTOR = 50_000, 10
PEAK_PER_SECOND = TICKETS_PER_DAY / 86_400 * PEAK_FACTOR   # 86,400 seconds per day
BYTES_PER_LOGGED_REQUEST = 2_000

for name, capacity in [("classifier", 100), ("LLM", 1)]:   # requests per second per copy
    copies = math.ceil(PEAK_PER_SECOND / capacity)
    print(f"{name:10} needs {copies} instance(s) at peak ({PEAK_PER_SECOND:.1f} req/s)")
print(f"telemetry: {TICKETS_PER_DAY * BYTES_PER_LOGGED_REQUEST / 1e9:.2f} GB per day")

Run python capacity.py. The output:

classifier needs 1 instance(s) at peak (5.8 req/s)
LLM        needs 6 instance(s) at peak (5.8 req/s)
telemetry: 0.10 GB per day

What to observe:

What changes for LLM and agent systems#

LLM inference is the scaling problem most teams now meet.

For an agent, one task can last minutes and make dozens of model calls. A single request that waits for an answer no longer fits. Put tasks in a queue, let a worker handle each one, and keep state so that an interrupted task resumes. Cap the steps and the spending per run. A loop in an agent is a scaling incident. The structure is in The Anatomy of an Agent.

What the practitioners say#

Pitfalls#

  1. Scaling before measuring. Fix: the load and the capacity of one copy, written down.
  2. Scaling the whole system for one bottleneck. Fix: find the slow part and scale that.
  3. A cache without an invalidation rule. Fix: the model version in the cache key.
  4. A design that cannot add machines later. Fix: keep components stateless where you can, even before you need copies.
  5. Forgetting that telemetry grows. Fix: bytes per event, times events per day, times retention.

Try it#

Write a one-page capacity note for one feature that contains a model.

Include:

  1. The average and peak load, per second.
  2. The capacity of one copy: requests per second and memory.
  3. The three budgets: compute, storage, network.
  4. The bottleneck.
  5. The first thing you would change if the load grew tenfold.

You are done when every number is either a measurement with its source or a guess labeled as one, and the note says whether the feature needs more than one machine.

Stretch goal: find one expensive computation in the feature that a cache could remove, and write the cache's invalidation rule.

Key takeaways#

Self-check#

  1. Name the three ways to get more capacity, and say why the third is usually the real answer.
  2. How do partitioning and replication differ? - A. Partitioning copies data to several machines, while replication splits it across them. - B. Partitioning splits data across machines, while replication copies it to several of them. - C. Partitioning speeds up reads, while replication speeds up writes. - D. Partitioning applies to training data, while replication applies to telemetry.
  3. Which processing strategy answers each request as it arrives, and which is built for throughput over a large snapshot of data?
  4. A cache returns an answer that was computed with last week's model. What was left out?
  5. A feature peaks at 8 requests a second, and one copy handles 40. How many copies do you run, and why might the answer be two?
Show answers 1. A more efficient algorithm, a faster machine, more machines. The first two grow expensive and hit physical limits. Adding machines has no such ceiling. 2. B. Partitioning divides the data so that different parts sit on different machines. Replication stores the same data on several machines so that one can fail. 3. A service answers each request as it arrives. Batch processing is built for throughput over a large snapshot. 4. An invalidation rule. The cache key must include the model version, or the cache must be cleared whenever the model changes. 5. One copy covers the load. Two cover the failure of one copy.

Sources#

Next#

→ Planning for Operations, because a system built to scale still needs someone to watch it, and to know what to do at three in the morning.