# Building scalable backends

A practical guide to backend scalability, from load balancing and caching to queues, database replicas and sharding, circuit breakers and tail latency, with the tips I wish I had learned earlier.

<FramedImage src="https://assets.crossxr.me/blog/blog6.png" alt="Building scalable backends" />

Scalability is often confused with speed. They are related, but they are not the same thing. A fast system answers one request quickly. A **scalable** system keeps answering quickly, and at a predictable cost, as the number of requests, users and records grows by ten or a hundred times.

Most of the work is not exotic. It is a small set of ideas applied carefully: keep services stateless, cache what is read often, move slow work off the request path, spread data across machines, expect failure, and measure the right things. This post walks through each one, with the practical details that tend to matter in production.

## Start with the numbers

Before choosing an architecture, it helps to know roughly what you are building for. A few back-of-the-envelope numbers go a long way:

* **Requests per second**, at average and at peak. Peaks are usually several times the average, and you have to survive the peak.
* **Read-to-write ratio.** A read-heavy system scales very differently from a write-heavy one.
* **Data size and growth.** How much you store today, and how fast it grows.
* **Latency budget.** How long a user is willing to wait, and how that time is split across the calls a request makes.

It also helps to keep a rough sense of how long things take. Reading from memory takes around a hundred nanoseconds. A round trip inside a data centre is in the region of half a millisecond. A round trip between continents takes tens to hundreds of milliseconds. Those orders of magnitude explain most caching and placement decisions.

<Tip title="Find the bottleneck first">
  Scaling the wrong component is expensive and changes nothing. Profile real
  traffic, find the one resource that saturates first (CPU, memory, database
  connections, a single slow query), and fix that. Then measure again, because
  the bottleneck will move.
</Tip>

## Scale out, not just up

There are two ways to add capacity. **Scaling up** means a bigger machine. It is simple and often the right first step, but it has a ceiling and a single point of failure. **Scaling out** means more machines of the same size behind a load balancer. It has no hard ceiling and survives the loss of any one machine.

<ScaleOut />

Scaling out only works if any instance can serve any request. That means the application tier should be **stateless**: no user sessions in local memory, no files written to local disk that another request will need. Anything that must persist goes to a shared store such as a database, a cache or object storage.

The load balancer then does three jobs. It spreads traffic, it runs **health checks** and stops sending requests to instances that fail them, and it gives you a single stable address while instances come and go. On top of that, an **autoscaler** adds and removes instances based on a signal like CPU usage, request rate or queue depth.

<Tip title="Make instances disposable">
  Treat every instance as something that can be killed at any moment. If
  replacing one loses data or logs users out, it is holding state it should not
  hold. Disposable instances make autoscaling, deploys and failure recovery all
  work the same way.
</Tip>

## Cache what is read often

The cheapest request is the one that never reaches your database. Most applications read the same data far more often than they change it, which makes caching one of the highest-leverage tools available.

<CacheHit />

The most common pattern is **cache-aside**: the application checks the cache first, and on a miss it reads from the database and writes the result into the cache. Every entry gets a **time to live (TTL)** so stale data eventually ages out, and important writes can delete the matching key so the next read fetches fresh data.

Caching happens at several layers, and each one shields the next: a CDN at the edge for static and public content, an in-memory store like Redis for application data, and the database's own buffer cache underneath.

<Tip title="Add jitter to TTLs">
  If thousands of keys are written at the same time with the same TTL, they also
  expire at the same time, and the database gets hit by all of the misses at
  once. Adding a small random offset to each TTL spreads expirations out. For a
  single very hot key, let one request refill it while the others wait, instead
  of all of them racing to the database.
</Tip>

## Move slow work off the request path

Not everything a user triggers has to happen before they get a response. Sending an email, resizing an image, generating a report or calling a slow third-party API can all happen in the background.

<QueueDrain />

A **message queue** sits between the part of the system that accepts work and the part that does it. The API validates the request, puts a job on the queue and responds immediately. **Workers** consume jobs at a steady pace. When traffic spikes, the queue grows instead of the database falling over, and the depth of the queue becomes a clean signal for how many workers you need.

Queues also change the failure model. Most provide **at-least-once** delivery, which means a job can occasionally be delivered twice. Jobs that fail repeatedly should move to a **dead-letter queue** where someone can inspect them, rather than retrying forever.

<Tip title="Make every job idempotent">
  Assume every job will run twice at some point. Use an idempotency key, such as
  an order ID, and record that it has been processed, so a second run does
  nothing. It is much easier to design this in from the start than to add it
  after a customer is charged twice.
</Tip>

## Get the most out of one database

The application tier is usually the easy part to scale. The database is where most real bottlenecks end up, because it holds the one thing you cannot simply copy: state that has to stay correct. Before adding machines, it pays to make a single database do far more.

**Indexes.** Without an index, finding matching rows means reading the whole table. With the right one, the database follows a B-tree down to the rows it needs in a handful of page reads.

<IndexSeek />

Indexes speed up reads at the cost of slower writes and more storage, so add them for the queries you actually run. Column order in a composite index matters too. An index on `(user_id, created_at)` serves queries that filter by `user_id`, or by `user_id` and a date range, but not queries that filter by `created_at` alone.

<Tip title="Read the query plan">
  `EXPLAIN`, or `EXPLAIN ANALYZE` in PostgreSQL, shows how the database will
  actually run a query: which indexes it uses, how many rows it expects to read
  and where the time goes. A sequential scan over a large table on a hot path is
  usually the first thing to fix.
</Tip>

**Query shape.** The most common performance bug in application code is the **N+1 query**: one query to load a list, then one more query for every item in it. It looks fine with ten rows in development and falls over with ten thousand in production.

<Tip title="Batch instead of looping">
  ORMs make N+1 queries easy to write by accident through lazy loading. Load
  related data with a join or a single `WHERE id IN (...)` query instead. A
  request that makes hundreds of database calls stands out immediately in a
  trace.
</Tip>

**Connections.** Opening a database connection is expensive, and each one uses memory on the server.

<Tip title="Watch database connections">
  Every application instance opens connections to the database, and databases
  handle a limited number of them well. When you scale out the app tier,
  connection count grows with it. Use a pooler between the application and the
  database before it becomes an outage.
</Tip>

**The right model for the job.** A relational database is a strong default: transactions, constraints and flexible queries cover most needs. Some workloads fit better elsewhere, such as a key-value store for sessions and counters, a search engine for full-text search, a time-series database for metrics or a columnar store for analytics. Each extra store is another system to run and keep in sync, so add one for a clear workload, not by default.

**Keep hot data small.** Tables that only ever grow make indexes larger, backups slower and migrations riskier. Archive old rows, or partition large tables by time, so the data you query every day stays small enough to live in memory.

## Scale the data layer

When one well-tuned database is still not enough, the next steps are spreading reads across copies and splitting writes across machines. This is where scaling gets difficult, because data has to stay correct while it is spread out.

<DataScale />

When reads become the problem, add **read replicas**. The primary handles every write and streams changes to the replicas, which serve reads. Replication is usually asynchronous, so a replica can be slightly behind. For flows where a user must see their own change immediately, read from the primary right after a write.

When writes become the problem, you need to **partition** the data, often called **sharding**. Each shard owns a slice of the rows, chosen by a **shard key**. A good shard key spreads load evenly and keeps the data a query needs on a single shard.

<Tip title="Choose the shard key like it is permanent">
  Changing a shard key later means moving most of your data. Pick one that
  queries almost always include, such as a tenant or user ID, and check that no
  single value will be far larger than the rest. A few very large customers on
  one shard create a hot partition that no amount of hardware fixes evenly.
</Tip>

## Design for failure

At scale, something is always failing: a disk, a network link, a dependency, a deploy. The question is not whether a component will fail, but whether that failure stays local or spreads.

<CircuitBreaker />

A few patterns do most of the work:

* **Timeouts on every network call.** Without one, a slow dependency ties up your threads and connections until you fail too.
* **Retries with exponential backoff and jitter.** Retry transient failures, wait longer each time, and randomise the wait so clients do not retry in lockstep.
* **Circuit breakers.** When a dependency keeps failing, stop calling it for a while and fail fast with a fallback, then test it again with a single request.
* **Bulkheads.** Give different workloads separate pools of resources, so one misbehaving feature cannot exhaust capacity for everything else.
* **Graceful degradation.** Decide in advance what the product does when a non-critical dependency is down, such as hiding recommendations instead of failing the whole page.

<Tip title="Retries can make an outage worse">
  If every layer retries three times, one failing call at the bottom can turn
  into dozens of calls. That extra load can keep a struggling service down.
  Retry at one layer, cap retries with a budget, and never retry errors that
  will not succeed on a second attempt.
</Tip>

## Measure the tail

You cannot scale what you cannot see. The common starting point is four signals, often called the golden signals: **latency**, **traffic**, **errors** and **saturation**.

For latency, averages are misleading. What users feel is the distribution, and the slow end of it matters most.

<LatencyTail />

The **p50**, or median, tells you what a typical request looks like. The **p99** tells you what the slowest one percent look like, and at scale one percent is a lot of people. Define targets on percentiles, often as **service level objectives (SLOs)**, and alert when they are at risk rather than when an average drifts.

<Tip title="Fan-out makes the tail everyone's problem">
  If one page load calls 100 backend services in parallel and waits for all of
  them, the page is only as fast as the slowest call. Even if each service is
  slow only 1% of the time, about 63% of page loads will hit at least one slow
  call. That is why tail latency, not average latency, decides how a large
  system feels.
</Tip>

Distributed **tracing** completes the picture by following a single request across every service it touches, which is often the only way to find where the time actually went.

## Start simple

None of this means you should start with a dozen services, a message queue and three kinds of database. A well-indexed relational database and a stateless application behind a load balancer go a very long way, often much further than people expect.

The better approach is to [design the system](/blog/how-i-became-good-at-designing-systems) so each of these steps is possible when the numbers ask for it: keep services stateless, keep data access behind clear interfaces, measure from day one, and add complexity only when a real bottleneck justifies it. Scalable systems are rarely built all at once. They are grown, one measured bottleneck at a time.


Last updated on March 29, 2026