Scaling a web application: vertical, horizontal and when to bother

How to handle more traffic without guesswork: bigger servers, more servers, caching, database tuning, queues and load testing.

A row of small cream boxes ending in one tall terracotta box

"Will it scale?" is a question that worries many developers long before it needs to. Most applications never need an elaborate architecture, and the ones that do usually get there through a series of small, measured steps rather than one big redesign.

This guide is for developers and technical founders whose app is getting slower as traffic grows, or who want to be ready before it does. You will learn the two basic ways to add capacity, what has to be true of your app before you can run more than one copy, which caching and database techniques buy the most headroom, how to load test, and when scaling is the wrong answer.

Examples use Node.js and PostgreSQL, but the ideas apply to any stack.

Vertical vs horizontal scaling

There are two ways to give an application more capacity.

Vertical scaling (scaling up) means a bigger server: more CPU, more memory, faster disk. It needs no code changes and is usually the first thing to try. Its limits are that there is always a largest size, resizing may need a restart, and one server remains a single point of failure.

Horizontal scaling (scaling out) means more servers or containers running copies of your app behind a load balancer. It removes the ceiling and improves resilience, but your app must be designed for it, and you take on more moving parts.

Vertical vs horizontal scaling
Vertical scaling adds power to one server; horizontal scaling adds more servers behind a load balancer

A sensible order for most teams: optimise, then scale vertically, then scale horizontally when you need resilience or have outgrown the largest practical server.

Stateless apps: the prerequisite for scaling out

If you run three copies of your app, any request may land on any copy. That only works if no copy keeps important state to itself. A stateless app stores nothing locally that another copy would need.

Common sources of hidden state:

  • Sessions held in memory. A user logs in on copy A, the next request hits copy B, and they appear logged out.
  • Uploaded files on local disk. A file uploaded to copy A is missing on copy B. Store uploads in object storage instead.
  • In-process caches that must be consistent between copies.
  • Scheduled jobs that run on every copy, so the job runs three times.

Sessions

Move sessions into a shared store such as Redis or your database, or use signed, self-contained tokens. "Sticky sessions" at the load balancer, which send each user to the same copy, are a workaround rather than a fix: when that copy restarts, its users lose their sessions.

Caching layers

Caching is the cheapest capacity you can add. Each layer stops work from reaching the layer below.

HTTP caching and CDNs

Static assets with hashed filenames (for example app.3f9a1c.js) never change, so browsers and CDNs can keep them for a long time. A typical nginx rule:

nginx
location /assets/ {
    add_header Cache-Control "public, max-age=31536000, immutable";
    try_files $uri =404;
}

A CDN in front of your origin serves these files from locations near your visitors and absorbs much of the traffic. See Cloudflare explained for how that works.

Application caching with Redis

For data that is expensive to compute but changes rarely, cache the result in Redis with an expiry time. This "cache-aside" pattern uses the redis package for Node.js; db.findProduct stands for your own database query:

JavaScript
import { createClient } from 'redis';

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

export async function getProduct(id) {
  const key = `product:${id}`;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const product = await db.findProduct(id);
  await redis.set(key, JSON.stringify(product), { EX: 300 });
  return product;
}

When the product changes, delete its key so the next request loads fresh data.

Database scaling

The database is where most scaling problems actually live. Work through these in order.

Indexes first

A missing index can make a query thousands of times slower than it needs to be, and no amount of hardware fixes that efficiently. Find slow queries (the pg_stat_statements extension is useful in PostgreSQL), then inspect them:

SQL
EXPLAIN ANALYZE
SELECT id, total FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20;

-- If the plan shows a sequential scan on a large table, add an index
CREATE INDEX CONCURRENTLY idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

CONCURRENTLY builds the index without blocking writes, which matters on a live table.

Connection pooling with PgBouncer

Each PostgreSQL connection is a separate server process with its own memory. When you run many app copies, each with its own pool, the total can exceed what the database handles well. PgBouncer sits in between and shares a small number of real connections among many clients:

Config
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb

[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 500
default_pool_size = 20

Transaction pooling is the most efficient mode, but session-level features such as SET commands, advisory locks and LISTEN do not behave as they would on a direct connection. Check your framework's guidance for running behind PgBouncer.

Read replicas

A read replica is a copy of the database that receives changes from the primary and serves read-only queries. It helps when reads far outnumber writes. Replicas lag slightly behind the primary, so read your own writes from the primary where it matters, for example straight after a user saves a form.

Queues and background jobs

Anything slow that the user does not need to wait for should leave the request: sending emails, resizing images, generating reports, calling slow third-party APIs. Put a job on a queue, respond immediately, and let a worker process handle it.

Popular choices include BullMQ for Node.js, Celery or RQ for Python, and Laravel's built-in queues for PHP. Most use Redis or a database as the queue. Queues also smooth out spikes: a burst of work waits in line instead of overwhelming the web process.

Load testing with k6

Load testing shows where your app breaks before your users find out. k6 is an open-source load testing tool that uses JavaScript scripts. This one ramps up to 20 virtual users, holds, then ramps down, and fails if more than 1% of requests error or the 95th percentile response time exceeds 500 ms:

JavaScript
import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
  stages: [
    { duration: '1m', target: 20 },
    { duration: '3m', target: 20 },
    { duration: '1m', target: 0 },
  ],
  thresholds: {
    http_req_failed: ['rate<0.01'],
    http_req_duration: ['p(95)<500'],
  },
};

export default function () {
  const res = http.get('https://staging.example.com/');
  check(res, { 'status is 200': (r) => r.status === 200 });
  sleep(1);
}
Terminal
k6 run load-test.js

Point it at a staging copy, never at production without warning, and watch CPU, memory and database metrics on the server while it runs.

When not to scale

Scaling multiplies cost and complexity. Before you add capacity, check whether the problem is something cheaper to fix:

  • A handful of slow queries that need indexes.
  • N+1 query patterns, where a page runs one query per item in a list.
  • Large, uncompressed images and scripts.
  • Work done during the request that belongs in a background job.
  • A memory leak that makes the app slower the longer it runs.

If the app is fast with one user and slow with fifty, scaling may help. If it is slow with one user, scaling will not.

Step by step: a scaling plan

  1. Measure. Find out which resource runs out first: CPU, memory, disk or database connections. Our resource sizing guide covers the commands.
  2. Optimise the biggest bottleneck, usually slow queries or missing caching.
  3. Load test to confirm the improvement and find the next limit.
  4. Scale vertically if a bigger server solves the problem at acceptable cost.
  5. Make the app stateless: shared sessions, object storage for uploads, one scheduler.
  6. Scale horizontally behind a load balancer, with connection pooling in front of the database.
  7. Add monitoring and alerts so you know about the next limit before your users do.

On Launchpad, each app runs as a single container with CPU and memory limits; it does not offer autoscaling or multiple load-balanced instances. Moving to the Pro plan gives more power per app. If you need multiple instances or autoscaling, talk to us about Cloud Hosting.

Common mistakes

  • Scaling before measuring. Fix: identify the bottleneck with metrics or a load test first.
  • Adding app servers when the database is the bottleneck. Fix: more copies mean more database load; fix queries and pool connections first.
  • Keeping sessions in memory, then scaling out. Fix: move sessions to Redis or the database before adding copies.
  • Caching without an invalidation plan. Fix: set sensible expiry times and delete keys when data changes.
  • Load testing production unannounced. Fix: use staging, or schedule and monitor a production test carefully.

Security considerations

  • Keep Redis, PgBouncer and database ports on private networks only. Never expose them to the internet without authentication and TLS.
  • Never cache personalised responses in a shared CDN cache. Mark them Cache-Control: private or no-store.
  • Rate-limit login and expensive endpoints so attackers cannot trigger the costly code paths you just scaled.
  • Load testing can look like a denial-of-service attack. Only test systems you own, and tell your provider if their terms ask you to.

Troubleshooting

SymptomLikely causeFix
Users randomly logged out after scaling outSessions stored in each copy's memoryStore sessions in Redis or the database
too many clients already from PostgreSQLEach app copy opens its own poolAdd PgBouncer or reduce pool size per copy
Stale data shown after an updateCache not invalidatedDelete the cache key on write, or shorten its expiry
Response times rise steadily under constant loadQueue backlog or memory leakCheck queue length and memory over time

Frequently asked questions

Should I design for horizontal scaling from day one?

Make the app stateless from the start, because that is cheap and good practice anyway. Do not build multi-server infrastructure until measurements show you need it.

Is Kubernetes required to scale?

No. A load balancer in front of a few servers or containers handles a great deal of traffic. Kubernetes helps when you run many services and want automated scheduling, but it adds operational work.

How many users can one server handle?

There is no universal number. It depends on what each request does. Load test your own app to find out.

Do read replicas make writes faster?

No. They take read traffic off the primary, which can free capacity for writes, but every write still goes to the primary.

Next steps

Scale in measured steps: optimise first, scale up next, and scale out when you need resilience or more headroom than one server can give. Caching, indexes and connection pooling often postpone the need for more servers by a long way.

Share this articleLinkedIn (opens in a new tab)X (opens in a new tab)Facebook (opens in a new tab)
Was this article helpful?

Get new guides in your inbox.

One email a month. Unsubscribe anytime.