Architecture

The Thundering Herd Problem: Why Servers Collapse All at Once and How to Stop It

By NileVPS Team · Published · 4 min read

اقرأ المقال بالعربي

Your database restarts after a routine update and is back within twenty seconds. Then it falls over again. Every application worker, every cron job and every client retried at the same moment it came back, and the burst was far larger than normal traffic. That is the thundering herd: many waiting parties are released at the same instant and stampede toward one shared resource, overwhelming it precisely when it is most fragile. The problem is not the volume of work. It is the synchronisation.

Where thundering herds come from

The pattern shows up in several forms, but they all share one trait: something lines up many clients on the same moment.

  • Cache expiry (cache stampede). A hot key expires and every request that misses rebuilds it at the same time.
  • Synchronised retries. A dependency fails, and every client retries after exactly one second, then exactly two, keeping the waves aligned.
  • Reconnect storms. After a network blip or a server restart, thousands of WebSocket or database clients reconnect at once.
  • Scheduled jobs. Every server runs 0 * * * * cron jobs at the top of the hour, or every customer device syncs at midnight.
  • Kernel-level wakeups. Historically, many processes blocked on the same socket were all woken for one incoming connection. Modern Linux mitigates this with EPOLLEXCLUSIVE and SO_REUSEPORT, which Nginx can use through reuseport on its listen directive.

Why it hurts more than normal load

A server that handles 1,000 requests per second evenly may fail at 3,000 arriving in the same 100 milliseconds. Connection pools are exhausted, queues fill, latency climbs, and timeouts trigger yet more retries. The herd feeds itself. A resource recovering from failure, such as a database warming its caches after a restart, has even less capacity than usual, so it gets hit hardest when it is weakest.

Fix 1: add jitter to everything scheduled or retried

Randomness breaks synchronisation. Instead of retrying after a fixed delay, use exponential backoff with jitter:

import random, time

def call_with_retry(fn, attempts=6, base=0.2, cap=10.0):
    for i in range(attempts):
        try:
            return fn()
        except Exception:
            if i == attempts - 1:
                raise
            delay = random.uniform(0, min(cap, base * 2 ** i))
            time.sleep(delay)

The "full jitter" approach above picks a random delay between zero and the backoff ceiling, spreading retries widely. Apply the same idea to cache TTLs. Instead of ttl = 3600, use ttl = 3600 + random.randint(0, 300) so keys written together do not expire together.

For cron, systemd timers have built-in jitter:

[Timer]
OnCalendar=hourly
RandomizedDelaySec=15min

With classic cron, set SHELL=/bin/bash in the crontab and prefix the command with sleep $((RANDOM \% 600));. The backslash matters, because cron treats an unescaped % as a newline.

Fix 2: let only one caller rebuild

When a hot cache key is missing, one request should recompute it and the rest should wait or receive the old value. This is request coalescing. In Nginx, proxy_cache_lock on handles it for cached HTTP responses. In application code, use a short Redis lock:

SET lock:product:42 <token> NX PX 5000

Whoever gets the lock rebuilds the value. Everyone else briefly sleeps and rereads the cache, or serves stale data.

Fix 3: serve stale while refreshing

Keeping a slightly old value is almost always better than a stampede. Options include:

  • Nginx: proxy_cache_use_stale updating error timeout; with proxy_cache_background_update on;
  • HTTP caches and CDNs: the stale-while-revalidate directive in Cache-Control.
  • Application caches: store a soft expiry inside the value, and refresh early in the background once it has passed, while the hard TTL is still in the future.

A refinement called probabilistic early expiration makes each reader refresh with a small, rising probability as expiry approaches, so one request usually refreshes the key before it actually expires.

Fix 4: protect the resource itself

Even with all the above, you want the shared resource to survive a burst:

  • Cap concurrency with connection pools such as PgBouncer, so the database sees a fixed number of connections no matter how many clients arrive.
  • Shed load early with rate limits, for example Nginx limit_req, returning 503 with a Retry-After header rather than queueing forever.
  • Use a circuit breaker so clients stop hammering a dependency that is clearly down.
  • After restarts, warm caches and bring capacity back gradually instead of opening the floodgates.

Quick diagnosis checklist

SymptomLikely herd sourceFirst fix
Load spikes exactly on the hourAligned cron jobsRandomizedDelaySec or random sleep
DB falls over right after recoveringSynchronised retriesExponential backoff with jitter
Spikes when a popular page expiresCache stampedeCache lock plus stale serving
Connection count jumps after a deployReconnect stormRandomised reconnect delay

Graphs from your monitoring will usually show the herd as sharp, regular spikes rather than a smooth curve. Size your servers with headroom for bursts; plans are listed on /pricing.

FAQ

Is a thundering herd the same as a DDoS attack?

No. A DDoS is external and deliberate. A thundering herd is self-inflicted: your own clients, workers or schedules synchronise and overload your system. The symptoms can look similar, but the fixes are about design, not filtering traffic.

Does adding more servers solve it?

Only partly. More capacity raises the threshold, but synchronised bursts can grow with your user base. Jitter, coalescing and stale serving remove the synchronisation itself, which is cheaper and more reliable than buying headroom for the worst spike.

How much jitter should I add?

Enough to spread the burst across a window the resource can comfortably absorb. For cache TTLs, 5 to 10 percent of the TTL is a common starting point. For retries, full jitter between zero and the backoff ceiling works well. Measure the result rather than guessing.

Related guides