Skip to content

No. 03DevOps8 min read2,093 words

How to scale a web app: for traffic spikes, step by step

How to keep a web app up when traffic spikes: what breaks first, the cheap fixes that buy the most headroom, when to add servers, and how to load test first.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways · 05

The short version

  1. 01Under a traffic spike the database usually fails first, because app servers can be copied cheaply and the primary database cannot. Protect it before you add anything else.
  2. 02Work in order: load test to find the bottleneck, cache at the CDN, fix slow queries and add indexes, pool database connections, move slow work to queues, then scale horizontally.
  3. 03Postgres defaults to roughly 100 connections, so a few dozen autoscaled app instances can exhaust it on their own. A connection pooler like PgBouncer is often the difference between bending and breaking.
  4. 04Horizontal scaling only works if the app is stateless: sessions, uploads, caches and background jobs must live outside any single server's memory or disk.
  5. 05Plan for graceful degradation: decide in advance which features can be switched off, served stale or queued when load exceeds capacity.
On this page · 11

To keep a web app up during a traffic spike, find what breaks first with a load test, then fix things in order: cache public pages at the CDN, fix slow queries and indexes, put a connection pooler in front of the database, move slow work to background queues, and only then add servers with autoscaling. In most apps the database breaks first, not the web servers, and most spike problems are solved with caching and tuning rather than a rewrite.

Your app runs fine for months, then a TV segment, a newsletter feature or a launch sends thousands of people at it in an hour and it falls over. The good news: spikes are one of the most solvable problems in web development. The bad news: the fix depends entirely on what breaks first, and most teams guess wrong. This is the playbook we use in our cloud and DevOps work.

What breaks first when traffic spikes

When traffic jumps, failures tend to arrive in a predictable order.

LayerHow it failsTypical symptom
DatabaseRuns out of connections, CPU or I/O"Too many connections", timeouts, every page slow at once
App serversMemory or CPU exhausted, event loop blockedRising latency, crashes and restarts
Third-party APIsRate limits or slow responsesSpecific features fail (payments, email, search) while the rest works
Background work done inlineRequests wait on emails, webhooks, image processingSignup or checkout slows to a crawl
BandwidthRarely the bottleneck behind a CDNLarge assets slow to download

The reason the database usually goes first is simple. Your web server can run more copies of itself cheaply. Your database is typically one primary machine holding the truth, and every request that reads or writes goes through it. Under a spike, that single machine gets a flood of requests asking for the same homepage data and gives out.

Step 1: load test before you spend anything

Before you buy capacity, get one number: at what load does the app bend, and which layer gives out? A load testing tool such as k6 or Artillery, pointed at a production-like environment, will tell you whether you fall over at hundreds of concurrent users or tens of thousands. Without that number, scaling work is expensive guessing.

A useful load test:

  1. Scripts your real critical paths, not just the homepage: browse, search, sign up, check out.
  2. Ramps up gradually so you can see where latency starts to bend, not just where it breaks.
  3. Runs against production-like data volumes. A query that is fast on a thousand rows can crawl on ten million.
  4. Watches the server side: database CPU, connection count, slow queries and error rates, not only the response times the tool reports.

You need observability in place to read the results. Our observability basics for web apps covers the latency, traffic, error and saturation signals that tell you which layer is struggling.

Step 2: cache everything that can be cached

If the same page or API response is computed over and over for different users, you are doing pointless work. A cache stores the result so the next thousand requests get it for free. There are three layers, cheapest first.

CDN caching for public pages

Anything public and mostly static (marketing pages, product listings, blog posts, images) should be served by a CDN from locations near the user, without touching your app. On a content-heavy site, this alone can absorb most of a spike, and it is usually the cheapest capacity you will ever buy. Where pages are rendered matters here too; our guide to edge vs server rendering covers when moving work to the edge helps and when it just moves the bottleneck.

The control is the Cache-Control header. s-maxage tells shared caches like a CDN how long to keep a response, and stale-while-revalidate, defined in RFC 5861, lets the CDN keep serving the cached copy while it fetches a fresh one in the background:

Cache-Control: public, s-maxage=60, stale-while-revalidate=600

That header means: any CDN may serve this for 60 seconds, then for up to ten more minutes it may serve the stale copy while refreshing it. Under a spike, your origin sees roughly one request per minute per page from each CDN location, instead of thousands. In Next.js, static and revalidated pages get sensible headers automatically.

Application caching with Redis

For data that is expensive to compute but does not change every second ("top 50 products", a dashboard summary), compute it once and store it in Redis for 30 seconds or five minutes. Every user in that window gets the cached copy.

Watch for the stampede: when a popular key expires, hundreds of requests can try to recompute it at the same moment. Use a short lock so only one request recomputes, or refresh hot keys before they expire.

The staleness decision

The honest trade-off with caching is staleness. A cached price might be a minute old. For most content that is fine. For a checkout total or a stock count, it is not. Deciding which data can be stale, and for how long, is a business call, not a technical one, which is why the person who owns the product should make it.

Step 3: fix the database before you scale it

Half of "we need a bigger database" problems are really slow queries. A query that scans a whole table to find one row is fine with a hundred rows and crawls with a million. Use EXPLAIN ANALYZE on the slowest queries and add the right index. Our guide to database indexing for app developers walks through it. It costs nothing but engineering time, and it often turns seconds into milliseconds.

Pool your database connections

Next comes connection pooling. Postgres sets a hard limit on concurrent connections, and the default max_connections is typically 100. Each connection also consumes memory on the database server, so raising the limit is not free.

Now do the arithmetic for a spike. If each app instance opens a pool of 10 connections and autoscaling takes you from 4 instances to 20, you need 200 connections from a database that allows 100. New requests start failing exactly when traffic is highest. Serverless functions make this worse, because every concurrent invocation may open its own connections.

A pooler such as PgBouncer, or your provider's managed equivalent, sits in front of Postgres and shares a small set of real connections across many clients. In transaction mode, a connection is only held for the length of a transaction. This is frequently the difference between surviving a spike and watching the database refuse every new request.

Take read pressure off the primary

If reads dominate and some can be slightly stale, add a read replica and send reporting, search and listing queries to it. Keep writes, and reads that must see the latest write, on the primary. Moving to a larger database instance (vertical scaling) is also legitimate here: it is often the fastest fix for a database that is genuinely at capacity, as long as you have done the tuning first.

Step 4: move slow work out of the request

A flood of signups also means a flood of welcome emails, webhooks, image resizing and analytics calls. If those run inline with the request, every request waits for them, and a slow email provider becomes your outage.

Move anything the user does not need to see the result of right away into a background job queue. The request writes a job and returns. Workers process the queue at whatever rate the downstream services allow. Under a spike, the queue grows and drains later instead of taking the site down.

Know your third parties' limits, too. Payment, email and AI APIs all enforce rate limits, and you can hit them under load even when your own servers are fine. Queue and retry with backoff rather than hammering them.

Step 5: add servers with horizontal scaling

Once caching and database tuning are done, the remaining move is more capacity.

Horizontal scaling means running more identical copies of your app behind a load balancer. If the app is stateless, you can go from two copies to twenty in minutes, and most managed platforms will do it automatically. This is the default answer for spiky traffic.

Vertical scaling means a bigger single machine. It is often right for the database, which is hard to split, but it has a ceiling and keeps a single point of failure.

The hidden state that breaks horizontal scaling

Horizontal scaling only works if any request can go to any instance. The twelve-factor guidance on processes states the rule: processes are stateless and share nothing, and anything that must persist lives in a backing service. What quietly breaks this:

  • Sessions stored in server memory. Move them to signed cookies, the database or Redis.
  • Uploaded files saved to local disk. Move them to object storage like S3.
  • In-process caches and job queues. Move them to Redis or a proper queue.
  • Scheduled jobs that run on every instance. Run them once, from a scheduler or a single worker.

Self-hosted Next.js has a few framework-specific items, which the Next.js self-hosting guide documents. Every instance must share the same NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, or Server Actions fail when a request lands on a different instance. The default in-memory cache is not shared across instances, so consistent caching needs a shared cache handler. And a deploymentId protects users from version skew during rolling deploys. If you run in containers, our guide to Docker for web apps covers building a stateless image.

Step 6: plan for graceful degradation

Even a well-tuned app has a limit. Decide in advance what happens when you exceed it, instead of discovering it live.

  • Switch off expensive extras. Recommendations, live search suggestions or AI features can be turned off with a flag to protect checkout. Our post on feature flags without a platform shows a simple kill-switch setup.
  • Serve stale rather than nothing. A product page from five minutes ago beats an error page.
  • Rate limit abusive or automated traffic so it cannot crowd out real users.
  • Use a waiting room for extreme, predictable peaks such as ticket drops, so people queue politely instead of hammering a failing site.

Effort and trade-offs at a glance

Rough effort, because the real number depends on your stack and how the app was built:

FixTypical effortRunning costMain trade-off
CDN caching for public pagesDaysLowContent can be briefly stale
Indexes and query fixesDaysNoneNeeds profiling under realistic data
Connection poolingDaysLowSome session-level database features behave differently
Redis application cacheOne to two weeksLow to moderateInvalidation logic to maintain
Background queues for slow workOne to two weeksLowEventual consistency for side effects
Making the app statelessA week to a couple of monthsNoneDepends on how much hidden state exists
AutoscalingUsually configurationPay for extra capacity only while neededNeeds the stateless work done first

A realistic first pass for a typical app (load test, caching, indexes, pooling, queues, autoscaling) is a few weeks of focused work. The bigger numbers only appear when the app needs structural changes to become stateless.

Common mistakes

  • Scaling blind. Paying for a database several sizes too big to cover a missing index is the most common money pit we see.
  • Testing only the homepage. The homepage is usually cached. Checkout and signup are where spikes hurt.
  • Autoscaling the app into the database. More app instances mean more database connections. Pool first.
  • Forgetting the week before. A load test the week before a known launch is cheap insurance. The night before is too late.
  • Buying a rewrite. Most spike problems are configuration and caching, not architecture. A rewrite is occasionally right, but it should be the last resort, not the first quote.

Ready for the next spike

Find what breaks first with a load test, cache aggressively, fix your queries and pool your connections, move slow work to queues, then add machines with autoscaling. In that order. Most teams can survive their next big spike with a few weeks of focused work, not a rebuild, as long as they tune before they buy.

If you have a launch on the calendar and a nagging worry about whether the app will hold, take it seriously a few weeks early rather than the night before. Tell us what is coming and we will help you find the bottleneck and fix it.

FAQ · 05 questions

Frequently asked questions

What usually breaks first when a website gets a traffic spike?

Most often the database: it runs out of connections, CPU or I/O because every request hits it. After that come application server memory and CPU, then third-party APIs that rate-limit you. Bandwidth is rarely the problem for a modern site behind a CDN.

How do I know how much traffic my web app can handle?

Run a load test against a production-like environment with a tool such as k6 or Artillery, ramping up virtual users along your real critical paths, like browsing, signing up and checking out. Watch latency, error rate and database load as you ramp, and note where they bend. Never assume capacity from averages in normal traffic.

Is a CDN enough to handle a traffic spike?

For content-heavy, mostly public pages it can absorb most of a spike, because cached responses never reach your servers. It does not help with logged-in, personalised or write-heavy traffic such as checkout or signup, which still hits your app and database and needs its own capacity planning.

Should I scale vertically or horizontally?

Scale application servers horizontally by running more identical, stateless copies behind a load balancer. Databases are usually scaled vertically first, by moving to a larger instance, because splitting a database is much harder. Use read replicas when reads dominate and the application can tolerate slightly stale reads.

Do I need Kubernetes to handle traffic spikes?

Rarely. Managed platforms and container services can autoscale stateless apps without you operating a cluster. Kubernetes makes sense when you already run many services and have people to operate it, not as a first response to a spike.

Related service

Cloud & DevOps

Reliable deploys and infrastructure that gets out of the way.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1–2 weeks
Pricing
Fixed price per phase
You own
All code and accounts