Chapter 22 of 27 · Part 9: Deployment and scaling

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

Where we are

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.

This chapter

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

Problem

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.

Solution · Name the goal, then pick an axis

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.

Two goals, four axes Performance more load, lower latency Robustness survive failures Vertical scaling bigger machine Horizontal duplication more copies of the same thing Data partitioning split work by a data key Functional decomposition split work by type: microservices Scale Cube (Abbott and Fisher) plus a fourth axis, vertical scaling.
AxisHelps load?Helps robustness?Main cost
VerticalYes, quicklyHardlyMoney; a ceiling on machine size
Horizontal duplicationYes, if work spreads easilyYesMore infrastructure; needs a way to spread work
Data partitioningYes, especially writesLittle on its ownHard key choice; cross-shard queries
Functional decompositionYes, per workloadOpens the doorBiggest code change; more services
Cost

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.

Problem

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.

Solution · Vertical scaling

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.

Vertical scaling and its limits Small VM 2 cores, 8 GB Bigger VM 16 cores, 64 GB Hardware limit no larger box exists Limits you will meet: more cores, not faster cores; software may not use them; still one point of failure; cost grows faster than capacity Bigger machines also make room for databases of newly extracted services.

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

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.

Problem

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.

Solution · Horizontal duplication

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.

Load balancing across instances Consumers Load balancer health checks Restaurant #1 Restaurant #2 Restaurant #3 Database Balancer drops unhealthy nodes. Avoid sticky sessions if you can.

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.

Competing consumers Work queue notifications Notifier #1 Notifier #2 Notifier #3 Email / SMS sent Competing consumers: add instances to raise 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.

Cost

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.

Problem

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.

Solution · Data partitioning (sharding)

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.

Choosing a shard by key Request consumer id 7281 Partition fn hash(id) mod 3 Partition 1 Partition 2 Partition 3 own database own database own database Callers never see the partitioning: it is an internal detail of the service.

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.

Getting the key right Poor key: family name A-M / N-Z Better key: unique customer id A-M few names N-Z most names Shard 1 Shard 2 Uneven load, and name changes move people. Even spread, stable over time. Surname distributions are very skewed in some countries.
BenefitLimit
Scales write-heavy workloads wellA 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 timeOne 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.

Cost

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.

Problem

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.

Solution · Functional decomposition

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.

Extract a workload, then scale it Monolith order, menu, delivery extract Remaining system Order service scales alone x3 copies, then shard Extraction unlocks the other axes for just the hot workload.

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.

Three axes on one service Region EU Region US Order #1 Order #2 Orders database Order #1 Order #2 Orders database Order service: extracted, partitioned by region, duplicated inside each region.

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).

Cost

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.

Problem

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.

Solution · Read replicas

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.

Read replicas offload the primary Service routes internally Primary all writes Read replica 1 Read replica 2 writes reads (dashed) Replicas are eventually consistent: a read can be slightly stale.
ProblemTry firstThen
Read-heavyRead replicas behind a balancerCaching, or CQRS if reads need a different shape
Write-heavyBigger database machineShard by key; consider a database built for your write pattern
One hot workloadMove it to its own service and databaseScale 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.

CQRS: separate models for reads and writes Client Command model writes Query model reads Write store Read store projection separate processes can scale apart CQRS is an internal choice of the service; callers do not see it.
CQRS and event sourcing are hard. Capable teams struggle with them, and both raise the cognitive load on everyone who touches the service. If you are only read-constrained, try a read replica first. See chapter 11 for CQRS views and chapter 10 for event sourcing.
Cost

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.

Problem

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.

Solution · Cache

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.

Where to cache Four places to cache a restaurant menu Order svc needs prices Restaurant svc origin of menus Client-side Shared (Redis) Server-side Request cache inside Order svc one copy, one hop inside Restaurant whole answer no network call consistent for all helps all callers fastest, narrowest Client-side saves the network call and helps robustness; server-side helps every consumer.

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.

InvalidationHow it worksWatch out
TTLEntry valid for a set time (HTTP Cache-Control, Expires)Blunt: stale until expiry. A shorter TTL means more origin calls
Conditional GETSend If-None-Match with the ETag; 304 Not Modified means unchangedStill a round trip; saves rebuilding the response
NotificationOrigin publishes a change event, such as MenuRevisedNeeds a broker; send heartbeats so silence is not mistaken for no change
Write-throughCache and origin updated togetherPractical mainly on the server side
Write-behindUpdate the cache first, origin laterData 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.

The golden rule: cache in as few places as possible Origin price changes Server cache TTL 1 min: 1 min old Client cache TTL 1 min: 2 min old Nested caches add their staleness. The client thinks it is at most one minute behind.
Cache poisoning, a side story: at another company, a bug let some old pages go out with an 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.
Cost

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.

Problem

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.

Solution · Autoscaling

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.

Predictive and reactive scaling Load through the day Predicted: 11:15 up, 14:30 down Spike: react FTGO lunch: a daily curve to predict, plus spikes (a big match, a rainy day) to react to.
Cost

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.

Problem

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.

Solution · Scale by experiment

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.

Scale by experiment Observe real bottleneck? Hypothesis one change Load test baseline, change Measure keep or revert Repeat. Optimize for problems you have, not ones you might have.

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.

Cost

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

PatternProblem it solvesWhat it costs
Vertical scalingA machine runs out of CPU, memory or I/ORising 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 failureMore infrastructure; shared database writes untouched
Data partitioning (sharding)Write contention on one databaseHard-to-change key; cross-shard queries; no robustness alone
Functional decompositionA hot workload forces scaling of everything around itBiggest code change; more services to run
Read replicasReads overload the primary databaseStale reads; more databases to pay for
CQRSReads need a different shape and scale from writesHigh complexity and cognitive load
Caching with an invalidation strategyIdentical requests waste origin capacity; origin outages block callersStale data; staleness adds up across nested caches
Autoscaling (predictive and reactive)Fixed capacity is idle at night and short at peakRules to test; scale-up lag needs spare capacity
Scale by experimentScaling work aimed at guessed, not measured, bottlenecksLoad tests and time; sometimes a redesign

Recap

Quick check

After lunch, FTGO's Order Service database sits at 90% CPU, almost all of it serving "my orders" reads. What do you try first, and why not CQRS?
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.

A team proposes sharding FTGO's consumers by the first letter of their family name. What goes wrong?
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.

Restaurant Service caches menus for one minute, and Order Service caches what it gets for another minute. A restaurant raises a price. How long can Order Service charge the old price?
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.

Still open

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 →