Vertical vs horizontal scaling & statelessness
Make a service horizontally scalable by moving state out of it.
By Invicly Tech, , in System Design Deep Dive. About 10 minutes to read.
In short
Vertical scaling buys a bigger machine; horizontal scaling adds more machines behind a load balancer. Horizontal scaling only works when servers are stateless, so session and user state must live in shared stores.
Think of it like this: Vertical is hiring a faster cashier; horizontal is opening more checkout lanes.
Explained simply
When an app gets more users, one server eventually cannot keep up. There are two ways to grow. Vertical scaling means buying a bigger server. Horizontal scaling means adding more servers and splitting the work between them.
Picture a busy kitchen. You can buy a bigger stove, or hire more cooks. More cooks only help if orders are pinned on a shared board, not kept in one cook's head. If a cook goes home, the orders must still be on the board.
In software, "state" is anything a server remembers between requests: who is logged in, what is in a cart, an uploaded file. If that lives in one server's memory and the server dies, it is gone, and other servers cannot see it.
The fix is to move state into shared places like a database, Redis or object storage. Then every server is identical and replaceable. You can add ten more during a sale and remove them afterwards without anyone noticing.
Press Play on a diagram to walk through it one step at a time.
- Bigger CPU, RAM, disk
- No code changes
- Hard hardware ceiling
- Single point of failure
- Add more servers
- Near-linear capacity growth
- Needs stateless services
- Survives individual server failures
- 1Load balancer
Sends any request to any healthy server
- 2Stateless app servers
Identical, disposable, auto-scaled by load
- 3Shared session store
Redis holds sessions and short-lived state
- 4Database and object storage
Durable source of truth for data
- 1Find the state
Sessions, files, jobs, counters
- 2Sessions to Redis
Or short-lived signed tokens
- 3Files to object storage
S3 or similar, served by a CDN
- 4Jobs to one scheduler
Or a queue with workers
- 5Add a load balancer
Run 2+ copies in different zones
- 6Turn on auto scaling
Target ~60% CPU
- 1Measure
CPU or requests per instance
- 2Compare to target
For example 60% CPU
- 3Adjust
Add or remove instances
- 4Wait
Warm-up and cooldown before acting again
- Back to step 1
In depth
A checklist of hidden state
Sessions are the famous example, but servers hide state in other places too. Before you put a service behind a load balancer and scale it out, go through this list. Each item either breaks when a second server appears or disappears when a server is replaced.
- Sessions in memory: move to Redis or signed tokens
- Files on local disk: move to object storage like S3
- Scheduled jobs on every server: they run N times; use one scheduler
- Local rate-limit counters: each server counts only its own share
- In-process caches: fine, as long as losing them is harmless
Sessions: Redis or signed tokens?
With server-side sessions, the browser holds only a random session ID, and every server looks up the details in Redis, which takes about a millisecond. Logging someone out is easy: delete the key.
With signed tokens such as JWTs, the user's ID and roles live inside the token, signed by the server. Any server can check the signature without a lookup. The downside is that you cannot easily cancel a token before it expires. The common compromise is a short-lived access token, 5 to 15 minutes, plus a longer refresh token that is checked against a store and can be revoked.
- Browser holds a random session ID
- About 1 ms lookup per request
- Logout: delete the key
- User ID and roles inside the token
- Any server checks the signature
- Hard to cancel before expiry
- Usual fix: 5-15 min token + refresh
How auto scaling actually works
Auto scaling watches a metric, such as average CPU or requests per instance, and compares it with a target, for example 60 percent CPU. Above target, it adds instances; below, it removes them. AWS Auto Scaling groups and the Kubernetes Horizontal Pod Autoscaler both work this way.
New instances are not instant. Booting, pulling the image and warming caches can take one to five minutes. So scale out early and quickly, scale in slowly with a cooldown, keep a sensible minimum, and use scheduled scaling for predictable peaks such as 9 a.m. on Mondays.
The database is the last stateful piece
Once app servers are stateless, the database becomes the bottleneck. Scale it in order of effort. First, go bigger: a large PostgreSQL machine handles a lot. Second, add a cache so repeated reads never reach it. Third, add read replicas for read-heavy traffic. Last, split the data across machines (sharding), which is powerful but complex.
Watch connections too. Every app server holds a pool of connections, so 50 servers with 20 connections each is 1,000. PostgreSQL often struggles above a few hundred, so put a pooler such as PgBouncer in between.
- 1Bigger machine
Vertical scaling goes far
- 2Add a cache
Repeated reads never reach it
- 3Read replicas
For read-heavy traffic
- 4Sharding
Powerful but complex
- 5Pool connections
PgBouncer in front of PostgreSQL
When vertical scaling is the right answer
Horizontal scaling is not always better. A single big machine has no network calls between parts, no partial failures and much simpler code. Cloud servers with over a hundred CPU cores and terabytes of memory are available today. Stack Overflow famously served huge traffic from a small number of powerful database servers.
Vertical scaling is a great first move for databases and young products. Its limits are a hard ceiling on size, rising prices at the top end, and a single point of failure, so you still want a standby copy ready to take over.
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Compare vertical and horizontal scaling~40m
- 2Move session state out of servers~40m
- 3Design a stateless service tier~40m
Key points
- Start vertical for simplicity, go horizontal when you hit limits or need redundancy.
- A stateless server can be killed or added at any time without losing data.
- Move sessions to Redis or signed tokens instead of server memory.
- Sticky sessions are a workaround that hurts balancing and failover.
Key terms
Tap a card to flip it. 0/5 known
Examples
Moving a shopping cart out of server memory
Before: each server kept carts in a Python dictionary, so a user whose next request hit another server saw an empty cart, and a restart emptied everyone's cart. After: the cart lives in a Redis hash keyed by session ID. Any server can add items with HINCRBY, and EXPIRE forgets carts left idle for a week. The servers now keep nothing between requests.
import redis
r = redis.Redis(host="sessions.internal", port=6379)
def add_to_cart(session_id: str, product_id: str, qty: int) -> None:
key = f"cart:{session_id}"
r.hincrby(key, product_id, qty) # any server can update it
r.expire(key, 7 * 24 * 3600) # drop idle carts after 7 days
def get_cart(session_id: str) -> dict:
raw = r.hgetall(f"cart:{session_id}")
return {k.decode(): int(v) for k, v in raw.items()}Growing from 1,000 to 10 million users
Stage 1: one server runs the app and the database. Stage 2: the database moves to its own machine so each can be sized separately. Stage 3: sessions move to Redis and uploads to S3, then two app servers sit behind a load balancer in different zones, so one can fail safely. Stage 4: a cache and a read replica absorb read traffic, and a CDN serves images and scripts. Stage 5: auto scaling adds app servers at peak. Only when writes outgrow the biggest database machine does sharding enter the picture.
Quick reference
- Stateless = any server can serve any request, and any server can die safely
- Sessions → Redis or tokens; files → object storage; jobs → one scheduler or a queue
- Run at least 2 instances in different zones, even with little traffic
- Auto scale on CPU (~60%) or requests per instance; out fast, in slowly
- DB connections = app servers × pool size; use PgBouncer when it gets large
- Database order: bigger machine → cache → read replicas → sharding
- JWT: no lookup, hard to revoke; keep access tokens to 5–15 minutes
Common mistakes
- Storing uploaded files on local server disks.
- Keeping in-memory sessions, so users log out when a server dies.
- Forgetting the database also needs a scaling plan.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
An app keeps sessions in memory, saves profile pictures to local disk and sends a daily digest via cron on each server. List each piece of state and where it should move.
- Exercise 2medium
40 app servers each have a database pool of 20 connections, and PostgreSQL's max_connections is 500. You plan to scale to 60 servers. What goes wrong and how do you fix it?
- Exercise 3hard
Traffic jumps 5× at 9:00 every weekday, and new instances need 4 minutes to be ready. Design an auto scaling policy that avoids slowdowns at 9:00 and wasted money at night.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does stateless mean the app has no database?
- No. The app servers keep nothing between requests, but the data still lives in databases and caches. Statelessness moves state out of servers, it does not remove it.
- Are sticky sessions always bad?
- They are a workaround that hurts balancing and loses users' sessions when a server dies. They are acceptable for long-lived connections like WebSockets, where a client naturally stays on one server.
- When should I switch from vertical to horizontal scaling?
- When you need redundancy, when the next bigger machine is too expensive, or when you hit the largest size available. For stateless app servers, start horizontal early since it is cheap.