Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 02 · Scaling, Traffic & Data StoresChapter 8 of 33
07.
Phase 02Read time ~26 minDifficulty advanced

Scaling Applications

In this chapter
  • 01Chapter Overview
  • 02What Does Scaling Mean?
  • 03Capacity
  • 04Scaling Dimensions
  • 05Compute
  • 06Memory
  • 07Storage
  • 08Network
  • 09Database
  • 10Connections
  • 11Background processing
  • 12Vertical Scaling
  • 13Advantages of Vertical Scaling
  • 14Limitations of Vertical Scaling
  • 15Horizontal Scaling
  • 16Vertical vs Horizontal Scaling
  • 17Example: Scaling an API
  • 18Why Statelessness Matters
  • 19Load Balancer
  • 20The Scaling Bottleneck
  • 21Bottleneck Chain
  • 22Little's Law
  • 23Throughput vs Latency
  • 24Throughput
  • 25Latency
  • 26Capacity Planning
  • 27Peak Traffic
  • 28Headroom
  • 29Scaling Application Servers
  • 30Autoscaling
  • 31CPU-Based Autoscaling
  • 32Request-Based Autoscaling
  • 33Queue-Based Autoscaling
  • 34Scaling Policies
  • 35Scaling Oscillation
  • 36Caching as a Scaling Strategy
  • 37Read-Heavy Workloads
  • 38Write-Heavy Workloads
  • 39Asynchronous Processing
  • 40Queue as a Shock Absorber
  • 41Important Trade-off: Latency vs Throughput
  • 42Database Scaling
  • 43Read Replicas
  • 44CDN as a Scaling Layer
  • 45Database Connection Pooling and Scaling
  • 46Fan-Out
  • 47Fan-Out Example
  • 48Cascading Failures
  • 49Rate Limiting During Scaling
  • 50Load Shedding During Overload
  • 51Priority-Based Scaling
  • 52Scale-Out Is Not Infinite
  • 53Scaling the Load Balancer
  • 54Scaling Storage
  • 55Scaling by Partitioning
  • 56Scaling by Replication
  • 57Scaling by Caching
  • 58Scaling by Asynchrony
  • 59The Critical Path
  • 60Scale the Critical Path First
  • 61Capacity Modeling Example
  • 62Scaling Example — URL Shortener
  • 63Scaling Example — Image Upload Service
  • 64Scaling Example — Video Processing
  • 65Scaling Example — Notification System
  • 66Autoscaling + Queue Example
  • 67Cost and Scaling
  • 68Over-Scaling
  • 69Under-Scaling
  • 70Scaling Feedback Loops
  • 71Scaling and Timeouts
  • 72Scaling Strategy
  • 73Step 1 — Measure
  • 74Step 2 — Find bottleneck
  • 75Step 3 — Optimize
  • 76Step 4 — Cache
  • 77Step 5 — Scale horizontally
  • 78Step 6 — Scale dependencies
  • 79Step 7 — Add asynchronous processing
  • 80Step 8 — Add autoscaling
  • 81Step 9 — Add protection
  • 82Common Scaling Mistakes
  • 83Mistake 1 — Only scaling application servers
  • 84Mistake 2 — Ignoring state
  • 85Mistake 3 — Assuming average traffic is enough
  • 86Mistake 4 — No headroom
  • 87Mistake 5 — Unlimited retries
  • 88Mistake 6 — Ignoring connection pools
  • 89Mistake 7 — Putting all work synchronously in APIs
  • 90Mistake 8 — Treating queues as infinite capacity
  • 91Mistake 9 — Autoscaling on the wrong metric
  • 92Mistake 10 — Scaling without measurement
  • 93Interview Questions
  • 94Q1. Vertical vs horizontal scaling?
  • 95Q2. Why is horizontal scaling usually easier with stateless services?
  • 96Q3. What happens when you add more application servers?
  • 97Q4. How would you handle a sudden traffic spike?
  • 98Q5. How do you calculate server count?
  • 99Q6. Why is peak traffic more important than average traffic?
  • 100Q7. How can caching improve scalability?
  • 101Q8. When should work move to a queue?
  • 102Q9. Can horizontal scaling solve every problem?
  • 103Q10. What is backpressure?
  • 104Practical Exercise
  • 105Version 1
  • 106Version 2
  • 107Version 3
  • 108Mini Project — Scalable API Platform
  • 109Master Mental Model
  • 110Chapter Summary
  • 111Scaling Fundamentals
  • 112Scaling Strategies
  • 113Application Scaling
  • 114Reliability Under Load
  • 115Capacity Planning
  • 116Architecture
  • 117Chapter 06 Master Checklist
  • 118What Comes Next?
  • 119Chapter 07 — Load Balancers
In this chapter (119 sections)
01Chapter Overview02What Does Scaling Mean?03Capacity04Scaling Dimensions05Compute06Memory07Storage08Network09Database10Connections11Background processing12Vertical Scaling13Advantages of Vertical Scaling14Limitations of Vertical Scaling15Horizontal Scaling16Vertical vs Horizontal Scaling17Example: Scaling an API18Why Statelessness Matters19Load Balancer20The Scaling Bottleneck21Bottleneck Chain22Little's Law23Throughput vs Latency24Throughput25Latency26Capacity Planning27Peak Traffic28Headroom29Scaling Application Servers30Autoscaling31CPU-Based Autoscaling32Request-Based Autoscaling33Queue-Based Autoscaling34Scaling Policies35Scaling Oscillation36Caching as a Scaling Strategy37Read-Heavy Workloads38Write-Heavy Workloads39Asynchronous Processing40Queue as a Shock Absorber41Important Trade-off: Latency vs Throughput42Database Scaling43Read Replicas44CDN as a Scaling Layer45Database Connection Pooling and Scaling46Fan-Out47Fan-Out Example48Cascading Failures49Rate Limiting During Scaling50Load Shedding During Overload51Priority-Based Scaling52Scale-Out Is Not Infinite53Scaling the Load Balancer54Scaling Storage55Scaling by Partitioning56Scaling by Replication57Scaling by Caching58Scaling by Asynchrony59The Critical Path60Scale the Critical Path First61Capacity Modeling Example62Scaling Example — URL Shortener63Scaling Example — Image Upload Service64Scaling Example — Video Processing65Scaling Example — Notification System66Autoscaling + Queue Example67Cost and Scaling68Over-Scaling69Under-Scaling70Scaling Feedback Loops71Scaling and Timeouts72Scaling Strategy73Step 1 — Measure74Step 2 — Find bottleneck75Step 3 — Optimize76Step 4 — Cache77Step 5 — Scale horizontally78Step 6 — Scale dependencies79Step 7 — Add asynchronous processing80Step 8 — Add autoscaling81Step 9 — Add protection82Common Scaling Mistakes83Mistake 1 — Only scaling application servers84Mistake 2 — Ignoring state85Mistake 3 — Assuming average traffic is enough86Mistake 4 — No headroom87Mistake 5 — Unlimited retries88Mistake 6 — Ignoring connection pools89Mistake 7 — Putting all work synchronously in APIs90Mistake 8 — Treating queues as infinite capacity91Mistake 9 — Autoscaling on the wrong metric92Mistake 10 — Scaling without measurement93Interview Questions94Q1. Vertical vs horizontal scaling?95Q2. Why is horizontal scaling usually easier with stateless services?96Q3. What happens when you add more application servers?97Q4. How would you handle a sudden traffic spike?98Q5. How do you calculate server count?99Q6. Why is peak traffic more important than average traffic?100Q7. How can caching improve scalability?101Q8. When should work move to a queue?102Q9. Can horizontal scaling solve every problem?103Q10. What is backpressure?104Practical Exercise105Version 1106Version 2107Version 3108Mini Project — Scalable API Platform109Master Mental Model110Chapter Summary111Scaling Fundamentals112Scaling Strategies113Application Scaling114Reliability Under Load115Capacity Planning116Architecture117Chapter 06 Master Checklist118What Comes Next?119Chapter 07 — Load Balancers

1. Chapter Overview#

So far, we have built the foundation:

Chapter 01 → How a Web Application Works
Chapter 02 → Networking Fundamentals
Chapter 03 → DNS Deep Dive
Chapter 04 → HTTP & API Design
Chapter 05 → Servers & Application Architecture

Now we reach one of the central questions in System Design:

How do we make an application handle more traffic?

Imagine an application currently handles:

1,000 requests/second

Then users grow and traffic becomes:

5,000 requests/second

Later:

50,000 requests/second

Eventually:

1,000,000 requests/second

A system that works perfectly at 1,000 requests/sec may fail completely at 50,000.

Scaling is the process of increasing a system's capacity while keeping required properties such as:

  • performance
  • availability
  • reliability
  • consistency
  • security
  • manageable cost

2. What Does Scaling Mean?#

Scaling means increasing the system's ability to handle workload.

Workload can increase because of:

  • more users
  • more requests
  • larger files
  • more database records
  • more background jobs
  • more simultaneous connections
  • more complex computations

A useful model is:

Traffic / Workload
        ↓
System Capacity
        ↓
Can capacity satisfy workload?

If:

Workload ≤ Capacity

the system can potentially keep up.

If:

Workload > Capacity

queues grow, latency increases, and eventually requests may fail.


3. Capacity#

Capacity is the amount of work a component can handle under defined conditions.

For an API:

Capacity = 2,000 requests/sec

For a database:

Capacity = 20,000 queries/sec

For a worker pool:

Capacity = 500 jobs/sec

Capacity is not a universal fixed number.

It depends on:

  • hardware
  • workload
  • request complexity
  • data size
  • latency target
  • concurrency
  • dependency performance

Therefore:

"This server supports 10,000 requests/sec" is incomplete without specifying the workload and performance target.


4. Scaling Dimensions#

A system can need scaling in different dimensions.

Compute#

More CPU is needed.

Memory#

More RAM is needed.

Storage#

More data must be stored.

Network#

More bandwidth is needed.

Database#

More queries or data must be handled.

Connections#

More concurrent users/connections exist.

Background processing#

More jobs need to be processed.

A common mistake is to scale the wrong resource.

Example:

CPU = 20%
Database = overloaded

Adding more application CPU will not solve the database bottleneck.


5. Vertical Scaling#

Vertical scaling means making a machine more powerful.

Example:

Before:
 
4 CPU
16 GB RAM
 
        ↓
 
After:
 
16 CPU
64 GB RAM

This is also called:

Scale up


6. Advantages of Vertical Scaling#

It is often simple.

Architecture:

Client
  ↓
Server
  ↓
Database

can remain largely unchanged.

Advantages:

  • simple architecture
  • fewer machines
  • easier deployment
  • fewer network hops
  • easier debugging
  • often good for early-stage systems

7. Limitations of Vertical Scaling#

A machine has practical limits.

Eventually:

CPU cannot be increased indefinitely
RAM cannot be increased indefinitely

There are also:

  • hardware limits
  • instance size limits
  • cost increases
  • single-machine failure risk

If everything depends on one machine:

Machine failure
      ↓
Entire service unavailable

Vertical scaling alone therefore does not solve every problem.


8. Horizontal Scaling#

Horizontal scaling means adding more machines or instances.

Also called:

Scale out

Example:

Before:
 
Client
  ↓
Server 1
 
After:
 
              ┌── Server 1
Client → LB ──┼── Server 2
              ├── Server 3
              └── Server 4

Instead of one powerful machine handling all requests, multiple instances share the workload.


9. Vertical vs Horizontal Scaling#

Vertical Scaling Horizontal Scaling
Bigger machine More machines
Simpler initially More architectural complexity
Hardware limits Can scale across many instances
Often easier state management Works best with stateless services
Single-machine failure can matter Can provide redundancy
Scale-up Scale-out

A production system may use both.


10. Example: Scaling an API#

Suppose one application server handles:

1,000 requests/sec

Traffic:

1,000 req/sec

One server may be sufficient.

Traffic increases:

3,000 req/sec

Possible design:

              Load Balancer
             /      |      \
            ↓       ↓       ↓
          App 1   App 2   App 3

If each instance handles approximately 1,000 req/sec, three instances provide roughly the required compute capacity, subject to real-world overhead and bottlenecks.


11. Why Statelessness Matters#

Horizontal scaling becomes much easier when application instances are stateless.

Bad design:

User
 ↓
App 1
 ↓
Session stored in App 1 memory

Next request:

User
 ↓
App 2
 ↓
Session missing

Better:

App 1 ─┐
App 2 ─┼──→ Shared Redis / Database
App 3 ─┘

or use an appropriate stateless authentication mechanism.

Then:

Request 1 → App 1
Request 2 → App 3
Request 3 → App 2

All instances can serve the user.


12. Load Balancer#

A load balancer distributes traffic across multiple servers.

                    Load Balancer
                  /      |       \
                 ↓       ↓        ↓
               App 1   App 2    App 3

It can:

  • distribute traffic
  • detect unhealthy instances
  • terminate connections
  • provide failover
  • support scaling

We will study load balancers deeply in Chapter 07.

For now, remember:

Horizontal scaling usually needs a mechanism for distributing traffic.


13. The Scaling Bottleneck#

Suppose:

Load Balancer
     ↓
App 1 ─┐
App 2 ─┼──→ Database
App 3 ─┤
App 4 ─┘

We add more application servers:

App 1
App 2
App 3
...
App 100

But the database remains:

One database

Now the database may become the bottleneck.

This teaches an important principle:

Scaling one component can move the bottleneck to another component.


14. Bottleneck Chain#

Consider:

Internet
   ↓
Load Balancer
   ↓
Application
   ↓
Cache
   ↓
Database

The bottleneck might be:

Network

or:

Application CPU

or:

Cache

or:

Database

or:

External API

System design is partly the process of identifying the current bottleneck and scaling the correct layer.


15. Little's Law#

A useful relationship for capacity reasoning is:

L = λ × W

Where:

  • L = average number of items in the system
  • λ = arrival rate
  • W = average time in the system

For example:

Arrival rate = 100 requests/sec
Average response time = 0.5 sec

Then approximately:

L = 100 × 0.5
  = 50

So there are approximately 50 requests in the system on average.

This becomes useful when reasoning about concurrency.


16. Throughput vs Latency#

These are different.

Throughput#

How much work is completed per unit time.

Example:

5,000 requests/sec

Latency#

How long one request takes.

Example:

120 ms

A system can have:

High throughput
+
High latency

or:

Low throughput
+
Low latency

You must optimize for the actual requirement.


17. Capacity Planning#

Before scaling, estimate the workload.

Suppose:

10 million users

But only:

10% active daily

Then:

1 million DAU

Suppose each active user generates:

20 API requests/day

Then:

1,000,000 × 20
= 20,000,000 requests/day

Average requests/sec:

20,000,000 / 86,400
≈ 231 requests/sec

But average traffic is not enough.

Peak traffic may be much higher.


18. Peak Traffic#

Suppose average traffic is:

231 req/sec

but peak traffic is 10× average:

≈ 2,310 req/sec

The system must be designed around an appropriate peak requirement rather than only the daily average.

Peak factors can come from:

  • business hours
  • launches
  • notifications
  • breaking news
  • sales
  • sports events
  • traffic bursts

19. Headroom#

Do not design capacity exactly at expected traffic.

Suppose expected peak:

2,000 req/sec

and measured safe capacity:

2,500 req/sec

Headroom:

500 req/sec

or:

25%

Headroom helps absorb:

  • traffic spikes
  • unexpected workload
  • instance failures
  • deployment events
  • performance degradation

The appropriate amount depends on the system.


20. Scaling Application Servers#

A typical scalable application architecture:

                    Internet
                       ↓
                 Load Balancer
                       ↓
          ┌────────────┼────────────┐
          ↓            ↓            ↓
        App 1        App 2        App 3
          │            │            │
          └────────────┼────────────┘
                       ↓
                    Cache
                       ↓
                   Database

The application tier is horizontally scalable.


21. Autoscaling#

Instead of manually adding servers:

Traffic increases
       ↓
More instances

an autoscaling system can adjust capacity automatically.

Conceptually:

CPU / RPS / Queue Depth
          ↓
     Autoscaler
          ↓
  Add / Remove instances

22. CPU-Based Autoscaling#

Example:

Target CPU = 60%

If average CPU becomes:

85%

the system can add instances.

If traffic decreases:

CPU = 20%

it may remove instances.

CPU is useful, but not always the best scaling metric.


23. Request-Based Autoscaling#

For APIs, requests per second can be a better signal.

Example:

Target = 500 req/sec/instance

If:

Total traffic = 2,000 req/sec

we may need roughly:

4 instances

assuming each instance can reliably handle the target workload.


24. Queue-Based Autoscaling#

For asynchronous systems:

Queue depth
    ↓
Autoscaler
    ↓
Workers

Example:

Queue = 10,000 jobs
       ↓
Add workers

When:

Queue = 50 jobs

workers can scale down.

This is often more meaningful than CPU for background workloads.


25. Scaling Policies#

Autoscaling needs policies.

Examples:

If CPU > 70% for 5 minutes
    add instances

or:

If queue depth > 5,000
    add workers

There are trade-offs:

  • scaling too quickly → cost
  • scaling too slowly → latency
  • aggressive scale-down → instability
  • insufficient warm capacity → cold-start delays

26. Scaling Oscillation#

Suppose an autoscaler behaves like this:

CPU high
 ↓
Add 10 servers
 ↓
CPU becomes low
 ↓
Remove 10 servers
 ↓
CPU high again
 ↓
Add 10 servers

This repeated scaling behavior is undesirable.

It can be caused by:

  • overly aggressive thresholds
  • insufficient cooldown
  • delayed metrics
  • large scaling steps

Autoscaling systems need stabilization.


27. Caching as a Scaling Strategy#

Suppose every request queries the database.

100,000 requests/sec
        ↓
100,000 DB queries/sec

This may overwhelm the database.

Add caching:

100,000 requests/sec
        ↓
Cache
 ├── 90,000 hits
 └── 10,000 misses
        ↓
Database

The database load can drop substantially.

Caching is therefore not only a latency optimization.

It can also be a scalability mechanism.

We will study caching deeply later.


28. Read-Heavy Workloads#

Suppose:

90% reads
10% writes

Scaling strategies can include:

  • caching
  • read replicas
  • CDN
  • denormalized read models
  • search systems

The correct strategy depends on access patterns.


29. Write-Heavy Workloads#

Suppose:

20% reads
80% writes

Caching alone may not solve the bottleneck.

Potential strategies include:

  • batching
  • asynchronous processing
  • partitioning
  • sharding
  • queueing
  • write optimization

These will become important later in the course.


30. Asynchronous Processing#

Suppose an API receives:

POST /generate-report

Generating the report takes:

30 seconds

Instead of holding the HTTP request open:

Client
 ↓
API
 ↓
Generate report
 ↓
30 seconds
 ↓
Response

we can use:

Client
 ↓
API
 ↓
Queue
 ↓
202 Accepted

Then:

Queue
 ↓
Worker
 ↓
Generate report
 ↓
Storage

This allows the API tier to handle more concurrent requests.


31. Queue as a Shock Absorber#

A queue can absorb temporary bursts.

Suppose:

Normal workload = 1,000 jobs/sec
Burst = 5,000 jobs/sec
Worker capacity = 1,500 jobs/sec

Without a queue:

4,000 jobs/sec rejected/failed

With a queue:

5,000 jobs/sec
      ↓
Queue
      ↓
1,500 jobs/sec processed
      ↓
Backlog gradually decreases

A queue does not create infinite capacity.

It changes immediate rejection into delayed processing.


32. Important Trade-off: Latency vs Throughput#

Batching and queueing can improve throughput.

But users may experience additional latency.

For example:

Synchronous:
request → process → response
latency = 100 ms

Asynchronous:

request → queue → worker → result
latency = seconds

The correct choice depends on whether the operation must be synchronous.


33. Database Scaling#

A database can become the main bottleneck.

Possible strategies include:

Vertical scaling
Caching
Read replicas
Partitioning
Sharding
Database optimization
Connection pooling

We will cover these systematically in later chapters.

For now, understand:

Adding more application servers does not automatically scale the database.


34. Read Replicas#

For read-heavy workloads:

             Primary DB
             /        \
            ↓          ↓
       Replica 1   Replica 2

Writes go to the primary.

Reads can potentially go to replicas.

Example:

Write
 ↓
Primary
 
Read
 ↓
Replica

This can increase read capacity.

But replication introduces consistency considerations.

We will study replication in Chapter 13.


35. CDN as a Scaling Layer#

Suppose users repeatedly request:

images
videos
CSS
JavaScript

Serving everything from application servers is inefficient.

A CDN can cache content near users.

User
 ↓
CDN Edge
 ├── Cache Hit → Response
 └── Cache Miss
          ↓
       Origin

This reduces:

  • origin traffic
  • bandwidth
  • application load
  • latency for cached content

CDNs will be covered in Chapter 08.


36. Database Connection Pooling and Scaling#

Suppose:

20 application servers

Each has:

50 DB connections

Potential total:

20 × 50 = 1,000 DB connections

If the database safely supports only 300 connections, simply adding application servers can make the database problem worse.

This is a crucial scaling lesson:

Every horizontally scaled layer can multiply pressure on its dependencies.


37. Fan-Out#

Suppose one API request calls:

Service A
Service B
Service C
Service D

One incoming request creates four downstream requests.

If traffic is:

10,000 API requests/sec

then downstream traffic can become approximately:

40,000 requests/sec

before considering retries or additional calls.

This is called fan-out.

High fan-out can create scaling problems.


38. Fan-Out Example#

                  API
                   │
       ┌───────────┼───────────┐
       ↓           ↓           ↓
    Service A   Service B   Service C
       ↓           ↓           ↓
    Database    Cache       External API

If Service B becomes slow, the whole API may become slow.

Scaling the API servers may not solve the problem.


39. Cascading Failures#

Consider:

Service A
   ↓
Service B
   ↓
Database

Database becomes slow.

Then:

Service B waits
   ↓
connections occupied
   ↓
Service A waits
   ↓
API requests accumulate
   ↓
Application workers exhausted
   ↓
Entire service becomes unavailable

This is a cascading failure.

Scaling requires thinking about dependencies, not only the main server.


40. Rate Limiting During Scaling#

Suppose traffic suddenly increases from:

10,000 req/sec

to:

100,000 req/sec

Autoscaling takes time.

Rate limiting can protect the system during the scaling delay.

Traffic
  ↓
Rate Limiter
  ↓
Allowed traffic
  ↓
Application

Excess traffic may receive:

429 Too Many Requests

This protects system capacity.


41. Load Shedding During Overload#

Suppose:

Capacity = 10,000 req/sec
Traffic = 20,000 req/sec

The system may intentionally reject some requests.

Possible strategy:

Critical requests → allow
Low-priority requests → reject/defer

This is especially useful when not all operations are equally important.


42. Priority-Based Scaling#

Consider an e-commerce system.

High priority:

Payment
Order creation
Checkout

Lower priority:

Recommendations
Analytics
Personalized suggestions

During overload:

Keep checkout functioning
Reduce recommendation traffic

This is a form of graceful degradation and load prioritization.


43. Scale-Out Is Not Infinite#

A common misconception:

"Just keep adding servers."

In reality, bottlenecks can move to:

Database
Cache
Network
Load Balancer
Storage
External APIs
Queues
Coordination systems

Eventually the architecture itself may need to change.


44. Scaling the Load Balancer#

Even the load balancer can become a bottleneck.

Large systems may use:

DNS / Anycast
      ↓
Multiple load balancers
      ↓
Application clusters

or managed load-balancing infrastructure.

The principle is:

A supposedly central component must also have sufficient capacity and redundancy.


45. Scaling Storage#

Storage requirements can grow from:

100 GB
 ↓
1 TB
 ↓
100 TB
 ↓
Petabytes

At large scale, systems may use:

  • object storage
  • distributed file systems
  • partitioned databases
  • data lakes
  • archival storage

Storage architecture becomes its own system-design problem.


46. Scaling by Partitioning#

Suppose one dataset is too large for one machine.

Partition it:

Data
 ├── Partition 1
 ├── Partition 2
 ├── Partition 3
 └── Partition 4

Each partition stores a subset of the data.

Example:

Users A–F → Partition 1
Users G–L → Partition 2
Users M–R → Partition 3
Users S–Z → Partition 4

This concept leads toward sharding.

We will study database partitioning and sharding later.


47. Scaling by Replication#

Replication means maintaining multiple copies.

Example:

Primary
  ↓
Replica 1
Replica 2
Replica 3

Replication can improve:

  • read capacity
  • availability
  • fault tolerance

But it creates:

  • replication lag
  • consistency concerns
  • additional coordination

48. Scaling by Caching#

Replication stores additional copies in persistent or semi-persistent systems.

Caching stores frequently needed data closer to consumers.

Client
 ↓
Cache
 ↓ miss
Database

The key trade-off is:

freshness
   ↕
performance

We will study this deeply in caching chapters.


49. Scaling by Asynchrony#

Some work does not need to happen during the user request.

Move it out:

Synchronous path
       ↓
Queue
       ↓
Workers

This reduces the work performed directly on the request path.

Example:

User registration
 ↓
Create account
 ↓
Return response
 
Background:
 ↓
Send welcome email
 ↓
Generate analytics event
 ↓
Update recommendation model

50. The Critical Path#

The critical path is the work required before a response can be returned.

Example:

Request
 ↓
Authentication
 ↓
Database
 ↓
Response

If email sending is not required before the response:

Request
 ↓
Authentication
 ↓
Database
 ↓
Response
 
Background:
 ↓
Email

Removing unnecessary work from the critical path improves latency and often scalability.


51. Scale the Critical Path First#

Suppose:

API
 ↓
Service A
 ↓
Service B
 ↓
Service C

but Service C only performs analytics.

If analytics does not affect the user response:

API
 ↓
Service A
 ↓
Service B
 ↓
Response
 
Background:
Service C

This can significantly reduce request-path work.


52. Capacity Modeling Example#

Suppose:

Peak traffic = 10,000 req/sec

One application instance safely handles:

500 req/sec

Required instances:

10,000 / 500
= 20

Suppose we want 25% headroom:

20 × 1.25
= 25 instances

If we also want to survive the loss of 5 instances:

25 + 5
= 30 instances

This is a simplified capacity model.

Real capacity planning should account for workload variation, dependency limits, autoscaling delay, failure domains, and measured performance.


53. Scaling Example — URL Shortener#

Suppose:

10 million redirects/day

Average:

10,000,000 / 86,400
≈ 116 requests/sec

Suppose peak is:

10× average
≈ 1,160 requests/sec

Architecture:

Users
  ↓
CDN / Load Balancer
  ↓
Stateless API Servers
  ↓
Redis Cache
  ↓
Database

Most popular URLs can be served from cache.


54. Scaling Example — Image Upload Service#

Suppose users upload:

10,000 images/minute

Do not make application servers perform every operation synchronously.

Better:

Client
 ↓
Upload API
 ↓
Object Storage
 ↓
Queue
 ↓
Image Workers
 ├── Resize
 ├── Compress
 └── Generate thumbnails

This separates upload traffic from processing capacity.


55. Scaling Example — Video Processing#

Video processing is CPU/GPU intensive.

A better architecture:

Client
 ↓
Upload Service
 ↓
Object Storage
 ↓
Job Queue
 ↓
Worker Fleet
 ├── Worker 1
 ├── Worker 2
 ├── Worker 3
 └── Worker N
 ↓
Processed Video
 ↓
Object Storage

Workers can scale according to:

queue depth
processing time
CPU/GPU utilization

56. Scaling Example — Notification System#

Suppose:

1 million notifications

Instead of sending synchronously:

API
 ↓
Send 1 million notifications
 ↓
Response

use:

API
 ↓
Queue
 ↓
Notification Workers
 ↓
Email/SMS/Push providers

The queue absorbs bursts and workers control processing rate.


57. Autoscaling + Queue Example#

                Queue
                  │
          Queue depth = 50,000
                  │
                  ▼
              Autoscaler
          ┌───────┼───────┐
          ▼       ▼       ▼
       Worker  Worker   Worker
          │       │       │
          └───────┼───────┘
                  ▼
               Storage

As backlog increases:

queue depth ↑
    ↓
workers ↑

As backlog decreases:

queue depth ↓
    ↓
workers ↓

58. Cost and Scaling#

Scaling is not only about performance.

Suppose:

10 servers → ₹X/month
100 servers → ₹10X/month

If traffic grows only 2× but infrastructure cost grows 10×, architecture may need optimization.

System design balances:

Performance
Availability
Reliability
Complexity
Cost

59. Over-Scaling#

Running too much capacity can waste resources.

Example:

Traffic = 100 req/sec
Capacity = 100,000 req/sec

The system may be extremely reliable, but unnecessarily expensive.

The correct capacity depends on:

  • traffic
  • failure requirements
  • scaling speed
  • business criticality
  • cost constraints

60. Under-Scaling#

Under-provisioning causes:

High CPU
 ↓
High latency
 ↓
Timeouts
 ↓
Retries
 ↓
More traffic
 ↓
Higher CPU
 ↓
Failure

This can create a feedback loop.


61. Scaling Feedback Loops#

A particularly dangerous pattern:

Service overloaded
      ↓
Requests become slow
      ↓
Clients timeout
      ↓
Clients retry
      ↓
Traffic increases
      ↓
Service becomes even slower

Therefore:

Scaling and retry policies must be designed together.

Retries without capacity planning can amplify failures.


62. Scaling and Timeouts#

Suppose one instance normally processes:

500 req/sec

At overload:

700 req/sec

latency rises.

Clients timeout.

Retries create:

900 req/sec

Now the system is even more overloaded.

Therefore production systems need:

  • bounded retries
  • rate limiting
  • load shedding
  • autoscaling
  • timeouts
  • backpressure

63. Scaling Strategy#

A practical approach:

Step 1 — Measure#

Find:

RPS
latency
CPU
memory
DB load
cache hit rate
queue depth
error rate

Step 2 — Find bottleneck#

Do not guess.

Step 3 — Optimize#

Remove unnecessary work.

Step 4 — Cache#

If workload is cache-friendly.

Step 5 — Scale horizontally#

Add instances where appropriate.

Step 6 — Scale dependencies#

Database, queue, storage, etc.

Step 7 — Add asynchronous processing#

Move non-critical work off the request path.

Step 8 — Add autoscaling#

Automate capacity changes.

Step 9 — Add protection#

Rate limiting, backpressure, load shedding.


64. Common Scaling Mistakes#

Mistake 1 — Only scaling application servers#

The database may be the real bottleneck.

Mistake 2 — Ignoring state#

Local sessions can prevent effective horizontal scaling.

Mistake 3 — Assuming average traffic is enough#

Peak traffic matters.

Mistake 4 — No headroom#

The system can fail during small traffic spikes.

Mistake 5 — Unlimited retries#

Retries can amplify outages.

Mistake 6 — Ignoring connection pools#

More servers can create too many database connections.

Mistake 7 — Putting all work synchronously in APIs#

Expensive background work should often be asynchronous.

Mistake 8 — Treating queues as infinite capacity#

Queues delay work; they do not eliminate capacity limits.

Mistake 9 — Autoscaling on the wrong metric#

CPU may be low while queue depth or latency is extremely high.

Mistake 10 — Scaling without measurement#

Always identify the bottleneck first.


65. Interview Questions#

Q1. Vertical vs horizontal scaling?#

Vertical scaling makes one machine more powerful.

Horizontal scaling adds more machines or instances.


Q2. Why is horizontal scaling usually easier with stateless services?#

Because requests can be routed to any healthy instance without depending on local state.


Q3. What happens when you add more application servers?#

You increase application compute capacity, but may increase pressure on:

  • database
  • cache
  • network
  • external services
  • connection pools

Q4. How would you handle a sudden traffic spike?#

Possible mechanisms:

CDN
Caching
Load balancing
Autoscaling
Rate limiting
Queueing
Load shedding
Graceful degradation

The correct combination depends on workload.


Q5. How do you calculate server count?#

A simplified estimate:

Required instances
≈ Peak traffic / Safe capacity per instance

Then add appropriate headroom and failure capacity.


Q6. Why is peak traffic more important than average traffic?#

Because the system must remain within acceptable performance limits during expected high-load periods.


Q7. How can caching improve scalability?#

It reduces repeated work and decreases load on downstream systems such as databases.


Q8. When should work move to a queue?#

When the work does not need to complete before the user response and can tolerate asynchronous processing.


Q9. Can horizontal scaling solve every problem?#

No.

The bottleneck may move to:

Database
Cache
Network
Storage
Queue
External dependency
Coordination layer

Q10. What is backpressure?#

A mechanism that prevents incoming work from overwhelming downstream capacity.


66. Practical Exercise#

Design a scalable URL shortener.

Requirements:

100 million URLs
10 million redirects/day
10× peak traffic
99.9% availability
Low redirect latency

Start with:

Client
 ↓
Application
 ↓
Database

Then evolve it.

Version 1#

Client
 ↓
App
 ↓
Database

Version 2#

Client
 ↓
Load Balancer
 ↓
App 1 / App 2 / App 3
 ↓
Database

Version 3#

Client
 ↓
Load Balancer
 ↓
Stateless App Servers
 ↓
Redis
 ↓
Database

Now answer:

  1. What is the bottleneck?
  2. What can be cached?
  3. What should be horizontally scaled?
  4. What happens when one app server fails?
  5. What happens when Redis fails?
  6. What happens when the database becomes slow?
  7. How would you handle a traffic spike?
  8. How would you estimate the number of instances?

67. Mini Project — Scalable API Platform#

Design:

                         Internet
                            │
                            ▼
                         CDN
                            │
                            ▼
                     Load Balancer
                            │
                 ┌──────────┼──────────┐
                 ▼          ▼          ▼
               App 1      App 2      App 3
                 │          │          │
                 └──────────┼──────────┘
                            │
                    ┌───────┴────────┐
                    ▼                ▼
                  Redis          PostgreSQL
                                     │
                                     ▼
                                  Replica

Add:

Queue
 ↓
Workers

Then define:

  • scaling metric
  • minimum instances
  • maximum instances
  • health checks
  • timeout
  • retry policy
  • rate limit
  • cache strategy
  • database connection pool
  • overload behavior

68. Master Mental Model#

When someone asks:

"How would you scale this system?"

Do not immediately say:

"Add more servers."

Instead think:

1. What is the workload?
        ↓
2. What is the peak?
        ↓
3. What is the current capacity?
        ↓
4. What is the bottleneck?
        ↓
5. Can we optimize it?
        ↓
6. Can we cache?
        ↓
7. Can we scale horizontally?
        ↓
8. Are instances stateless?
        ↓
9. Can dependencies handle the added load?
        ↓
10. Can expensive work become asynchronous?
        ↓
11. Do we need autoscaling?
        ↓
12. How do we protect the system during overload?

This is much stronger than simply proposing more machines.


69. Chapter Summary#

You should now understand:

Scaling Fundamentals#

  • workload
  • capacity
  • bottlenecks
  • throughput
  • latency
  • peak traffic
  • headroom

Scaling Strategies#

  • vertical scaling
  • horizontal scaling
  • replication
  • partitioning
  • caching
  • asynchronous processing

Application Scaling#

  • stateless services
  • load balancing
  • autoscaling
  • CPU-based scaling
  • request-based scaling
  • queue-based scaling

Reliability Under Load#

  • rate limiting
  • backpressure
  • load shedding
  • graceful degradation
  • cascading failures
  • retry amplification

Capacity Planning#

  • requests/sec
  • peak traffic
  • capacity per instance
  • headroom
  • failure capacity
  • Little's Law

Architecture#

  • scalable application tier
  • cache layer
  • database layer
  • queues
  • worker fleets
  • dependency bottlenecks

70. Chapter 06 Master Checklist#

Before moving forward, make sure you can explain:

  • What scaling means
  • Capacity
  • Vertical scaling
  • Horizontal scaling
  • Scale up vs scale out
  • Stateless services
  • Load balancer role
  • Scaling bottlenecks
  • Throughput
  • Latency
  • Little's Law
  • Capacity planning
  • Peak traffic
  • Headroom
  • Autoscaling
  • CPU-based autoscaling
  • Request-based autoscaling
  • Queue-based autoscaling
  • Scaling oscillation
  • Caching for scalability
  • Read-heavy workloads
  • Write-heavy workloads
  • Asynchronous processing
  • Queue as a shock absorber
  • Database scaling
  • Read replicas
  • CDN scaling
  • Connection pool pressure
  • Fan-out
  • Cascading failures
  • Rate limiting
  • Load shedding
  • Priority-based scaling
  • Partitioning
  • Replication
  • Critical path
  • Scaling feedback loops
  • Timeouts and retries during overload
  • Cost-aware scaling

71. What Comes Next?#

Chapter 07 — Load Balancers#

We now have multiple application servers.

The next question is:

How do we distribute traffic intelligently across them?

We will deeply study:

Client
   ↓
Load Balancer
   ├── Server 1
   ├── Server 2
   ├── Server 3
   └── Server 4

Topics will include:

  • what a load balancer is
  • Layer 4 vs Layer 7 load balancing
  • reverse proxy vs load balancer
  • health checks
  • round robin
  • weighted round robin
  • least connections
  • IP hash
  • consistent hashing
  • sticky sessions
  • connection draining
  • failover
  • active-active architecture
  • active-passive architecture
  • load balancer bottlenecks
  • high availability
  • global load balancing
  • DNS + load balancer architecture
  • real-world load-balancing design
  • interview questions
  • practical architecture exercises

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 05 — Servers & Application ArchitectureNext ChapterChapter 07 — Load Balancers
PrevNext