Scaling a web app from one server to millions

Learn the step-by-step journey of scaling a system from a single server to a distributed architecture handling millions of users. Master load balancing, caching, and database scaling.

beginner11 min readBy CureBugs EditorialUpdated 5 Nov 2026

Every large tech company, whether it's Flipkart, Zomato or Uber, started with a simple architecture. When you launch a new application, a single server might be enough to handle your first 100 users. But what happens when your app goes viral and traffic spikes to 1 million users? If your architecture doesn't evolve, your servers will crash, your database will lock up, and your users will leave. Scaling is the art of evolving your system to handle increasing load without sacrificing performance or reliability.

What it is and why it matters

Scalability is the measure of how well a system can grow to accommodate increasing demand. In system design, demand is usually measured in QPS (Queries Per Second) or concurrent users.

Handling 10 QPS is trivial; almost any laptop can do it. Handling 10,000 QPS requires careful architectural choices. Handling 1,000,000 QPS requires a highly distributed system.

In system design interviews, interviewers rarely want you to design a Google-scale microservice architecture for a simple internal tool. Instead, they want to see your ability to identify bottlenecks and apply the right scaling strategy at the right time. Understanding this evolutionary journey proves you know why certain technologies exist, rather than just throwing buzzwords at a whiteboard.

How it works: The Scaling Journey

Let's walk through the evolution of a web application from day one to millions of users.

Phase 1: The Single Server (0 to 10,000 users)

Initially, everything lives on one machine. Your web server (e.g., Tomcat, Node.js), your application logic, and your database (e.g., PostgreSQL, MySQL) all share the same CPU, memory, and disk.

  • The Bottleneck: As traffic grows, the web server and database fight for resources. If the server goes down, your entire application is dead. This is a Single Point of Failure (SPOF).

Phase 2: Database Separation (10,000 to 50,000 users)

The first step in scaling is separating the web tier from the data tier. You move your database to its own dedicated server (or a managed service like AWS RDS).

  • Why it works: Web servers and databases scale differently. Web servers are typically CPU-bound, while databases are memory and I/O-bound. Separating them allows you to scale them independently.

Phase 3: Load Balancing and Horizontal Scaling (50,000 to 500,000 users)

When one web server can no longer handle the traffic, you add more. This is called Horizontal Scaling (scaling out). To distribute incoming traffic evenly across these multiple servers, you introduce a Load Balancer.

  • The Catch - Statelessness: For a load balancer to work effectively, your web servers must be stateless. If Server A stores a user's login session in its local memory, and the load balancer routes their next request to Server B, the user will be logged out. State must be moved out of the web servers and into a shared database or cache.

Phase 4: Caching (500,000 to 2 Million users)

Now you have multiple web servers, but they are all hammering the same single database. Databases are slow because they read from disk and ensure strict data integrity. To protect the database, you introduce a distributed cache like Redis or Memcached.

  • Why it works: Caches store frequently accessed data in RAM, making reads blazing fast (sub-millisecond). By implementing a cache-aside pattern, you can intercept 80-90% of read requests before they ever reach the database.

Phase 5: Database Scaling (2 Million to 10 Million users)

Even with a cache, your database will eventually hit a wall with write traffic. The next step is Database Replication. You set up a Master-Slave (or Primary-Replica) architecture. The Master handles all write operations, while multiple Slaves handle the read operations.

  • Beyond Replication: If write traffic exceeds what a single Master can handle, you must implement Database Sharding, which splits your data across multiple independent databases based on a shard key (e.g., User ID).

Phase 6: Asynchronous Processing (10 Million+ users)

At massive scale, you cannot afford to make users wait for slow, synchronous operations (like sending an email, generating a PDF, or processing a video). You introduce a Message Queue (like Kafka or RabbitMQ). The web server instantly drops a message in the queue and returns a success response to the user. Background worker nodes consume these messages and process the heavy tasks asynchronously.

Here is what the architecture looks like at Phase 6:

The Main Strategies Compared

When scaling, you constantly choose between different architectural patterns. Here are the core comparisons:

StrategyWhat it isProsCons
Vertical Scaling (Scale Up)Upgrading a single server with more CPU/RAM.Extremely simple. No code changes required.Hard hardware limits. Expensive. Remains a Single Point of Failure.
Horizontal Scaling (Scale Out)Adding more servers to a pool.Infinite scalability. High availability.Requires complex load balancing and stateless application design.
Read ReplicasCopying the database to serve read-only queries.Drastically improves read throughput.Introduces replication lag (stale data). Doesn't help with write scaling.
Database ShardingSplitting data across multiple databases.Scales both reads and writes infinitely.Extremely complex to implement. Cross-shard joins are nearly impossible.

Code Example: The Cache-Aside Pattern

A critical milestone in scaling is implementing caching. The most common approach is the Cache-Aside pattern: the application first checks the cache; if the data is missing (a cache miss), it queries the database, stores the result in the cache, and returns the data.

Here is how you implement a stateless API endpoint using this pattern across different languages:

import json

def get_user_profile(user_id, redis_client, db_connection):
    cache_key = f"user:{user_id}"
    
    # 1. Check the cache first
    cached_data = redis_client.get(cache_key)
    if cached_data:
        return json.loads(cached_data)  # Cache hit
    
    # 2. Cache miss: Query the database
    cursor = db_connection.cursor()
    cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
    user_data = cursor.fetchone()
    
    if user_data:
        # 3. Store the result in the cache with a Time-To-Live (TTL)
        redis_client.setex(cache_key, 3600, json.dumps(user_data))
        
    return user_data

Trade-offs and Failure Modes

Scaling is never free. Every component you add introduces new trade-offs and potential failure modes.

1. Cache Invalidation and The Thundering Herd

When you rely heavily on a cache, what happens when data changes? If a user updates their profile, you must invalidate the old cache. If you forget, users see stale data. Furthermore, if a highly popular cache key (e.g., a viral tweet) suddenly expires, thousands of concurrent requests will experience a cache miss simultaneously. They will all query the database at the exact same millisecond, potentially bringing the database down. This is known as the Thundering Herd problem. It is typically solved by using mutex locks (only allowing one request to query the DB while others wait) or background cache refreshing.

2. Replication Lag

In a Master-Slave database setup, data written to the Master takes a few milliseconds to copy over to the Slaves. If a user updates their password (written to Master) and immediately tries to log in (read from Slave), the Slave might not have the new password yet. The login fails. This is Replication Lag. To solve this, systems often route reads from the same user who just made a write to the Master for a short window of time.

3. Complexity vs. Cost

Maintaining a distributed system requires a dedicated DevOps team, robust monitoring (like Prometheus/Grafana), and centralized logging (like ELK stack). If your app only makes $1,000 a month, spending $5,000 on AWS infrastructure to achieve "infinite scale" is a terrible engineering decision.

How it shows up in real systems

  • E-commerce Flash Sales (e.g., Flipkart Big Billion Days): During a flash sale, traffic spikes 100x in seconds. Relational databases cannot handle the sudden surge of writes. These systems rely heavily on Message Queues. When you click "Buy", the request is put into a Kafka queue. The UI tells you "Order Processing..." while worker nodes slowly drain the queue and update the database at a safe speed.
  • Social Media Feeds (e.g., Instagram): Social media is incredibly read-heavy (ratio of 1000 reads to 1 write). They rely on massive Redis clusters to cache users' timelines. When you open the app, you are almost entirely reading from RAM, not a database. (See our guide on design-instagram-feed for more).

Interview Questions

1. How do you handle user sessions when scaling horizontally?

Model Answer: If web servers hold session state locally, a load balancer might route a user to a different server, causing them to lose their session. I would solve this by making the web servers stateless and moving session data to a centralized, fast in-memory store like Redis. The load balancer can then route requests to any available server.

2. When would you choose Vertical Scaling over Horizontal Scaling?

Model Answer: I would choose vertical scaling when the application is a legacy monolith that is difficult to decouple, when the traffic growth is predictable and within the limits of a single high-end machine, or when the engineering cost of re-architecting for horizontal scaling outweighs the cost of buying a larger server.

3. What happens if your Redis cache cluster goes down entirely?

Model Answer: This would cause a massive cache miss, sending all traffic directly to the database, likely causing it to crash (cascading failure). To prevent this, I would implement circuit breakers in the application. If Redis fails, the circuit breaker opens, and we aggressively rate-limit incoming requests or serve a degraded experience rather than overwhelming the database.

4. How do you solve replication lag for critical reads?

Model Answer: For highly critical reads (like reading a payment status immediately after a transaction), I would force the application to read directly from the Master database instead of the Read Replicas. Alternatively, we can use a "read-your-own-writes" consistency model, where a user's reads are routed to the Master for 5 seconds after they perform a write.

5. What is the difference between Database Replication and Database Sharding?

Model Answer: Replication involves making exact copies of the entire database to scale out read capacity and provide high availability. Sharding involves splitting the actual data into smaller, independent chunks across multiple databases to scale both read and write capacity. Sharding is much more complex and is usually a last resort.

Scaling is a journey of finding the current bottleneck and applying the simplest pattern to remove it. Master these building blocks (load balancers, caches, replicas and queues) and you will be able to design systems that handle massive scale gracefully.

Mock interview

Can you explain it when someone pushes back?

Interviewers rarely ask for a definition. They ask why you'd pick this over that, and what breaks at ten times the load. A mock round finds those gaps before the real one does.

  • A question on your own project, then a design problem
  • The interviewer probes the parts you skim over
  • A scored report that quotes your answers and says what to fix
Start a mock design round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
System design•intermediate

Database sharding and replication

13 min read
System design•intermediate

Consistent hashing

12 min read
System design•beginner

SQL vs NoSQL: choosing a database

12 min read
System design•beginner

Load balancing: algorithms, layers and health checks

10 min read