Show contents
Chapter 5 of 6 · 25 min
Project: results day
By the end of this chapter, you'll be able to
- Estimate a traffic peak from explicit assumptions
- Reduce load by serving immutable content from an edge cache
- Protect an endpoint with a token bucket
- Bound a queue to keep latency acceptable under overload
- Write a reasoned, verifiable capacity plan
1. Estimating the peak
Every estimate rests on assumptions: write them down, so they can be discussed and corrected.
candidates = 300_000
visitors_per_candidate = 2.5 # the candidate, a parent, a teacher…
share_first_minute = 0.30 # 30% arrive in the first minute
pages_per_visit = 4 # home, search, result, refreshes
visit_s = 60
visitors = candidates * visitors_per_candidate
arrivals_per_s = visitors * share_first_minute / 60
simultaneous_visitors = arrivals_per_s * visit_s # Little's law
page_rate = simultaneous_visitors * pages_per_visit / visit_s
print(f"expected visitors : {visitors:,.0f}")
print(f"arrivals at the peak : {arrivals_per_s:,.0f} per second")
print(f"simultaneous visitors : {simultaneous_visitors:,.0f}")
print(f"pages per second : {page_rate:,.0f}")
expected visitors : 750,000
arrivals at the peak : 3,750 per second
simultaneous visitors : 225,000
pages per second : 15,000
About 15,000 pages per second during the first minute: far more than a classic relational database serves without preparation, while the rest of the year the site gets a few per minute. Building permanent infrastructure for this peak would be a waste: almost nothing must reach the servers.
2. Serving the immutable from the edge
Key observation: once published, the results never change. They can therefore be served by a CDN (content delivery network: cache servers spread around the world, close to users) with a long time to live. Only the "candidate number → result page" search needs computing, and even that can be cached per number.
page_rate = 15_000
for cdn_share in (0.0, 0.90, 0.97, 0.99):
to_servers = page_rate * (1 - cdn_share)
print(f"{cdn_share:>4.0%} served by the CDN → {to_servers:>6,.0f} req/s to the servers")
0% served by the CDN → 15,000 req/s to the servers
90% served by the CDN → 1,500 req/s to the servers
97% served by the CDN → 450 req/s to the servers
99% served by the CDN → 150 req/s to the servers
With 97% of pages served by the CDN (home page, styles, scripts, result pages already viewed), 450 requests per second remain for the origin: an ordinary load. Preparing a static page per candidate in advance, published on the CDN at 10 am, removes almost all computation.
Results are frozen: the database serves from read replicas, with no concurrent writes.
Text description of the animation
- Most pages are served by the nearest cache server, without touching the origin.
- Each address gets a reasonable rate; a bot hammering the search is slowed down.
- Requests wait for a free worker; beyond 400, the answer is immediately "try again in 30 s".
- The application computes the answer, or reads it from its own cache.
- Results are frozen: the database serves from read replicas, with no concurrent writes.
3. Rate limiting with a token bucket
Some clients abuse the service: bots trying every number, apps refreshing in a loop. The token bucket is the most common limiting algorithm: each client has a bucket of capacity tokens, refilled at rate tokens per second. Each request consumes a token; empty bucket → 429 response ("too many requests"). It allows short bursts while enforcing an average rate.
class TokenBucket:
def __init__(self, capacity, rate):
self.capacity, self.rate = capacity, rate
self.tokens, self.last = capacity, 0.0
def allow(self, now):
elapsed = now - self.last
self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
# A human: one request every 3 s. A bot: 20 per second for 3 s.
for name, instants in [("human", [i * 3.0 for i in range(6)]),
("bot ", [i * 0.05 for i in range(60)])]:
bucket = TokenBucket(capacity=5, rate=1)
accepted = sum(bucket.allow(t) for t in instants)
print(f"{name}: {accepted} accepted out of {len(instants)}")
human: 6 accepted out of 6
bot : 7 accepted out of 60
The human is never bothered; the bot gets its burst of 5, then about one token per second. In real life, the bucket is stored in a shared cache (Redis, for example) so that every server applies the same limit, and the per-IP limit stays cautious: behind a single address there is sometimes a whole school or an entire mobile operator.
4. Bounding the queue
When requests arrive faster than they are handled, an unbounded queue grows endlessly: everyone waits longer and longer, gives up, reloads… and adds yet another request. It is better to refuse quickly some requests (with a clear message and a retry delay) than to make everyone wait indefinitely.
import random
def simulate(max_queue, seconds=60, arrivals_per_s=600, capacity_per_s=500):
random.seed(11)
queue, served, refused, waits = [], 0, 0, []
for t in range(seconds):
for _ in range(arrivals_per_s + random.randint(-50, 50)):
if max_queue is None or len(queue) < max_queue:
queue.append(t)
else:
refused += 1
for _ in range(min(capacity_per_s, len(queue))):
waits.append(t - queue.pop(0))
served += 1
waits.sort()
p95 = waits[int(len(waits) * 0.95)]
return served, refused, p95
for max_queue in (None, 1_000):
served, refused, p95 = simulate(max_queue)
name = "unbounded queue " if max_queue is None else "queue of 1,000 "
print(f"{name}: {served} served, {refused} refused, p95 wait = {p95} s")
unbounded queue : 30000 served, 0 refused, p95 wait = 10 s
queue of 1,000 : 30000 served, 5577 refused, p95 wait = 1 s
In both cases, the server handles as many requests: its capacity does not change. But without a bound, the wait climbs to several seconds for everyone, well beyond the point where people give up; with a bounded queue, accepted requests are served in about a second, and the others immediately get "try again in 30 s". A virtual waiting room, handing out places in order of arrival, is the user-friendly version of this principle.
5. The capacity plan
The project's deliverable is a short document that the whole team can review and challenge:
Capacity plan — results publication, 15 July 10 am
Assumptions (to be checked against last year's figures)
- 300,000 candidates × 2.5 visitors; 30% in the first minute; 4 pages per visit.
- Estimated peak: 15,000 pages/s during the first minute.
Architecture
- Result pages generated in advance, published on the CDN at 10 am (time to live 24 h).
- Search by number: 450 req/s, i.e. 4 servers at 200 req/s under 70% (+1 spare), application cache, read replica.
- Token bucket: bursts of 5 requests, 1 per second per IP address.
- Queue bounded at 1,000 requests, 503 response with "Retry-After: 30" beyond that.
Verification
- Load test on 1 July: random numbers, cold cache, sudden arrival.
- Criteria: p95 < 2 s for accepted requests, no 5xx errors other than intended refusals.
On the day
- On-call team from 9:30 am to 1 pm, dashboard: throughput, p95, CDN hit rate.
- Plan B: static waiting page on the CDN if the origin saturates.
Your turn
Worked exercise
Project: your capacity plan
Adapt the plan to another event of your choice (university enrolment opening, concert ticketing, publication of a civil service competition):
- Write your assumptions and compute the peak in pages per second.
- Decide what can be served by the CDN and compute the remaining load.
- Compute the number of origin servers, knowing that a server handles 200 requests per second and that you aim for 70% utilisation, plus one spare server.
- Choose the token bucket and queue parameters, and justify them.
Hint 1
Hint 2
ceil(origin_load / (200 × 0.7)) + 1.Show the solution and common mistakes
Example for university enrolment opening:
import math
applicants = 80_000
share_first_hour = 0.50
pages_per_session = 25
session_s = 15 * 60
arrivals_per_s = applicants * share_first_hour / 3600
simultaneous_sessions = arrivals_per_s * session_s
rate = simultaneous_sessions * pages_per_session / session_s
cdn_share = 0.60 # information pages and static assets; forms go to the origin
origin = rate * (1 - cdn_share)
servers = math.ceil(origin / (200 * 0.7)) + 1
print(f"simultaneous sessions: {simultaneous_sessions:.0f}")
print(f"peak: {rate:.0f} pages/s, of which {origin:.0f} to the origin")
print(f"origin servers: {servers}")
simultaneous sessions: 10000
peak: 278 pages/s, of which 111 to the origin
origin servers: 2
Chosen parameters: a bucket of 10 tokens and 2 per second (a multi-step form chains quick requests), a queue bounded at 300 requests (about one second of work for 2 servers at 140 useful requests per second each), a waiting room if the queue stays full for more than a minute. And above all: a load test with real forms, different accounts and a sudden arrival.
Common mistakes:
- Forgetting that writes (enrolments, payments) do not go through the CDN: they are what saturates the database.
- Choosing limits without justifying them: a bucket that is too small blocks real users behind the same IP address.
- Having no plan B: when an assumption is wrong on the day, you need a ready fallback, not improvisation.
Summary
- 1A capacity plan starts with written assumptions and a peak estimate using Little's law.
- 2What does not change is served from a CDN: the real load on the origin drops by orders of magnitude.
- 3A token bucket limits the average rate while tolerating short bursts.
- 4A bounded queue quickly refuses some requests rather than making everyone wait.
- 5A load test is only worth something if it resembles the real day: varied data, cold cache, sudden arrival.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.