Contents

Scaling From Zero to Millions of Users

The beautiful art of growing from one server to millions of users. 🚀

“Somewhere right now, millions of people are pressing play, searching, scrolling and sending messages, and a carefully built system is quietly serving every single one of them. Nobody using it thinks about the load balancer, the cache, the replicas or the shards. It just works. Behind that simplicity sits years of careful decisions, and that is what makes system design so fascinating.”

What really happens behind the screen when millions of people tap the same button at the same time?

Every new user brings more requests and more data. Nothing breaks on day one. Pages get a little slower, background jobs take a little longer, and quietly the system starts carrying more than it was built for. I have watched this happen as more and more users came in, and the lesson is simple: every new user lands directly on the system. More weight on the same servers, the same database, the same code.

Now take that to the extreme. Netflix streaming to millions of screens at the same moment. Google answering a search before you finish typing. Facebook keeping billions of people connected, every single day. Somehow it all just works. How?

The answer is not one clever trick. It’s a craft, built one careful decision at a time. Honestly, it’s a beautiful art.

This post is that journey: from a single server to a system that can serve millions of users. Every drawing builds on the one before it, so you can watch the system grow exactly the way real systems do, one bottleneck at a time.

Before We Begin: What Does Scalable Really Mean?

Martin Kleppmann, author of Designing Data-Intensive Applications, defines scalability as a system’s ability to cope with increased load. “Is it scalable?” is too vague a question. A better one is: if the load grows in this particular way, what can we do to keep the system fast?

To answer it we need to know two things:

  • The load. For example: requests per second, how many reads there are for every write, or the number of users online at the same time.
  • The performance we care about. Usually response time, measured as percentiles (p95, p99) rather than an average. An average hides the slow requests your unhappiest users actually see.

Each step below answers that question for one specific kind of growth. Let’s start where every system starts: small, simple, and full of hope.

Where Every Story Begins: A Single Server

/posts/scaling-from-zero-to-millions-of-users/01-single-server.png
Many clients, one server

On the left are the clients: anything that talks to our system, such as a browser or a mobile app. On the right is one server that does everything: it runs our code, stores the data and builds the responses.

Each client sends a request and gets back a response:

  • A browser usually gets back an HTML page to show.
  • A mobile app or another program calling our REST API usually gets back JSON.

The dots between the clients mean there can be any number of them, and every one of them talks to the same single box.

This is perfect for getting started. It is cheap, easy to deploy and easy to debug. But look at the drawing again and two problems stand out:

  • No backup. Every arrow ends at the same box. If that server goes down, the whole product goes down.
  • One box does everything. Our code and our data compete for the same CPU, memory and disk.

Almost every great product started right here: one box, a handful of users, and someone who cared a lot.

Giving Data a Home of Its Own: The Database

/posts/scaling-from-zero-to-millions-of-users/02-database.png
Separate web tier and data tier

We take the data out of the server and give it its own machine, the Database on the right. The server in the middle becomes a web server: its only job is to handle client requests.

Follow the arrows in the drawing:

  1. The client sends a request to the web server.
  2. The web server needs data, so it sends a database query. This is an internal request: it stays between our own servers, and the client never sees it.
  3. The database sends its response back to the web server.
  4. The web server builds the final response and sends it to the client.

Because the web tier and the data tier are now separate, each one can grow on its own.

Choosing the Right Home: SQL or NoSQL?

Relational (SQL) Non-relational (NoSQL)
Examples MySQL, PostgreSQL, Oracle, SQL Server MongoDB, Cassandra, Redis, Firebase
Data model Tables with a fixed schema; joins across tables Documents, key–value pairs, wide columns; flexible schema
Good for Structured data, relationships, consistency, complex queries Unstructured data, huge scale, flexible schema, very fast lookups

Relational databases are the sensible default. Pick a non-relational one when you have a concrete reason, such as needing very low latency or storing data with no real relationships. Kleppmann puts it simply: document databases fit self-contained data (like a user profile with its list of jobs), and relational databases fit connected data (users, companies and schools that all point at each other).

Grow Taller or Grow Wider: Vertical vs. Horizontal Scaling

  • Vertical scaling (scale up): make one machine stronger by adding more CPU, more RAM or faster disks.
  • Horizontal scaling (scale out): add more machines.

Vertical scaling is simple, and it is the right first move. But there is a limit to how big one machine can get, and one machine is still one machine: if it dies, everything dies. That’s why the rest of this post scales out.

A Traffic Police for Requests: The Load Balancer

/posts/scaling-from-zero-to-millions-of-users/03-load-balancer.png
The load balancer spreads requests across the server pool

The blue circle is a load balancer. Clients don’t talk to a web server directly anymore; they talk to the load balancer, and it decides which web server handles each request.

Follow the numbers in the drawing:

  • Request 1 from client 1 goes to the load balancer, which sends it to the bottom web server. Response 1 comes back the same way.
  • Request 2 from client 2 goes to the top web server, and response 2 returns the same way.

The tall box around the two web servers is the server pool. Both servers run the same code and both talk to the same database.

This gives us two things:

  • Failover. If one web server goes down, the load balancer simply sends every request to the other one. Users don’t notice.
  • Room to grow. When traffic grows, we add another server to the pool and the load balancer starts sending it requests.

The web tier now has a backup. The database, still a single box on the right, does not.

This drawing is a turning point. For the first time, one server going down no longer takes the whole product down with it. That small sense of safety is what lets a team sleep at night.

One Writer, Many Readers: Database Replication

/posts/scaling-from-zero-to-millions-of-users/04-database-replication.png
Writes go to the master, reads go to the slaves

The single database becomes a team:

  • Both web servers send every write (create, update, delete) to the Master Database.
  • The master copies every change to the slave databases. These are the arrows labelled replication.
  • Reads go to the slaves. Follow the read line at the bottom: it spreads across all three slaves.

Why are there three slaves and only one master? Most applications read far more than they write. Think of how often you scroll a feed compared with how often you post. So we add copies where the load is.

Naming
Alex Xu, author of System Design Interview, calls this master/slave. Kleppmann calls it leader/follower replication, and you will also see primary/replica. They all mean the same thing.

When a Database Falls: Failover

  • A slave fails. Reads go to the other slaves. If it was the only slave, the master handles reads for a while until a new slave is set up.
  • The master fails. One slave is promoted to become the new master. This is the tricky part: the slave may not have the most recent writes yet, so those writes need to be recovered or can be lost.

Frequently Accessed Data at the Front Desk: Cache

/posts/scaling-from-zero-to-millions-of-users/05-cache.png
Check the cache first, the database second

Asking the database for the same popular data again and again is slow and wasteful. So we put a cache in front of it. A cache is a fast, in-memory store such as Redis or Memcached.

The drawing’s notes describe the whole flow:

  1. The web servers send every read to the cache first.
  2. If the data is present in the cache, read it from the cache. The database is never touched. This is a cache hit.
  3. If the data is not present in the cache, get it from the database, store it in the cache and forward it to the server. This is a cache miss, and the next request for the same data will be a hit.

Writes are unchanged: they still go straight to the master.

If you have ever watched a slow page suddenly become instant after adding a cache, you know the feeling. It’s one of the most satisfying moments in this job.

Things to watch:

  • Only cache what is read often and changed rarely. The cache lives in memory, so never keep data there that you cannot afford to lose.
  • Expiry (TTL). Without an expiry time, old data stays forever. Too short and the database gets hit constantly; too long and users see outdated data.
  • One cache is a single point of failure. In real systems you run several cache servers.
  • When the cache is full, something has to be removed. The usual choice is LRU (least recently used).

Static Files Closer to Home: Content Delivery Network (CDN)

/posts/scaling-from-zero-to-millions-of-users/06-cdn.png
Static content comes from the CDN; if it isn't there, the CDN asks our server

Images, videos, CSS and JavaScript files are the same for every user, so there is no reason for our web servers to send them over and over. A CDN is a network of servers spread around the world that keep copies of these files close to the users.

In the drawing, the clients now make two kinds of requests:

  • Request for static content (the arrow up to the cloud) goes to the CDN, which sends the file back.
  • Everything else (requests 1 and 2) goes through the load balancer as before.

The note at the top covers the missing case: if the file is not in the CDN, the CDN asks our server for it, keeps a copy, and sends it to the client. The next user nearby gets it straight from the CDN.

Things to watch:

  • Cost. CDNs charge for data transfer, so don’t put rarely used files there.
  • Expiry. Same trade-off as the cache: too long serves old files, too short asks our server too often.
  • Updating a file. The easiest way is to change its URL, for example logo.png?v=2, so clients and the CDN fetch the new version.
  • Keeping copies in step with the original. Making sure the copy in the CDN (or in a cache) always matches the main data is a different tale. Kleppmann calls the main database the system of record and every copy built from it derived data; keeping the two consistent is one of the hardest problems in the field. That one deserves its own upcoming post.

Any Server, Any Request: Going Stateless

/posts/scaling-from-zero-to-millions-of-users/07-stateless.png
Session data lives in a shared store, not inside a server

There is a hidden problem in the load balancer drawing. Say a user logs in through the top web server, and that server keeps the login session in its own memory. If the next request goes to the bottom server, that server doesn’t know the user, so they look logged out. To avoid this, every request from that user would have to go to the same server. That makes adding or removing servers painful, and if that server dies, the user’s session dies with it.

The fix is the new { } box in the drawing: shared databases for session. Both web servers have an arrow to it. Session data (who is logged in, what is in the cart) is stored there instead of inside a server.

Now any web server can handle any request, because each one looks up the session in the shared store. The servers become identical and interchangeable. We can add more when traffic rises and remove some when it drops, which is called autoscaling.

Closer to Every User: Multiple Data Centers

/posts/scaling-from-zero-to-millions-of-users/08-data-centers.png
Each region (geo) is a complete copy of the system

This is where companies like Netflix and Google live. A user in Kathmandu and a user in New York both expect the same thing: it should just work, and it should be fast.

The farther a user is from our servers, the longer every request takes, simply because of distance. And a whole data center can go offline (power cut, network failure, flood). So we run the system in more than one place.

In the drawing, everything we have built so far is copied into two boxes, geo 1 and geo 2. Each geo has its own load balancer, web servers, cache, master and slaves. In front of them sits one more load balancer, which sends each user to a geo:

  • Normally, each user goes to the closest geo, so requests are fast. In practice this is often done with GeoDNS, which turns the domain name into the address of the nearest data center.
  • If one geo goes down, all traffic is sent to the healthy one. It is slower for users far away, but a slow site is far better than a site that’s down.

Notice that the shared databases for session box sits outside both geos and both connect to it. That way a user’s session still works even if they are moved to the other geo.

This brings new challenges:

  • Keeping data in sync. Each geo has its own master. If geo 1 goes down, its users’ data must already be in geo 2, so the data has to be copied between geos. (Kleppmann covers this as multi-leader replication, which has its own problem: two geos can change the same data at the same time.)
  • Deploying everywhere. Every geo must run the same version of the code, so automated deployment becomes a must.

Leave a Note, Someone Will Handle It: Message Queue

/posts/scaling-from-zero-to-millions-of-users/09-message-queue.png
Web servers publish messages; workers take them and do the work

Some jobs are slow: resizing a photo, sending emails, generating a report. If a web server does that work while the user waits, the response is slow and the server is busy. A message queue lets us hand the work off.

In the drawing:

  1. A web server puts a message (each envelope) into the message queue and responds to the user right away. The web servers are the producers.
  2. The workers on the right take on messages from the queue and do the actual work. They are the consumers.

The queue sits between them, so the two sides don’t need to know about each other:

  • Scale each side on its own. If messages pile up, add more workers. If the queue is empty, remove some.
  • Survive failures. If the workers are down, the web servers keep adding messages and nothing is lost. The work is done when the workers come back.

Eyes on Everything: Logging, Metrics, Monitoring and Automation

/posts/scaling-from-zero-to-millions-of-users/10-logging-metrics-automation.png
One system watching everything

Look at the curved line in the drawing: it wraps around everything we have built, and the logging, metrics, monitoring, automation box points at all of it. With a couple of servers you can log in and look around. With hundreds you can’t. Without good tooling, the first sign of trouble is often a user complaining instead of the system telling you. That’s backwards. These tools fix it:

  • Logging. Collect error logs from every server in one central place, so problems are easy to search and spot.
  • Metrics. Collect numbers about the system:
    • Per machine: CPU, memory, disk.
    • Per tier: how the whole database tier or the whole cache tier is performing.
    • Business: daily active users, retention, revenue.
  • Monitoring. Watch those metrics and alert someone when something looks wrong.
  • Automation. Continuous integration checks every code change automatically, so problems are caught early. Automating builds, tests and deployments lets the team ship faster and more safely.

One Library, Many Shelves: Sharding the Database

/posts/scaling-from-zero-to-millions-of-users/11-sharding.png
Shard 1 to shard n, each holding part of the data

One master handles every write. Eventually it can’t keep up, or the data no longer fits on one machine. A bigger machine buys some time, but as we saw earlier with vertical scaling, there is a limit.

The horizontal answer is sharding, which Kleppmann calls partitioning. In the drawing, the master and its slaves are replaced by a Databases box with shard 1, shard 2, shard 3 … shard n. The web servers now write to the shards. Each shard has the same tables, but holds a different part of the data.

How do we know which shard holds a piece of data? We pick a sharding key. For example, with four shards and user_id % 4:

  • User 0 goes to shard 1, user 1 to shard 2, user 2 to shard 3, user 3 to shard 4, and user 4 back to shard 1.

A good key spreads data and traffic evenly, so choosing it is the most important decision.

Sharding brings its own problems:

  • Resharding. One shard fills up faster than the others and data has to move between shards. Consistent hashing reduces how much data needs to move.
  • Hot spots. A celebrity with millions of followers can overload the one shard that holds them. Sometimes they need a shard of their own.
  • Joins. Combining data from different shards is hard, so data is often duplicated (denormalized) so that a query can be answered from one shard.

The Craft Behind It All

The most beautiful part is that there is never one perfect answer. Every box in these drawings is a trade-off. A cache makes things fast but can serve old data. Replicas make reads cheap but can lag behind. Sharding lets us grow almost without limit but makes simple queries hard. Building a great system is not about knowing the “right” tool. It is about understanding what each choice gives, what it costs, and choosing with open eyes.

This post was the big picture. Every box in these drawings deserves its own story, so in upcoming posts I will go deep into each component, one at a time: how load balancers decide where to send a request, how caches stay fresh, how databases replicate and shard, how message queues keep work from getting lost, and all the nitty-gritty details in between. Stay tuned.

References

  1. Alex Xu, System Design Interview – An Insider’s Guide, Volume 1.
  2. Martin Kleppmann, Designing Data-Intensive Applications, O’Reilly, 2017.