Scaling microservices
FTGO's load is not flat: the Saturday lunch rush brings many times the orders of a quiet afternoon, and the business keeps growing. This chapter shows how to give each service and its data more capacity, or more resilience, without building for scale you will never need.
key idea / coordinator service / good path in progress / watch out problem / failure neutral
In chapter 21 FTGO built a pipeline that takes any service from commit to production quickly and safely, building each artifact once and promoting it. That left one problem open: production load changes by the hour and grows by the year, and the services must keep up.
How does FTGO handle more orders than its services and databases can take today? By the end you can name the four axes of scaling, choose between them, scale reads and writes, place and invalidate caches, set autoscaling rules, and treat each scaling change as an experiment.
Lunch rush: why scale, and along which axis
FTGO now operates in many countries. Every Saturday at lunch, Order Service response times climb, and the primary database that stores orders shows growing write contention: transactions wait for locks held by other transactions. Each month the peak is a little higher. Someone says "we need to scale", but nobody agrees on what that means.
There are two different reasons to scale. One is performance: handle more load, or answer faster. The other is robustness: keep working when a part fails. Some techniques help with one goal and not the other, so name the goal before picking a tool.
Abbott and Fisher's Scale Cube gives three axes: duplicate the same thing, partition work by a data key, or split work by type. Add a fourth, a bigger machine. Every scaling technique in this chapter is one of these four, or a mix.
| Axis | Helps load? | Helps robustness? | Main cost |
|---|---|---|---|
| Vertical | Yes, quickly | Hardly | Money; a ceiling on machine size |
| Horizontal duplication | Yes, if work spreads easily | Yes | More infrastructure; needs a way to spread work |
| Data partitioning | Yes, especially writes | Little on its own | Hard key choice; cross-shard queries |
| Functional decomposition | Yes, per workload | Opens the door | Biggest code change; more services |
Every axis adds cost or complexity, and they differ hugely in effort. The sections below follow FTGO through them, cheapest first.
The quickest relief: a bigger box
The cheapest experiment needs no code change at all.
The order database runs on a virtual machine with 2 cores and 8 GB of memory, and its CPU is pinned at lunch. The team needs relief by next Saturday, not next quarter.
Move to a faster CPU, more memory and better I/O. On virtual machines or a public cloud this takes minutes and rarely needs code changes, so try it first.
FTGO upsizes the primary database several times. It buys years. But growth projections say the next resize will not be enough, and a single machine, however large, is still a single point of failure.
Cost grows faster than capacity, new machines add cores rather than faster ones (and the software may not use them), and there is a ceiling. Vertical scaling also does nothing for robustness. For that, FTGO needs more than one copy.
Copy the service: horizontal duplication
Where one box runs out, several identical boxes can share the work.
Restaurant Service runs as a single instance. At lunch it serves menus to every customer browsing restaurants, and its CPU saturates. When it restarts for a deployment, no one can see a menu for a minute.
Run several copies of the same service and spread the work across them, with a load balancer for requests or a queue for background work. Consumers still see one service: the balancer or queue is part of its logical boundary.
The balancer uses health checks (chapter 17) to drop unhealthy instances. Instances come and go, so callers find them through DNS or a service registry (service discovery, chapter 4). For background work, the same idea is competing consumers: several instances of Notification Service read from one queue, and adding an instance raises throughput.
Duplication is simple because the code seldom changes. Avoid designs that need sticky sessions, where a user must always reach the same instance: they spread load unevenly and lose state when that instance dies.
More instances cost more infrastructure, and the approach relies on the balancer, broker or replicas working as designed. Applied to a monolith, it copies everything even when only one part is hot. And every copy still writes to the same database, so FTGO's write contention on orders is untouched.
Split the writes: data partitioning
Duplication copies all the data to every node. To scale writes, each node must hold only part of it.
The order database is already the biggest machine FTGO can buy. Read replicas would not help, because the contention is on writes: every new order, every status change, all on one primary.
Apply a function to a key on each request, such as a hash of the consumer id. The result picks the partition, or shard, that holds that data. Each shard handles only its share of the writes.
Partitioning can live in the data store itself (Cassandra partitions rows, Kafka partitions topics), or in front of dedicated service instances, which helps when each instance keeps an in-memory cache of its share. The hard part is choosing the key.
| Benefit | Limit |
|---|---|
| Scales write-heavy workloads well | A bad key is painful to change; one company needed three days of downtime to re-partition |
| Smaller blast radius for maintenance; rollouts one region at a time | One failed shard fails its share of requests (a quarter, with four shards) |
| Keeps data inside a jurisdiction (geographic shards) | Queries across shards must visit each shard or use a separate read store |
FTGO considers one shard per country and rejects it: the company plans to keep expanding, and a new partition for every country would make each launch expensive. It partitions orders by a hash of a unique id instead.
The key is hard to choose and harder to change, and cross-shard queries get slow. Partitioning alone does not add robustness, so combine it with duplication: replicate each shard so it survives a node failure. And partitioning still scales the whole service, even if only one workload inside it is hot.
Scale only the hot part: functional decomposition
The fourth axis is the one this whole course is about.
Order handling is the hot workload. As long as it shares a process and a database with menus and delivery, as it did in FTGO's monolith (chapter 1), scaling orders means scaling everything, on the same hardware, in the same language, with the same database.
Extract a piece of functionality into its own service so it can scale on its own. Each workload can then get right-sized hardware, be switched off when idle, or move to a better-suited language or database.
The axes combine. Once Order Service stands alone, FTGO can partition it by region and duplicate it inside each region, without touching any other service.
The goal is not to use every axis, only to know them. Try the cheap, low-impact ones first (vertical, then duplication), and leave decomposition for later unless it also solves a people problem. For FTGO it does: splitting out delivery and menus also lets a growing engineering organization give each team its own service (chapter 2 covers where to cut).
Decomposition is the biggest code change of all and leaves more services to run. And every service still ends at a database, where reads and writes behave very differently under load.
Reads and writes scale differently: replicas and CQRS
Copying data for reading is easy. Accepting more writes is the hard part.
After lunch, customers open "my orders" to track their delivery, and restaurants refresh their order lists. These reads now outnumber writes many times over, and the Order Service database runs at 90% CPU (an illustrative figure) serving them, which slows down new orders too.
Keep one primary for all writes and add read-only copies, the replicas, for reads. The service routes reads to replicas internally, so callers see no change.
| Problem | Try first | Then |
|---|---|---|
| Read-heavy | Read replicas behind a balancer | Caching, or CQRS if reads need a different shape |
| Write-heavy | Bigger database machine | Shard by key; consider a database built for your write pattern |
| One hot workload | Move it to its own service and database | Scale that service on its own |
When a database cannot keep up with writes, teams often end up changing database technology. A bigger box is the fastest relief while they evaluate options.
When reads need a different shape from writes, not just more copies, the next step is CQRS (chapter 11): a command model for writes and a separate query model, kept up to date by a projection. The two run as separate processes and scale apart.
Replicas and CQRS views are eventually consistent, so a read can be slightly stale. Each replica is another database to pay for. And many reads ask for the same answer again and again; serving each one from a database, even a replica, is wasted work.
Skip the work entirely: caching, and how stale is too stale
The fastest request is one that never reaches the origin.
To price each new order, Order Service asks Restaurant Service for the menu. During the lunch rush, that is the same few hundred menus fetched thousands of times a minute. Restaurant Service and its database spend most of their capacity giving identical answers, and when Restaurant Service is down, no one can order.
Keep a copy of a recent result close to where it is needed. A cache cuts latency, shields a busy origin, and, if you keep serving stale entries, lets a service keep answering while the origin is down. It always trades freshness for speed.
Chapter 11 covered caching for queries. From the scaling point of view, there are two decisions: where the cache lives, and how entries become invalid.
A client-side cache inside Order Service saves the network call and keeps orders flowing if Restaurant Service is down. A server-side cache inside Restaurant Service helps every caller. A shared cache such as Redis gives all clients one consistent copy at the price of one network hop. A request cache stores the whole answer to a specific request: fastest, but useful only for that exact request.
| Invalidation | How it works | Watch out |
|---|---|---|
| TTL | Entry valid for a set time (HTTP Cache-Control, Expires) | Blunt: stale until expiry. A shorter TTL means more origin calls |
| Conditional GET | Send If-None-Match with the ETag; 304 Not Modified means unchanged | Still a round trip; saves rebuilding the response |
| Notification | Origin publishes a change event, such as MenuRevised | Needs a broker; send heartbeats so silence is not mistaken for no change |
| Write-through | Cache and origin updated together | Practical mainly on the server side |
| Write-behind | Update the cache first, origin later | Data loss risk; unclear source of truth. Rare in microservices |
Caches also stack, and their staleness adds up. The golden rule is to cache in as few places as possible.
Expires: Never header. Those pages stuck in customers' browser caches, which the team could not clear; the only fix was to change the URLs. Know the full path from source to screen, including CDNs and browsers.Every cache is stale data you must reason about, an invalidation strategy you must be able to explain, and one more thing to run. Caches, replicas and copies also all need the right number of instances at the right time, and FTGO's load at 4 a.m. is a small fraction of its load at noon.
Follow the load: autoscaling
Fixed capacity is either too much at night or too little at lunch.
FTGO sizes Order Service for the Saturday peak and pays for idle instances the rest of the week. Then a big football final and a rainy evening arrive together, orders go far beyond the usual peak, and there is still not enough.
When provisioning and deployment are fully automated (chapter 19, chapter 21), let the platform add and remove instances. Predictive scaling follows a known daily pattern; reactive scaling responds to observed load or failure.
- Autoscale for failure first ("always run at least five instances"), while you collect load data.
- Know how fast you can scale up. If a spike gives you two minutes of warning and a new instance takes ten to be ready, keep spare capacity.
- Test your rules with load tests; otherwise you learn how they behave in production.
- Scale down slowly. Extra capacity for a while is cheaper than too little.
- Beware forgotten rules: a minimum-instances rule will respawn the instances you are trying to stop for maintenance.
Autoscaling rules are code that runs only under stress, so they need testing like any other code. And like every technique in this chapter, they add moving parts. Each one must earn its place.
Scale by experiment, and expect to start again
Scaling adds complexity: every new service, shard, replica or cache is another thing to run, secure and observe.
After a slow Saturday, an FTGO architect proposes sharding every database, adding Redis in front of every service and moving everything to CQRS. Nobody has measured where the time goes. Months later the system is much harder to run, and the real bottleneck, a missing index on the orders table, is still there.
Treat each scaling change as an experiment. Observe to find the real bottleneck, form a hypothesis about one change, load test a baseline and the change, then keep it or revert it.
The architecture that gets you started may not carry you to the next level. Gilt, an online fashion retailer, ran a Rails monolith for two years before load forced a redesign. That is no reason to build for huge scale on day one: you would spend months on load that may never come, and learn too late whether anyone wants the product. Needing to re-architect for scale is a sign of success, not failure.
Experiments take time and a realistic load test environment, and sometimes the answer is a large redesign. For FTGO, the largest redesign is still ahead: most of the business logic and data still lives in the original monolith.
Patterns in this chapter
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Vertical scaling | A machine runs out of CPU, memory or I/O | Rising cost, a hard ceiling, still one point of failure |
| Horizontal duplication (load balancing, competing consumers) | One instance cannot take the load or is a single point of failure | More infrastructure; shared database writes untouched |
| Data partitioning (sharding) | Write contention on one database | Hard-to-change key; cross-shard queries; no robustness alone |
| Functional decomposition | A hot workload forces scaling of everything around it | Biggest code change; more services to run |
| Read replicas | Reads overload the primary database | Stale reads; more databases to pay for |
| CQRS | Reads need a different shape and scale from writes | High complexity and cognitive load |
| Caching with an invalidation strategy | Identical requests waste origin capacity; origin outages block callers | Stale data; staleness adds up across nested caches |
| Autoscaling (predictive and reactive) | Fixed capacity is idle at night and short at peak | Rules to test; scale-up lag needs spare capacity |
| Scale by experiment | Scaling work aimed at guessed, not measured, bottlenecks | Load tests and time; sometimes a redesign |
Recap
- Scale either for load or for robustness, and choose the technique by the goal: vertical scaling, horizontal duplication, data partitioning or functional decomposition, cheapest first.
- Duplication behind a balancer or queue scales and protects stateless work, but every copy still writes to the same database.
- Partitioning scales writes when the key spreads load evenly and stays stable, and it needs duplication to add robustness.
- Reads scale with replicas and caches; writes need bigger machines, sharding or a better-suited database, and CQRS is a powerful but hard last step.
- Cache in as few places as you can, with an invalidation strategy you can explain, because nested caches add up their staleness.
- Autoscale for failure first, test the rules, scale down slowly, and treat each scaling change as a measured experiment.
Quick check
Show answer
Add a read replica, or cache the order history. Both are quick and low risk, and they leave the write model untouched. CQRS solves the problem too, but it is one of the hardest options and raises the cognitive load on the team; save it for reads that need a different shape.
Show answer
Names are unevenly distributed, and the distribution varies by country, so one shard gets far more load than the others. Names also change, which would move a consumer between shards. Use a unique consumer id, hashed.
Show answer
Up to two minutes: Order Service may refresh its copy from a server cache that is already one minute old. Nested caches add their staleness, which is why you cache in as few places as possible, or invalidate by notification for data like prices.
Everything in this part assumed FTGO's services already exist and can be built, deployed and scaled one by one. In reality, FTGO still runs a large monolith in production, and the services have to be carved out of it while it keeps taking orders.
Next: 23 Refactoring a monolith: the strangler application →