Scale a Web App from Zero to Millions of Users
One server runs everything, and then the users arrive. This lesson grows that app to millions of users one bottleneck at a time: split the database out, put a load balancer in front of a stateless web tier, add read replicas, a cache and a CDN, move sessions out of the servers, go multi-region, push slow work onto queues, measure everything, and finally shard the database.
What you will learn
- Scale one bottleneck at a time, and name the bottleneck before you add anything.
- Keep the web tier stateless so any server can handle any request; then scaling it is just adding servers.
- Reads usually dominate: replicas, a cache and a CDN absorb them before you touch writes.
- Move slow work off the request path onto a queue and workers.
- You cannot scale what you cannot see: logs, metrics and alerts come before the millionth user.
- Shard the database last, because it is the most expensive change to undo.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: Start with a single server
- Step 4: Separate the database, and choose how to grow
- Step 5: A load balancer and many web servers
- Step 6: Database replication
- Step 7: A cache in front of the database
- Step 8: A CDN and object storage for static files
- Step 9: Make the web tier stateless
- Step 10: More than one data centre
- Step 11: A message queue for slow work
- Step 12: Logging, metrics and automation
- Step 13: Sharding the database
- Step 14: The whole journey on one page
- Step 15: The follow-up questions
- Step 16: The parts people forget
- Recap
The question
Welcome to lesson thirty-one of the system design course. Today's question is a classic, and it often opens a junior or mid-level interview. The interviewer says: take a web app that runs on a single server, and explain, step by step, how you scale it to millions of users.
This question is different from the others in the course. There is no single product to design. Instead, it is a tour of the basic building blocks: load balancers, replicas, caches, content delivery networks, queues, sharding. The interviewer wants to see that you know each one, and, more importantly, when you need it.
That second part is the trap. A weak answer lists every component at once: here is a load balancer, a cache, Kafka, sharding, three regions. A strong answer tells a story. We start small, something breaks, we fix that one thing, and we explain what breaks next. Every component arrives because a specific bottleneck demanded it.
So the shape of this lesson is a timeline. We go from one user to ten thousand, to a hundred thousand, to a million, to ten million, and at each step we name the bottleneck, add the fix and say what it costs. Along the way you will pick up the vocabulary that every other system design question in this course builds on.
Let us start with the questions you should ask before you draw anything.
Step 1: Clarify the requirements
- 01What does the app do?reads, writes, media, real time?
- 02Read to write ratiousually 10 to 1 or more
- 03Growth targetmillions of users: daily or total?
- 04Where are users?one country or worldwide
- 05Availability goalhow much downtime is acceptable
- 06Team and budgetsmall team: prefer managed services
First, what kind of app is it? Say it is a typical web app: users sign up, log in, read and write content, upload images. A small social site or a marketplace. Mostly reads, some writes, some media.
Second, the read to write ratio. Most consumer apps read far more than they write: people scroll more than they post. Ten reads for every write is a common assumption, and it shapes everything later, because reads are much easier to scale than writes.
Third, what does millions mean? Ten million registered users is very different from ten million daily active users. Clarify, and say: let us aim for ten million monthly users and about one million daily active users.
Fourth, where are the users? If they are all in one country, one region is enough for a long time. If they are worldwide, latency will push us towards a CDN and eventually more than one region.
Fifth, availability. Is an hour of downtime a month acceptable? Or do we need four nines, about four minutes a month? Higher availability means redundancy at every layer, which costs money and complexity.
And finally, the team. A team of three should lean on managed databases and hosted services. That is a perfectly good answer in an interview, as long as you also show you understand what the managed service is doing for you.
Step 2: Back-of-the-envelope estimates
Let us put numbers on the target. One million daily active users. Say each user makes about fifty requests a day, loading pages, scrolling, posting. That is fifty million requests a day.
A day has about eighty-six thousand seconds, so fifty million requests a day is about six hundred requests a second on average. Traffic is not flat; evenings are busier. Assume the peak is three times the average: about two thousand requests a second.
If reads outnumber writes ten to one, that is about two hundred writes a second at peak. Storage: if one user in ten uploads a half-megabyte image each day, that is a hundred thousand images, fifty gigabytes a day, about eighteen terabytes a year. The text data is tiny by comparison.
What do these numbers tell us? Two thousand requests a second is more than one modest server should carry, but it is not enormous. A handful of web servers will do it. Two hundred writes a second fits on one well-tuned database. Eighteen terabytes a year of images does not belong in a database at all; it belongs in object storage. Already we know roughly where we are heading.
Step 3: Start with a single server
Here is where everyone starts. One server runs everything: the web application, the database, and the uploaded files on its disk. A user types the domain name, DNS returns the server's IP address, and the browser sends HTTP requests straight to it.
This is not a mistake. For the first few hundred users, it is the right design. It is cheap, simple, and one person can understand all of it. Say this in the interview: I would start here, because nothing has broken yet.
But it has two problems that appear quickly. First, everything competes for the same CPU, memory and disk. A heavy database query slows down every page. Second, it is a single point of failure. If the server dies, or you deploy a bad build, the whole site is down.
So the first change, usually somewhere in the thousands of users, is to split the database off onto its own server.
Step 4: Separate the database, and choose how to grow
Move the database to its own machine. Now the web tier and the data tier can be sized and scaled independently. The web server needs CPU; the database needs memory and fast disks.
Which database? For most apps, start with a relational database. Users, posts, orders and payments are structured, related data, and you want transactions and joins. Reach for a non-relational store when you have a specific reason: huge write volume, no relations, or flexible documents. Saying that out loud shows judgement.
| Scale up (vertical) | Scale out (horizontal) | |
|---|---|---|
| How | bigger machine | more machines |
| Code changes | none | must work on many servers |
| Limit | largest machine you can buy | practically none |
| Failure | still one box | survives losing a box |
| Cost curve | gets steep at the top | roughly linear |
Now the big idea of this whole lesson: vertical versus horizontal scaling. Vertical scaling, scaling up, means a bigger machine: more CPUs, more memory. Horizontal scaling, scaling out, means more machines.
Scaling up is wonderful early on: no code changes, and modern machines are huge. But it has a hard ceiling, the biggest machine you can buy, the price climbs steeply near the top, and you still have one machine that can fail.
Scaling out has no real ceiling and survives failures, but your software must be ready for it. So the practical plan is: scale up the database for as long as it is cheap, because databases are hard to split, and scale out the web tier early, because web servers are easy to multiply. Which brings us to the load balancer.
Step 5: A load balancer and many web servers
With one web server, users connect directly to it. To add a second, we put a load balancer in front. DNS now points at the load balancer's public address. The web servers sit behind it on a private network, unreachable from the internet.
The load balancer spreads requests across the servers, round robin or to the least busy one. It runs health checks every few seconds. If a server stops answering, the load balancer stops sending it traffic, and users never notice. We just removed the web tier's single point of failure.
And when traffic grows, we add web server four and five, and the load balancer starts using them. At our peak of two thousand requests a second, if each server comfortably handles four hundred, we need five, plus a couple spare. Later, autoscaling adds and removes servers based on CPU or request rate, so we pay for evening peaks only in the evening.
The load balancer usually also terminates TLS, so the servers behind it speak plain HTTP on the private network. And the load balancer itself must not be a single point of failure: managed load balancers are redundant by design, or you run a pair with a floating address.
But there is a catch, and interviewers love it. This only works if any server can handle any request. If server one remembers that you are logged in, and your next request goes to server two, you are suddenly logged out. We need a stateless web tier, and we will fix that shortly. First, the database, which is now the obvious single point of failure.
Step 6: Database replication
The database is one machine, and every server talks to it. If it dies, everything stops. And it is doing all the reads, which are ninety per cent of the work. Replication fixes both.
We keep one primary database that takes every write. It streams its changes to several replicas, which are read-only copies. The application sends writes to the primary and spreads reads across the replicas.
Three benefits. Performance: reads, the bulk of the load, are now spread over many machines. Reliability: the data exists in several places. And availability: if a replica dies, reads go to the others; if the primary dies, we promote a replica to be the new primary, and a fresh replica is built to replace it.
The cost is replication lag. Replicas are usually a fraction of a second behind the primary, sometimes more under load. The classic bug: a user updates their profile, the page reloads from a replica that has not caught up, and they see the old name. They think the save failed.
The fix is called read-your-own-writes. For a few seconds after a user writes, send that user's reads to the primary, or remember the version they wrote and read from a replica that has reached it. Mentioning replication lag, unprompted, is one of the clearest signals of experience in this question.
Step 7: A cache in front of the database
def get_post(id):
post = cache.get(f'post:{id}')
if post is None: # miss
post = db.query(id)
cache.set(f'post:{id}', post, ttl=300)
return post
def update_post(id, data):
db.update(id, data)
cache.delete(f'post:{id}') # next read refillsEven with replicas, many requests ask for the same data again and again: the home page, popular posts, a user's own profile. Every one of those becomes a database query. A cache keeps the answers in memory, so most of those requests never reach the database.
The usual pattern is cache-aside. The application checks the cache first. On a hit, it returns immediately, in well under a millisecond. On a miss, it reads the database, stores the result in the cache with an expiry time, and returns it. An in-memory key value store is the typical choice, and a single node can serve over a hundred thousand reads a second.
On a write, update the database, then delete the cache entry, so the next read fetches the fresh value. Deleting is safer than updating the cache in place, because two concurrent updates could otherwise leave the cache holding the older one.
- 01ExpiryTTL on every entry
- 02Evictionleast recently used when full
- 03Failurecache down = slower, not broken
- 04Consistencyshort staleness is acceptable for most reads
- 05Stampedeone miss refills; others wait
Four things to say about caches in an interview. Expiry: every entry gets a time to live, so stale data heals itself. Eviction: when memory fills up, the least recently used entries go. Failure: the cache is a performance layer, never the source of truth, so the system must survive losing it, slowly. And consistency: a cache means some readers see slightly old data for a short time; say which data can tolerate that.
And one more, the cache stampede. A very popular key expires, and a thousand requests miss at once and all hit the database. Fix it by letting only one request refill the key while the others wait briefly, or by refreshing hot keys before they expire. With a good cache, it is normal for ninety per cent of reads to never touch the database.
Step 8: A CDN and object storage for static files
Now the images. Earlier we worked out about fifty gigabytes of uploads a day. Those files should not live on web servers' disks, because then every server needs every file. And they should not be served by our web servers at all.
First, move uploads to object storage: a service that stores files by key, cheaply and durably, with practically unlimited space. The web server stores only the file's key in the database. Better still, the client uploads directly to object storage with a short-lived signed URL, so large files never pass through our servers.
Second, put a content delivery network in front. A CDN is a network of servers in many cities. When a user requests an image, the nearest CDN server answers from its own cache. On a miss, it fetches the file from object storage once, and then serves it to everyone nearby.
This helps twice. Users far away get images in tens of milliseconds instead of hundreds. And our servers stop serving the heaviest bytes entirely; typically most of a site's bandwidth moves to the CDN. Do the same for JavaScript, CSS and fonts, with a version hash in each file name so they can be cached for a year and replaced instantly when they change.
Lesson twenty-nine of this course designs a CDN from the inside, if you want the deep dive. Here, it is enough to say: static content goes to object storage and is served through a CDN, with long cache lifetimes and versioned file names.
Step 9: Make the web tier stateless
| Approach | How | Problem |
|---|---|---|
| Server memory | session on the box that logged you in | breaks when traffic moves |
| Sticky sessions | load balancer pins user to one server | uneven load; lost on server death |
| Shared store | sessions in a fast key value store | one more dependency, but scales |
| Signed token | client holds signed session data | hard to revoke before expiry |
Back to that catch with the load balancer. A user logs in on server one, which stores the session in its own memory. The next request goes to server two, which has never heard of them. Logged out.
One workaround is sticky sessions: the load balancer always sends a user to the same server. It works, but it makes load uneven, autoscaling awkward, and a server's death logs out everyone pinned to it. Treat it as a stopgap.
The real fix is to move state out of the web servers. Store sessions in a shared, fast key value store, the same kind we use for caching, or in the database. Or give the client a signed token that carries its identity, which any server can verify without a lookup. Each has a trade-off: tokens are hard to revoke early, so many systems use short-lived tokens with a refresh step.
Once no server holds anything that matters, the web tier is stateless. Any server can handle any request. Servers can be added, removed, restarted or replaced at any time, and autoscaling simply works. This is the single most important property of a scalable web tier, so say the word stateless clearly in your answer.
The same applies to uploaded files, which we already moved to object storage, and to anything else written to local disk. A good test: could you delete any web server right now, mid-request, and lose nothing but that one request? If yes, you are stateless.
Step 10: More than one data centre
We now have a solid design in one data centre. But a whole data centre can fail: a power problem, a network cut, a bad configuration push. And users on the other side of the world still wait a quarter of a second per round trip. The next step, often in the millions of users, is a second region.
Geo DNS sends each user to the nearest healthy region. Each region has the full stack: load balancer, web servers, cache, database. If region A goes down, DNS sends everyone to region B, which must have enough spare capacity to take the extra load.
The hard part is data. The simplest arrangement keeps one primary database in one region, with replicas in the other. Reads are local everywhere; writes from the far region cross the ocean, adding latency. On failover, a replica in the surviving region is promoted, accepting that the last second or so of writes may be lost.
More ambitious designs accept writes in both regions, which needs conflict handling, or partition users by home region, so each user's data has one primary close to them. Name the options, recommend the simplest one that meets the availability goal, and point out the operational cost: deployments, monitoring and tests now cover two regions.
A related point: one region already has several availability zones, separate buildings with separate power. Spreading servers and database replicas across zones gives most of the reliability benefit for much less effort. Many products run in one region with three zones for years.
Step 11: A message queue for slow work
Some work is slow and does not need to finish before we answer the user: resizing an uploaded image into five sizes, sending a welcome email, updating search indexes, generating a report. If the web server does it inline, the user waits, and a burst of uploads ties up the whole web tier.
So the web server publishes a message to a queue, a durable buffer, and replies immediately: upload received. Separate worker processes pull messages off the queue and do the work. The user sees a thumbnail placeholder for a second, then the real thing.
Queues give us three things. Decoupling: producers and consumers scale independently; if image jobs pile up, add image workers. Smoothing: a burst of ten thousand uploads becomes a backlog drained over a few minutes, instead of an outage. And resilience: if the email service is down, messages wait in the queue and are retried later.
The fine print. Most queues deliver at least once, so a message can be processed twice; make every job idempotent, safe to repeat. Messages that keep failing go to a dead-letter queue for a person to inspect. And watch the queue's depth and the age of its oldest message; those are the first signs that workers are falling behind.
Step 12: Logging, metrics and automation
- 01Logscentralised, searchable, with a request id
- 02Metricshost, service and business numbers
- 03Alertson user-visible symptoms
- 04Tracingfollow one request across services
- 05CI/CDevery change built, tested, deployed the same way
- 06Infrastructure as codeservers described in files, not by hand
By now we have dozens of servers. When something goes wrong at that scale, you cannot log in to each machine and read files. And with many deploys a day, manual steps become the main source of outages. So before the millionth user, invest in seeing and automating.
Logging: every server ships its logs to a central store you can search. Give every request an id at the load balancer and log it everywhere, so one search shows the whole story of a failed request.
Metrics, at three levels. Host metrics: CPU, memory, disk. Service metrics: requests per second, error rate, latency at the ninety-ninth percentile, cache hit rate, replication lag, queue depth. And business metrics: sign-ups, posts, payments per minute. A drop in sign-ups is often the first sign of a bug no technical metric shows.
Alerts fire on symptoms users feel, high error rates or slow pages, not on every busy CPU, so the person on call trusts them. And tracing follows one request across services, which matters once we split into several.
Automation: every change goes through the same pipeline: build, test, deploy to a few servers, watch the metrics, then roll out to the rest, with one-click rollback. Servers are described in configuration files, so building a new region is running a script, not a week of clicking. This is not glamorous, but at a million users it is what keeps the site up.
Step 14: The whole journey on one page
| Stage | Bottleneck | Fix |
|---|---|---|
| 1 server | nothing yet | keep it simple |
| Thousands | app and DB compete | separate database |
| Tens of thousands | one web server | load balancer + stateless web tier |
| Hundreds of thousands | DB reads | replicas + cache |
| Same | heavy static files | object storage + CDN |
| A million | slow work in requests | queues and workers |
| A million | can't see problems | logs, metrics, automation |
| Millions | one region | multiple zones, then regions |
| Tens of millions | DB writes and size | sharding |
Let us put the journey on one page, because this is how you should summarise it on the whiteboard.
At each stage, notice the pattern: measure, find the one thing that is about to break, fix that, and stop. You do not add a CDN because it is on a list. You add it because images are now most of your bandwidth and your far-away users are slow.
And the ordering is roughly by cost. Splitting the database is an afternoon. A load balancer is a day. Caching takes thought about staleness. Multiple regions and sharding are months of work and change how the whole team operates. A good engineer does the cheap things first.
The numbers in the stage column are rough, and they vary hugely with the app. A chat app hits write limits earlier; a news site may never need sharding. If the interviewer gives you a specific app, adjust the order and say why.
Step 15: The follow-up questions
- 01Database failoverwhat happens when the primary dies
- 02Cache vs replicawhich first
- 03SQL or NoSQLfor the scaled version
- 04Microserviceswhen to split the monolith
- 05Rate limitingprotecting the system
Now the follow-up questions. Here is Max, our AI interviewer, with the kind of thing an interviewer asks after this answer.
Max asks
“What exactly happens when the primary database dies?”
Monitoring notices it has stopped answering, usually within seconds. An orchestrator picks the replica that is most up to date and promotes it to primary. The application's database address is switched to the new primary, through DNS or a proxy. The other replicas start following the new primary. Writes that had not reached any replica are lost, typically under a second of data, so for payments you use synchronous replication to at least one replica. During those seconds, writes fail and reads keep working.
Max asks
“Would you add a cache or read replicas first?”
It depends on the reads. If many users read the same few things, like a home page, a cache is cheaper and far faster, and one cache node absorbs most of the load. If reads are spread thinly across many different rows, the hit rate will be poor, and replicas help more. In practice you end up with both. I would look at the query logs before deciding.
Max asks
“At ten million users, would you switch to a NoSQL database?”
Not by default. The relational database with replicas, caching and eventually sharding carries most apps a very long way, and it gives transactions and flexible queries. I would move specific workloads to specialised stores where they fit: a wide-column store for a huge append-only activity feed, a search engine for search, a key value store for sessions. Rewriting everything onto a new database is rarely worth it.
Max asks
“When would you split the monolith into microservices?”
When the organisation needs it more than the code does. Splitting lets separate teams deploy independently and lets one heavy feature scale on its own. But it adds network calls, partial failures and harder debugging. Every step in this lesson works with a single well-structured application. I would split along clear boundaries, like payments or media processing, when a team or a scaling need demands it.
Max asks
“How do you protect the system from a sudden flood of traffic?”
Several layers. A rate limiter at the load balancer or gateway caps requests per user or per IP. Autoscaling adds web servers, though it takes minutes. Queues absorb bursts of background work. And the app degrades gracefully: under heavy load, turn off expensive extras, like recommendations, and keep the core pages working. Lesson two covers rate limiters in depth.
Step 16: The parts people forget
- 01Backupsreplicas are not backups
- 02Connection limitshundreds of servers × pools
- 03Costevery layer costs money
- 04Securityprivate network, least privilege
- 05Load testingfind the next bottleneck before users do
A few points that candidates often miss, and that interviewers notice when you mention them.
Backups. A replica is not a backup. If someone runs a bad delete, it is faithfully copied to every replica within a second. Take regular snapshots plus a continuous log of changes, store them in another region, and practice restoring them.
Database connections. Each web server keeps a pool of connections. Fifty servers with fifty connections each is two and a half thousand connections, which can overwhelm a database. Put a connection pooler in between.
Cost. Every server, replica and region costs money. Say how you would right-size: autoscale the web tier down at night, use cheaper storage tiers for old images, and only add a region when the availability or latency goal requires it.
Security. Only the load balancer is public; everything else sits on a private network. Each service gets only the permissions it needs. Secrets live in a secrets manager, not in code.
And load testing. Do not wait for users to find the next bottleneck. Replay realistic traffic at twice your peak against a staging copy, watch which metric bends first, and that is the next step on your roadmap.
Recap
- 01One serveruntil it hurts
- 02Separate DBscale tiers independently
- 03Load balancerstateless web tier, autoscaling
- 04Replicas + cacheabsorb reads
- 05Object storage + CDNstatic files near users
- 06Queuesslow work off the request path
- 07Observe and automatelogs, metrics, CI/CD
- 08Regions, then shardsthe expensive steps, last
Let us recap. Start with one server; it is the right answer until something breaks. Separate the database. Put a load balancer in front of several web servers, and make them stateless so any server can handle any request.
Absorb reads with replicas, a cache, and a CDN in front of object storage. Push slow work onto queues. Invest in logs, metrics and automation before you need them.
Then, only when the numbers demand it, spread across zones and regions, and finally shard the database, choosing the shard key with care.
In a forty-five minute interview: five minutes on questions and numbers, thirty minutes walking the timeline, naming each bottleneck before each fix, and ten minutes on follow-ups. The thing that wins this interview is that storytelling habit: this broke, so I added that, and here is what it costs.
Practice telling that story out loud with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson thirty-two, where we design consistent hashing.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.