An app that feels fast for a few hundred users can fall over when a few lakh arrive at once. Nothing in the code changed; there is simply more work than the machines can finish in time. Pages load slowly, requests time out, and the database sits at 100%.

Scalability is a system's ability to handle more load by adding resources, without rewriting the whole application. In this article we follow one example the whole way: an online exam platform on results day. Students log in, open their scorecards, download PDFs, and the platform has to survive the moment results go live.

1. The Problem

In the first version, one server runs both the Java application and the MySQL database. On a normal day that is fine. At 10 AM on results day, a huge number of students click "View result" in the same minute.

The server's CPU hits 100%, requests wait in a queue, and some of them time out. The goal of scalability work is to keep the platform responsive while the load grows, ideally without the users noticing anything.

Scalability is not yes or no

A system can scale well for one kind of growth and badly for another. Always say what is growing: requests per second, students online at the same time, or the amount of stored data.

2. Measuring the Load

Before changing anything, write down what the load actually looks like. Three numbers come up again and again:

MetricWhat it measuresResults day example
Requests per secondHow often requests arrive10,000 requests/second at peak
Concurrent usersStudents active right now2,00,000 online in the first hour
Data volumeHow much is stored40 lakh result records and their PDFs

Not every request costs the same. Opening a scorecard is one indexed lookup; generating a rank list touches every student in the exam.

RequestWork involvedCost
View scorecardOne lookup by roll numberLow
Download result PDFBuild or fetch a file, send a few hundred KBMedium
Generate state rank listSort lakhs of rowsHigh

A quick capacity estimate in Java

A back-of-the-envelope estimate tells you roughly how many servers you need before you spend any money. The program below turns "2 lakh students online" into requests per second, uses Little's Law (requests in flight = arrival rate x time per request) to see how much work is in progress at any moment, and then works out the number of app servers, keeping each one under 70% busy.

Output

Peak load         : 10000 requests/second
Requests in flight: 800 at any moment
App servers needed: 18 (each at most 70% busy)

The 800 requests per server is not a guess: it comes from a load test of your own Java service (tools such as JMeter or Gatling are common for this). The 30% headroom is there because traffic never arrives perfectly evenly.

3. Finding the Bottleneck

Suppose scorecards normally load in 50 ms but now take 900 ms. Before adding anything, find out where the time goes:

What we checkSymptomLikely cause
CPUStuck at 100%The app is doing more work than the cores can handle
MemoryLong GC pauses or OutOfMemoryErrorThe JVM heap or the data set no longer fits in RAM
DiskHigh I/O waitThe database is reading from slow storage
Database queriesA few queries take most of the timeA missing index or an expensive query
Connection poolThreads waiting for a connectionThe pool (for example HikariCP) is too small or queries hold connections too long

The part that limits the whole system is the bottleneck. Fix one, and the next one appears, so this is a loop rather than a one-time job.

Adding more app servers will not fix a missing index on the results table. Always find the cause first; often the cheapest fix is an index, a smaller query, or a cache, not new hardware.

4. Vertical Scaling (Scale Up)

The simplest move is to make the existing machine bigger: more CPU, more RAM, faster disks.

If CPU or memory was the limit, this can buy a lot of headroom with no code change. For a Java service you usually also raise the JVM heap (-Xmx) so the application can actually use the new RAM. The upgrade has to match the bottleneck, though: more CPU does nothing if requests are waiting on a slow disk.

ProsCons
Simple: still one machine to runHard ceiling: there is a biggest machine you can buy
Usually no code changesCost grows faster than capacity at the high end
No network calls between partsUpgrading often needs a restart
Easy to keep data consistentStill a single point of failure

5. Separating the Database

After the upgrade, the Java app and MySQL still fight over the same CPU, memory and disk. The next step is to give the database its own machine.

Now each machine can be sized for its job: the app server for CPU, the database server for memory (so more of the results table stays cached in RAM) and fast disks. This is still vertical scaling; we just have two machines, each scaled on its own.

6. Horizontal Scaling (Scale Out)

When one app server is no longer enough, we stop making it bigger and run several copies of the Java application behind a load balancer.

Need more capacity? Add another server. If one becomes unhealthy, the load balancer stops sending it traffic and the others carry on, as long as they have spare capacity. But there is one catch we have to solve first.

The session problem

Riya logs in through app server 1, which keeps her session in its own memory (the default HttpSession in a single Java server). Her next request lands on app server 2, which has never heard of her.

One workaround is sticky sessions: the load balancer always sends Riya back to server 1. It works, but traffic spreads unevenly, and if server 1 dies, every student on it is logged out.

Stateless app servers

The cleaner fix is to move the state out of the app servers. Sessions go to a shared store such as Redis (in Spring Boot, Spring Session with Redis does this with almost no code), and files such as uploaded answer sheets go to object storage like Amazon S3 instead of a server's local disk.

The system still has state; it just no longer lives inside an individual app server. That makes servers easy to add, remove or replace. The Java simulation below shows the difference: with local sessions the second request fails, with a shared store it works even after a server crashes.

Output

-- sessions in each server's memory --
login  : app-1 created a session for Riya
request: app-2 -> no session, log in again
-- sessions in a shared store (Redis) --
login  : app-1 created a session for Riya
request: app-2 -> welcome back, Riya
app-1 crashes
request: app-3 -> welcome back, Riya

7. Vertical vs Horizontal Scaling

Vertical scalingHorizontal scaling
How it worksMake one machine biggerAdd more machines behind a load balancer
Code changesUsually noneApp servers must be stateless
LimitThe biggest machine availableKeeps growing while shared parts keep up
When a server failsNothing takes overThe load balancer routes around it
CostGets steep at the high endRoughly linear per server
ComplexityLowHigher: more machines, network calls, shared state

Real systems use both. The stateless Java app tier scales out, while the database often stays on one large machine for as long as it can. The next question is how to stop that database from drowning in queries from all those app servers.

8. Caching

On results day, the same scorecards are requested again and again: students refresh, parents check, friends compare. Running the same query every time is wasted work. With the cache-aside pattern, the app looks in the cache first and only goes to the database on a miss, then stores the result for next time.

The hard part is stale data. If a result is re-evaluated, the cached copy is now wrong. The usual options are: delete the cache entry when the data changes, write the new value to both places, or give every entry a time to live (TTL) and accept slightly old data until it expires. The Java code below uses deletion plus a 60-second TTL.

Output

t=0   A101 -> 78  MISS, read database
t=1   A101 -> 78  HIT
t=2   A102 -> 91  MISS, read database
t=3   A101 -> 78  HIT
t=4   A102 -> 91  HIT
      A101 re-evaluated, cache entry removed
t=6   A101 -> 84  MISS, read database
t=7   A101 -> 84  HIT
t=70  A102 -> 91  MISS, read database
Reads: 8, database queries: 4

Eight reads cost only four database queries, and the re-evaluated marks show up immediately because the old entry was removed. In Spring Boot, @Cacheable and @CacheEvict on a service method give you the same behaviour, with Redis or Caffeine underneath.

When one cache server runs out of memory, the cache itself is split across several nodes, using the key (for example the roll number) to decide which node holds each entry.

9. Read Replicas

The cache only helps for data that is read repeatedly. Everything else still reaches the database. If reads are the problem, add read replicas: extra databases that keep a copy of the primary's data.

All writes still go through the primary, so replicas add read capacity but not write capacity. Copying changes also takes a moment, which creates replication lag: a student who just changed their exam centre may read the old value from a replica. The common fix is "read your own writes": for a short time after someone writes, send their reads to the primary.

Output

t=0 Riya  writes riya.centre = Hyderabad (primary)
t=1 Riya  reads  riya.centre = Hyderabad (primary)
t=1 Admin reads  riya.centre = Pune (replica-1)
t=3 Admin reads  riya.centre = Hyderabad (replica-2)

In a Spring application this routing is usually done with an AbstractRoutingDataSource that picks the replica for @Transactional(readOnly = true) methods and the primary for everything else.

10. Sharding

Replicas cannot help when the data itself or the number of writes outgrows one primary, because every replica holds the full data set and every write still lands on the primary. The next step is sharding: splitting the data across several databases, each holding only part of it.

The field that decides where a row goes is the shard key. Here it is the student ID. Queries for one student go to exactly one shard; queries across all students (like finding the topper) have to ask every shard and merge the answers.

Output

shard 0: students [102, 105, 108]
shard 1: students [103, 106, 109]
shard 2: students [101, 104, 107]
Student 104: ask shard 2 only -> score 64
Topper: ask all 3 shards -> student 108 with 99

Pick a shard key that keeps your most common queries on a single shard. Also note that simple id % 3 makes it painful to add a fourth shard later, because most rows would move; real systems use consistent hashing or a lookup table to avoid that.

11. Queues and Background Work

Some work does not need to finish before the student gets a reply. When a student submits a mock test, scoring it and emailing the result can happen a few seconds later. So the app saves the answers, puts a job on a queue, and replies "Submitted" straight away. Background workers pick up the jobs.

A queue does not reduce the total work; it moves it out of the request so response times stay low, and it absorbs short spikes. If the queue keeps growing, add workers. In Java this is usually Kafka or RabbitMQ between services, or a BlockingQueue with a thread pool inside one application.

12. Autoscaling

Traffic on results day is not flat: it climbs fast at 10 AM and drops by evening. Paying for the peak all day is wasteful, and reacting by hand is too slow. Autoscaling adds servers when a metric stays high and removes them when it stays low.

The Java simulation below runs such a rule minute by minute. Notice that it waits for CPU to stay high for three minutes before acting, so a single spike does not trigger scaling, and it removes servers slowly, one at a time, because scaling in too fast causes flapping.

Output

min  1 | CPU  60% | 4 servers
min  2 | CPU  75% | 4 servers
min  3 | CPU  80% | 4 servers
min  4 | CPU  82% | 4 servers
min  5 | CPU  87% | -> add 2 servers, now 6
min  6 | CPU  70% | 6 servers
min  7 | CPU  83% | 6 servers
min  8 | CPU  86% | 6 servers
min  9 | CPU  83% | -> add 2 servers, now 8
min 10 | CPU  50% | 8 servers
min 11 | CPU  27% | 8 servers
min 12 | CPU  17% | 8 servers
min 13 | CPU  15% | 8 servers
min 14 | CPU  13% | 8 servers
min 15 | CPU  12% | -> remove 1 server, now 7
min 16 | CPU  14% | 7 servers
min 17 | CPU  14% | 7 servers
min 18 | CPU  14% | 7 servers

On Kubernetes, the Horizontal Pod Autoscaler applies the same idea to your Java pods; on AWS, an Auto Scaling group does it for EC2 instances. Remember that new JVMs need a little time to start and warm up, which is one more reason to scale out a bit early.

13. Verifying the Change

After every change, load-test again with traffic that looks like results day and compare:

MeasurementBeforeAfterWhat it tells us
Requests completed per second1,20010,000Did capacity really grow?
Median (p50) response time60 ms45 msWhat a typical student sees
p99 response time2,400 ms180 msWhat the slowest 1% of students see
Failed requests3%0.05%Is the system dropping work?

Look at percentiles, not just the average. An average of 70 ms can hide thousands of students waiting two seconds. And check correctness and cost too: a faster system that shows the wrong marks, or costs more than the business can afford, has not improved.

Summary

We scaled the exam platform one bottleneck at a time:

StepChangeBottleneck it removed
1Bigger machineCPU or memory on one server
2Separate database serverApp and database fighting over one machine
3Stateless app servers behind a load balancerOne app server at its limit
4Cache-aside with RedisThe same scorecards read again and again
5Read replicasToo many reads for one database
6ShardingToo much data or too many writes for one primary
7Queues and workersSlow work inside the student's request
8AutoscalingFixed capacity for traffic that rises and falls
  • Scalability means handling more load by adding resources; always be specific about what is growing.

  • Measure first and fix the real bottleneck; the cheapest fix is often an index or a cache.

  • Vertical scaling is simple but has a ceiling; horizontal scaling grows further but needs stateless app servers.

  • Caches and read replicas take read load off the database; sharding spreads data and writes.

  • Queues and autoscaling keep response times steady when traffic jumps, and every change should be verified with a load test.