How to Prepare Your Application for Traffic Spikes
A launch, a sale, a newsletter or a front-page mention can bring ten times your normal traffic in minutes. How to estimate the spike, load test for it, scale before it arrives, cache, protect the database, fail fast, and what to check on the day.

On this page
Key takeaways
- An app fails under a spike in a chain: queued requests hold connections, the pool runs dry, timeouts trigger retries and health checks restart replicas. Stop the chain early.
- Estimate the spike from the event, prepare for two to three times that, and load test real user journeys on production-sized data to find the first bottleneck.
- Autoscaling takes one to three minutes to add capacity: scale at 60 to 70% CPU, set a minimum that absorbs the first jump, and raise it before spikes you can see coming.
- Cache static files, public pages and expensive results, and guard hot keys against cache stampedes with a rebuild lock and random expiry.
- Protect the database: fit connection pools to the maximum replica count, fix slow queries, set statement timeouts and resize days before the event.
- On Cloider, App Engine autoscales an app from 1 to 100 replicas billed by the second, and Kubernetes clusters scale pods with the HorizontalPodAutoscaler and no nodes to manage.
Your app runs fine for months. Then a post about it reaches the front page of Hacker News, a newsletter with 300,000 readers mentions it, a push notification goes out to every user, or a Black Friday sale opens at 9 a.m. Within minutes traffic is ten or fifty times what it normally is. Pages slow down, then time out, then return errors, and by the time someone has opened a dashboard to look, most of the visitors you were waiting for have left.
A traffic spike isn't the same as growth. Growth gives you weeks to notice and add capacity. A spike gives you minutes, sometimes seconds, and it tends to arrive at the moment that matters most: a launch, a sale, a mention you can't repeat.
The good news is that surviving one is mostly preparation. This article goes through it in order: why apps fail under sudden load, how to estimate a spike and load test for it, what to change in the app, the cache and the database, how to fail gracefully when capacity runs out anyway, and a checklist for the day itself. The ideas work on any platform. The last sections show how they map to Cloider App Engine and Cloider Kubernetes.
How apps fail under a spike
An app rarely fails under a spike because one thing broke. It fails in a chain, usually like this:
Requests arrive faster than the app finishes them, so they start to queue.
Each waiting request holds a worker, memory and often a database connection for longer.
The database connection pool runs dry, so even fast requests now wait for a connection.
Requests reach their timeouts, and clients, load balancers and your own code retry them, adding load at the worst moment.
Health checks that query the database time out, replicas are marked unhealthy and restarted, and the replicas left take even more traffic.
Each step makes the next one worse, which is why an app can go from a little slow to completely down in a minute. Two lessons follow. First, your capacity is set by the narrowest shared component: usually the database, sometimes a third-party API or memory, and rarely the app's own CPU. Second, the defenses that matter most are the ones that stop the chain early: spare capacity, caches that keep work away from the database, and timeouts that fail requests fast instead of letting them pile up.
Estimate the spike before it arrives
You can't prepare for a number you don't know, so start by writing two of them down: what you handle on a normal busy day, and what the spike may bring.
For the first, read your metrics for the busiest hour of a normal week: requests per second, 95th percentile latency, error rate, CPU and memory per replica, the number of replicas, database CPU and open database connections.
For the second, work it out from the event. Say you send a push notification to 500,000 users of your mobile app. If 3% open the app within the first minute, that's 15,000 users in 60 seconds. If opening the app makes 8 API calls, that's 120,000 requests in a minute, or 2,000 requests per second, against a normal peak of perhaps 100. Newsletters, launches and sales can be estimated the same way: the size of the audience, the share that acts, how quickly they act, and how many requests each of them makes.
Then add a margin. The estimate is a guess, a link that gets shared further brings people you didn't count, and bots and retries ride along with every spike. Prepare for two to three times what you expect.
Load test to find your limit
A load test shows you where the chain starts, at a load you choose, instead of on launch day. A few rules make its results worth having:
Test what users do, not just the homepage. The homepage is often cached. Signing up, searching, adding to a cart and checking out are where the database works hardest, so script those journeys.
Test with production-sized data. A query that is instant on an empty table can take seconds on ten million rows. Load test a staging copy with realistic data.
Ramp up in steps and note the first thing that breaks. Latency climbing, errors starting, the connection pool filling up or memory running out: whatever goes first is what you fix first. Then test again, because the next bottleneck is right behind it.
Test the shape of a spike, not only a ramp. Jumping from normal traffic to ten times as much in one minute shows how your autoscaling reacts, which a slow ramp never does.
Leave third parties out. Point payment providers, email services and other external APIs at their sandboxes or at mocks, both to stay within their rate limits and to avoid sending ten thousand test emails.
k6 is a good open source tool for this, with tests written in JavaScript. This test holds 50 virtual users for two minutes, jumps to 500 within one minute and holds them there, and fails if more than 1% of requests fail or the 95th percentile goes above 800 ms:
import http from "k6/http";
import { check, sleep } from "k6";
export const options = {
stages: [
{ duration: "2m", target: 50 }, // a normal busy hour
{ duration: "1m", target: 500 }, // the spike
{ duration: "5m", target: 500 },
{ duration: "2m", target: 0 },
],
thresholds: {
http_req_failed: ["rate<0.01"],
http_req_duration: ["p(95)<800"],
},
};
export default function () {
const res = http.get(`${__ENV.BASE_URL}/products?category=new`);
check(res, { "status is 200": (r) => r.status === 200 });
sleep(1);
}Run it against your staging app:
k6 run -e BASE_URL=https://staging.example.com spike.jsLocust, Gatling and JMeter do the same job, and oha or hey are quick ways to load a single URL. Whatever you use, watch the app's own metrics while the test runs, since the tool only sees the app from the outside.
Make the app ready to scale out
The fastest way to add capacity during a spike is to run more copies of the app, so the app has to be able to run as several copies. Nothing a later request depends on may live inside one replica: sessions belong in Redis or the database, uploads in object storage, locks and counters in a shared store, and scheduled tasks must run once rather than once per replica. Understanding Horizontal vs. Vertical Scaling goes through that list in detail, and Why your application should never store files locally covers files.
For spikes, two more things matter:
Start fast. A replica that needs two minutes to boot can't help with a spike that peaks in three. Keep images small, do as little as possible before the app starts listening, and don't run database migrations on startup: with twenty replicas starting at once, twenty migrations race each other. Run them once, as a release step.
Size replicas from measurements. A replica that already runs near its CPU limit at normal traffic is throttled the moment traffic rises. Measure what one replica uses at normal load and at the throughput your load test reached, and give it room above that.
Scale before the spike, then let autoscaling follow
Autoscaling is the safety net for traffic you didn't predict, but it is a reaction, and reactions take time. Before a new replica serves its first request, the autoscaler has to see the load in its metrics, the replica has to be scheduled and its image pulled, the app has to start, and it has to pass its health check. All in, that's often one to three minutes. A spike that doubles traffic in thirty seconds outruns it.
Three settings close most of that gap:
Leave headroom. Scale at 60 to 70% CPU, not 90%. The difference is the capacity that carries the spike while the new replicas start.
Set the minimum for the first minutes. The minimum number of replicas should absorb the first jump on its own. For anything users depend on it is at least 2 anyway, so one replica can restart while the other serves.
Set a maximum the rest of the system can take. The maximum caps your bill, but it also caps how many database connections the replicas can open. A maximum the database can't serve only moves the failure.
For spikes you can see coming, such as a launch, a sale, a campaign or a scheduled push notification, don't wait for the autoscaler at all. Raise the minimum an hour before, so the capacity is already running and warm, and lower it again once the traffic has passed. It is the single most effective step in this article, and it costs a few hours of extra replicas.
Cache everything you can
The cheapest request is the one your app never has to compute. During a spike most visitors look at the same few pages, which makes caching unusually effective.
Serve static files from a CDN or a bucket. Images, scripts and stylesheets don't need your app. Give them fingerprinted names, such as
app.3f9c1a.js, and serve them withCache-Control: public, max-age=31536000, immutable, so browsers and CDNs keep them for a year.Cache public pages in front of the app. A landing page, a pricing page or a blog post is the same for every anonymous visitor.
Cache-Control: public, s-maxage=60, stale-while-revalidate=300lets a CDN or caching proxy serve it for a minute, then keep serving the old copy while it fetches a new one. Even ten seconds of caching turns a page requested a thousand times a second into one render every ten seconds.Cache expensive results in Redis. Featured products, a leaderboard, the totals on a dashboard: anything that is expensive to compute and fine to be a few seconds old. A shared cache serves every replica, including the ones the autoscaler just added.
Caching has one trap that only shows up under load: the cache stampede. When a popular key expires, every request that arrives before it is rebuilt finds it missing and runs the expensive query, possibly a thousand copies at once, right when the database is busiest. Two fixes go a long way: let one request rebuild the key while the others wait briefly, and add a few random seconds to expiry times so that keys cached together don't expire together.
import json, random, time
def featured_products():
for _ in range(100):
cached = redis.get("featured-products")
if cached is not None:
return json.loads(cached)
# One request rebuilds the value, the others wait for it
if redis.set("featured-products:lock", "1", nx=True, ex=10):
try:
products = db.fetch_featured_products()
# A random extra few seconds keeps keys from expiring together
redis.set("featured-products", json.dumps(products), ex=60 + random.randint(0, 15))
return products
finally:
redis.delete("featured-products:lock")
time.sleep(0.05)
return db.fetch_featured_products()Protect the database
The database is where most spikes are lost. App replicas can be added in a minute, a database usually can't, so it has to be ready before the spike starts.
Do the connection math. Every replica opens its own pool, so the total is replicas times pool size. Ten replicas with a pool of 10 fit PostgreSQL's default limit of 100 connections. Thirty replicas, at the autoscaler's maximum, don't. Size the pools so the maximum replica count still fits, with room left for migrations, cron jobs and your own access, or put a pooler such as PgBouncer in front of PostgreSQL.
Fix the slow queries first. The load test shows which queries slow down under load. Look for missing indexes, N+1 queries that run one query per row, and queries that fetch far more than they use. A single missing index can cost more capacity than any amount of scaling buys back.
Set statement timeouts. A runaway query should fail after a few seconds rather than hold a connection while requests pile up behind it.
Resize ahead of time, not during. If the load test shows the database running out of CPU or memory, move it to a larger size days before the event. Resizing usually restarts a database, and the middle of a spike is the worst time for that.
Keep reads away from it. Every read served from a cache is a query the database doesn't run. For read-heavy apps, read replicas take more of the load off the primary.
In PostgreSQL, a statement timeout for the app's role is one line, and it applies to every new connection the app opens:
ALTER ROLE app SET statement_timeout = '5s';Take slow work off the request path
Sending an email, generating a PDF, resizing an image or calling a slow third-party API doesn't have to happen while the user waits. Put a job on a queue, answer in 50 ms instead of 2 seconds, and let workers do the rest.
Under a spike, a queue works as a shock absorber. Ten thousand sign-ups in five minutes become ten thousand welcome emails waiting in line, sent by workers at the pace they and your email provider can sustain, instead of ten thousand web requests each waiting on the email provider. Watch the length of the queue during the event, scale the workers on it, and make jobs safe to run twice, because retries will run some of them twice.
Fail fast instead of slowly
Even a well prepared app can reach its limit. Whether a spike becomes a slow afternoon or an outage depends on how the app behaves at that limit.
Put a timeout on every outgoing call. Database queries, Redis, HTTP calls to other services. Many clients wait forever by default: Go's
http.DefaultClienthas no timeout, and Python'srequestshas none unless you pass one. A stuck request keeps everything it holds until the user gives up.Retry carefully. Retry a few times at most, with exponential backoff and random jitter, so retries spread out instead of arriving together. Retry at one layer only: three layers that each try three times turn one failing call into 27.
Shed load before you drown in it. Past its capacity, an app that quickly answers some requests with
503 Service Unavailableand aRetry-Afterheader keeps the rest fast. Queuing everything makes every request slow, and most of them fail anyway.Use circuit breakers for dependencies. When a third-party API starts failing, stop calling it for a while and use a fallback, instead of making every request wait for its timeout.
Degrade on purpose. Decide ahead of time what can be switched off: recommendations, live counters, search suggestions, a personalized feed. Put them behind feature flags so you can turn them off in seconds and keep sign-in and checkout fast.
Rate-limit abuse, not your customers
Spikes attract more than customers. Scrapers, credential-stuffing bots and aggressive crawlers turn up whenever a site is in the news, and they go for the most expensive endpoints. Rate-limit login, sign-up, search, password reset and anything else costly, per IP address and per account or API token, and answer with 429 Too Many Requests and a Retry-After header. Keep the counters in Redis, so the limits hold across every replica, including new ones.
For events where demand will exceed supply by a wide margin, such as ticket sales and limited product drops, consider a waiting room that admits visitors at the rate the app can serve. A fair queue is a better experience than a checkout that fails at random.
Health checks and graceful shutdown
Two settings that look minor decide how a platform treats your app under stress.
A health check should say whether this replica can serve, not whether everything it depends on is healthy. If the health check queries the database and the database slows down, every replica fails its check at the same moment and the platform restarts all of them, turning a slow database into a full outage. Keep the check fast and cheap, and monitor dependencies separately.
A replica should also shut down gracefully. When the spike passes, the autoscaler removes replicas, and a replica that receives SIGTERM should stop taking new requests, finish the ones in flight and then exit. Otherwise every scale-down drops a few requests, and so does every deploy during the event.
Watch it while it happens
You can't react to what you can't see. Before the event, put these on one screen:
Requests per second and the error rate, by status class
95th and 99th percentile latency, not only the average
The number of replicas, and CPU and memory per replica
Database CPU, memory and open connections
The length of each queue, and the cache hit rate if you have it
Alert on what users feel, such as error rate and latency, rather than on every possible cause. Keep the logs of every replica in one searchable place. And decide before you need it who is watching, who can raise the replica limits, who can switch features off and how to roll back a bad deploy.
A checklist for the big day
A week or more before:
Estimate the spike, and plan for two to three times that.
Load test the real user journeys, fix the first bottleneck, and test again.
Check that the app runs as several replicas: sessions, uploads, locks and scheduled tasks outside the replica.
Fix slow queries, size connection pools for the maximum replica count, and resize the database if it needs it.
Add caching, queues, timeouts and rate limits where the load test showed they're needed.
Check the limits of third parties: email sending quotas, payment API rate limits, SMS throughput.
The day before:
Raise the minimum replicas, and the maximum if the database can take it.
Freeze deploys, apart from fixes.
Warm the caches for the pages that will be hit hardest.
Prepare the feature flags you would switch off, and make sure the team knows the plan.
During the spike:
Watch the dashboard, latency and errors first.
If the replicas reach the maximum and the database still has room, raise the maximum.
If latency keeps climbing, switch off the features you prepared.
After it:
Lower the minimum again, so you stop paying for the peak.
Look at where the system bent first, and write it down for next time.
Traffic spikes on Cloider App Engine
Most of this article is about your application, and it holds wherever you run it. The platform decides how quickly capacity arrives, how much of it you have to configure and what you pay for it.
Cloider App Engine runs your code from a Git repository, a folder or a Docker image as a web service, and scales it horizontally. With Horizontal autoscaling you set the CPU and memory of each replica, up to 2 vCPU and 4096 MB, and a minimum and a maximum between 1 and 100 replicas. Cloider adds a replica whenever the replicas average your CPU or memory threshold, and removes one after 5 quieter minutes, never going below the minimum.
For spiky traffic, set a threshold with headroom and a minimum that carries the first minutes:
cloider app update shop --compute autoscaling --cpu 1 --memory 1024 --replicas 3 --max-replicas 30 --cpu-threshold 60 --waitBefore a launch you can see coming, raise only the minimum, and lower it again once the traffic has passed. Every value you don't pass is kept:
cloider app update shop --replicas 12
cloider app update shop --replicas 3A compute change redeploys the running version without a rebuild, and the old replicas keep serving until the new ones are up, so the app stays up while it changes. The rest of what this article recommends is built in:
Health checks: with a path such as
/healthz, a replica that fails 2 checks in a row stops receiving requests while the others serve, one that keeps failing is restarted, and a new version only goes live once its replicas pass. See Health checks.Insights: CPU and memory per replica and the number of ready replicas, minute by minute over up to 12 hours, so you can watch the autoscaler follow the spike, next to requests per day by status class. Logs from every replica are in one place, and searchable.
Billing by the second: replicas are billed for the time they run, so the extra replicas of a spike cost only while they serve.
Services next to the app: uploads and static files go in an S3 compatible bucket, and a static front end can be served straight from a bucket website, so replicas only handle the requests that need code. A managed Redis holds the sessions, cache and rate-limit counters that every replica shares, and managed PostgreSQL, MySQL and MongoDB databases resize to a larger plan ahead of the event.
See Scaling and compute in the docs for every option.
Traffic spikes on Cloider Kubernetes
Cloider Kubernetes is serverless Kubernetes. Every cluster has its own control plane, and your pods run on nodes that Cloider operates and scales. There are no node pools to size, no cluster autoscaler to configure and no idle nodes to pay for: you scale pods, and Cloider runs the capacity under them.
The metrics server runs in every cluster, so the HorizontalPodAutoscaler works out of the box. For spikes, give it headroom, and let it hold on to capacity after a peak, since traffic often arrives in waves:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
namespace: shop
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 3
maxReplicas: 30
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
behavior:
scaleDown:
stabilizationWindowSeconds: 600The HPA's default scale-up already doubles the pods, or adds four if that's more, every 15 seconds. The scaleDown window keeps them for 10 minutes after the load drops instead of the default 5, so a second wave finds them still running. Utilization is measured against each pod's CPU request, so set requests from real usage first, and give the pods a readinessProbe so they only receive traffic once they can serve it.
For a known event, raise the minimum ahead of time and set it back afterwards:
kubectl patch hpa web -n shop -p '{"spec":{"minReplicas":12}}'Each container is billed for the larger of its request and its use, prorated, so the pods a spike adds cost only while they run. HTTP services are published on your domain with a target, with automatic HTTPS.
Preparation beats reaction
Most of what keeps an app up during a spike is decided days before it: knowing your limit from a load test, an app that runs as many replicas, caches that keep work off the database, a database sized and pooled for the peak, and timeouts that fail fast. Pre-scaling then covers the spikes you can predict, and autoscaling covers the ones you can't.
On Cloider the platform half comes down to a few settings: an App Engine app on Horizontal autoscaling with headroom in its threshold, or a Kubernetes cluster with HorizontalPodAutoscalers and no nodes to manage, both billed for what runs, with managed databases and Redis next to them. Read more about Cloider App Engine and Cloider Kubernetes, or create a free account and load test your app with the welcome credit.
Frequently asked questions
What is a traffic spike?
A sudden, short rise in traffic to many times the normal level, caused by a launch, a sale, a newsletter, a push notification or a mention in the news or on social media. Growth gives you weeks to add capacity, a spike gives you minutes.
How do I know how much traffic my app can handle?
Load test it. Script realistic user journeys with a tool such as k6, Locust or Gatling, run them against a staging copy with production-sized data, and raise the load in steps until latency or errors pass your limits. The first component to fail sets your capacity, so fix it and test again.
Is autoscaling enough to handle a traffic spike?
Not on its own. Autoscaling reacts to load, and a new replica often takes one to three minutes before it serves. Leave headroom by scaling at 60 to 70% CPU, keep a minimum that absorbs the first jump, and raise the minimum ahead of spikes you can predict, such as launches and sales.
Why does the database fail first during a traffic spike?
App replicas can be added in a minute, a database usually can't, and every replica opens its own connections. Size connection pools for the maximum replica count or use a pooler such as PgBouncer, fix slow queries, cache hot reads in Redis and resize the database before the event.
What is a cache stampede?
When a popular cache key expires under heavy load, every request that arrives before it is rebuilt runs the same expensive query at once. Prevent it by letting one request rebuild the key while the others wait, serving the stale value while it refreshes, and adding random jitter to expiry times.
Should an app return errors when it is overloaded?
Yes, quickly. Answering some requests with 503 and a Retry-After header, or 429 for clients over their rate limit, keeps the rest of the requests fast. Letting every request queue makes all of them slow, and most fail anyway once they reach their timeouts.
How do I prepare for a traffic spike on Cloider?
On Cloider App Engine, use Horizontal autoscaling with a CPU threshold around 60 to 70%, up to 100 replicas of up to 2 vCPU and 4096 MB, and raise the minimum before a known event with cloider app update --replicas. On Cloider Kubernetes, use a HorizontalPodAutoscaler and raise its minReplicas. Resize managed databases days ahead.



Comments