Reasoning about cost
Can one machine count views for 5 million pages? Growth rates, a hidden quadratic, and an estimate that finds the real bottleneck.
This chapter lets you estimate, before building, whether a design will survive the load it is meant for, and find out which part of it will break first. The tools are a way of describing how cost grows with input (big-O notation), the prices from earlier chapters, and a few minutes of arithmetic.
The platform from the machine chapter has said yes. hitcount will count views for about 20,000 blogs and 5 million pages. Traffic averages 1,000 hits a second, with peaks of 10,000 when several posts go viral at once. Each blog’s sidebar calls /top for its own pages, and the platform’s home page shows a trending list across all of them. Before anyone writes code for this, we want to know three things. Do any of hitcount’s algorithms fall over at this size? Can one machine do it? And if something breaks first, what?
Ask how cost grows, then put a price on it
Big-O notation describes how the work an algorithm does grows as its input grows, ignoring constant factors. Looking up a page in a hash map is O(1): the work does not depend on how many pages there are. Scanning every page is O(n). Sorting them is O(n log n). Comparing every page with every other is O(n²). The notation deliberately hides constants, which the machine chapter showed can differ a hundredfold, so it answers a narrower question than “how fast?” It answers “what happens when n gets much bigger?”, which is exactly the question the platform asks.
| Growth | Where hitcount does it | Steps at n = 2,000 | Steps at n = 5 million | At ~1 ns per step |
|---|---|---|---|---|
| O(1) | find a page in the map | 1 | 1 | nanoseconds |
| O(log n) | find a position in a sorted index | ~11 | ~22 | nanoseconds |
| O(n) | scan every page’s count | 2,000 | 5 × 10⁶ | ~5 ms |
| O(n log n) | sort every page | ~22,000 | ~1.1 × 10⁸ | ~0.1 s, more with cache misses |
| O(n²) | compare every page with every other | 4 × 10⁶ | 2.5 × 10¹³ | ~7 hours |
The last column is the step that turns notation into a decision. Multiply the step count by a realistic cost per step, taken from the latency table, and the growth class becomes a duration you can compare with a budget. The O(n²) row is harmless at two thousand items, 4 ms, and absurd at five million.
The quiet quadratic
Nobody writes an O(n²) algorithm on purpose. It arrives as an O(n) operation inside something that is already done n times. hitcount’s version arrived with a bot filter. The rule was reasonable: ignore a repeat hit from the same IP address for the same page within 30 minutes. The implementation kept a slice of recent hits and checked each new one against all of them:
for _, r := range s.recent { // every hit in the last 30 minutes
if r.ip == ip && r.path == path {
return // repeat hit, ignore it
}
}
s.recent = append(s.recent, seen{ip, path, now})On the single blog this was invisible. At 50 hits a second, 30 minutes holds 50 × 1,800 = 90,000 entries. Checking each costs a couple of nanoseconds, so a hit spends about 0.2 ms in the loop, and 50 hits a second cost 10 ms of CPU per second: 1% of one core.
A post goes viral and hits rise from 50 a second to 2,000 a second, forty times more. The filter used 1% of a core before. What does it use now?
Show the worked answer
The rate rose 40 times, so there are 40 times as many hits to check. The window now holds 2,000 × 1,800 = 3.6 million entries, also 40 times more, so each check is 40 times longer. Total work grows by 40 × 40 = 1,600. One percent of a core becomes around sixteen cores. That is the signature of a quadratic: double the traffic and the work quadruples.
It was worse than that, because the loop ran while holding the store’s mutex. However many cores the machine had, only one hit could be in the loop at a time, so hitcount could process at most one hit per 7 ms or so, about 140 hits a second. Requests arrived at 2,000 a second and the queue grew until connections timed out.
The fix replaces the scan with a hash map keyed by the IP-and-path pair, holding the time it was last seen, and sweeps out expired entries once a minute. Each check becomes O(1). The cost moves from time to memory, and the memory is worth pricing. At the spike, 3.6 million entries at around 100 bytes each (two strings, a timestamp and the map’s overhead) is 360 MB, more than hitcount’s entire container limit. So the requirement had to give a little too. We shortened the window to five minutes, which still catches the bots we had seen, and stored a 64-bit hash of the pair instead of the two strings. Five minutes at 2,000 hits a second is 600,000 entries; at about 40 bytes each, roughly 25 MB. The maths chapter shows why a 64-bit hash makes accidental collisions between pairs vanishingly unlikely.
This is the general shape of algorithmic fixes in services: trade a growing cost in time for a bounded cost in memory, then check the memory against the machine. An estimate that stops after the first half often trades one outage for another.
/top: sort it, heap it, or keep it sorted
/top has four reasonable designs. Which one is right depends on two numbers: how many pages there are, and how often /top is called compared with how often a hit arrives.
| Design | Cost per /top | Cost per hit | What it must also handle |
|---|---|---|---|
| Sort every page on each call | O(n log n) | O(1) | nothing; it is the simplest |
| Scan with a 10-item heap | O(n log k), close to O(n) | O(1) | a flat layout to make the scan fast |
| Keep pages in a sorted structure | O(k) | O(log n): remove and reinsert | every hit pays; pointer-heavy trees |
| Compute every t seconds, cache it | O(1) almost always | O(1) | the list is up to t seconds stale |
For the original blog: n = 2,000, /top called about 5 times a second (the CDN in front of the blog caches most sidebar requests), and up to 2,000 hits a second. Sorting costs about 22,000 comparisons, perhaps 0.1 ms, five times a second: half a millisecond of CPU per second. A sorted structure would instead charge every hit about 11 steps of pointer chasing, 22,000 steps a second at the spike. The costs are similar and tiny, so the simplest design wins. We keep the sort.
Now change the variables to the platform’s trending list: n = 5 million, called 50 times a second, with 10,000 hits a second. Sorting costs around a second per call, at least; fifty calls a second would need fifty cores. That design is out. A heap scan over a flat array costs about 15 ms per call, 0.75 of a core at fifty calls a second. It works, but it spends most of a core recomputing an answer that barely changes between calls. Caching for 5 seconds means one scan per 5 seconds, about 3 ms of CPU per second. The cost is that the trending list can be 5 seconds out of date, and nobody browsing a trending list can tell. The decision: for the platform, scan with a heap every 5 seconds and serve the cached result; for a single blog’s sidebar, keep sorting on each call.
Amortised and expected costs
Two refinements stop big-O from misleading. The first is amortised cost. A Go map that runs out of room grows to a larger table and moves its entries. That one insert costs O(n), but it happens only after many cheap inserts, so the cost averaged over all inserts is still O(1). Go also spreads the move across subsequent operations rather than doing it all at once, so no single hit pays the full price. When latency matters, it is worth asking whether an amortised O(1) operation does its expensive work all at once.
The second is the difference between expected and worst-case cost. A hash map is O(1) on average because a good hash function spreads keys evenly over its slots. If many keys land in the same slot, lookups degrade to O(n), and n lookups to O(n²). For a service whose keys come from the internet, that is not a theoretical case. In 2011, researchers showed that many web frameworks could be stalled with a single request full of parameter names crafted to collide, a hash-flooding attack. Go’s maps use a hash seeded randomly when each map is created, so an attacker cannot compute colliding paths in advance. If you ever write your own hash table keyed by outside input, it needs the same property.
The estimate, worked: can one machine run the platform?
Now the question the platform actually asked. We go resource by resource, with the peak load of 10,000 hits a second and 5 million pages.
CPU. A hit costs a few tens of microseconds of CPU: parsing HTTP, a few system calls, a canonicalised map lookup and a short critical section. Call it 50 µs to be safe. 10,000 × 50 µs = 0.5 seconds of CPU per second, half a core. The /top designs above add a few percent.
Memory. About 200 bytes per page for the key, struct, title and map overhead, times 5 million, is 1 GB. The bot filter adds 25 MB. A machine with 4 GB of RAM leaves comfortable headroom, and the languages chapter will show why “comfortable” matters for a garbage collected runtime.
Network. A hit request is about 500 bytes with headers. 10,000 × 500 bytes = 5 MB a second, 40 Mbit/s. Any cloud machine handles that.
Disk. This is where the estimate finds the problem. The snapshot is JSON at about 120 bytes a page, so 5 million pages make a 600 MB file. Written every 10 seconds, that is 60 MB a second of continuous disk writes. Encoding JSON at roughly 400 megabytes a second takes about a second and a half of a core per snapshot, 15% of a core all the time, and the concurrency chapter’s design copies all the counts under the lock first. Nothing about the hit path is in trouble. The snapshot is.
The real fix is to stop writing pages that have not changed. At 1,000 hits a second, at most 10,000 pages change in a 10-second window, about 1.2 MB of JSON. Write a full snapshot once an hour and small files of changed pages every 10 seconds, and on restart load the full snapshot and replay the changes after it. The cost is recovery code that must handle partial and out-of-order files, which is the design of a log-structured store in miniature and the subject of a System Design chapter. Until it is built, the interim decision is a full snapshot once a minute instead of every ten seconds: one sixth of the write load, in exchange for up to a minute of counts lost in a power cut. The performance chapter picks up what happened next.
Money. A cloud machine with 4 vCPUs and 8 to 16 GB of memory costs in the region of a hundred dollars a month at on-demand prices, less with a commitment. That number is worth putting next to the alternative. Splitting hitcount across several machines to “be ready for scale” would take an engineer weeks and add every problem in the Distributed Systems pathway. A year of the single machine costs less than a few days of that engineer’s time. The estimate is how we earned the right to stay on one machine.
Why half a core is not the same as half the risk
The CPU estimate said half a core at peak, on a four-core machine. It is tempting to read that as “we could take eight times the traffic”. Latency says otherwise, because of queueing, and the shape of the effect is worth carrying into every estimate.
Any resource that serves requests one at a time, such as a core, a lock or a disk, has a utilisation ρ: the fraction of time it is busy. When requests arrive at random, a request that finds the resource busy waits. The simplest queueing model, a single server with random arrivals and random service times, gives the average time a request spends as the service time divided by (1 − ρ). At 50% utilisation, requests take twice their service time on average. At 80%, five times. At 90%, ten times. At 95%, twenty. Real systems do not follow the model exactly, but they share its shape: waiting is modest up to about half busy, grows quickly past 70 or 80%, and has no limit as utilisation approaches 100%.
This is the hidden half of the bot filter story. Its loop, running under the store’s mutex, made the mutex itself the resource. At 50 hits a second each holding it for 0.2 ms, the mutex was 1% busy and nobody waited. At the spike, each hit needed it for about 7 ms and 2,000 arrived each second, which asks for 14 seconds of mutex time per second. Utilisation above 100% has no steady state; the queue simply grows until something times out.
So the estimate needs a target utilisation, not just a capacity. We plan for the busiest resource to be at most about 50% busy at the expected peak. hitcount’s CPU at 12% of four cores and its store mutex at a fraction of a percent both pass. The rule has a cost too: it means paying for capacity that is idle most of the time. The alternative is latency that climbs sharply exactly when traffic is highest, which for most services is the worst time for it.
When the estimate is the wrong tool
For small inputs, growth rates are irrelevant and constants decide. A linear scan of a dozen items in a slice beats a hash map lookup, and nobody should build a heap to find the largest of ten numbers. Estimating also has limits in the other direction. An estimate gives you an order of magnitude; it does not give you a tail latency, a lock convoy or a garbage collector pause. It tells you where to look, and measurement, the subject of the next chapter, tells you what is there.
One more trap: big-O counts operations, not where they happen. If the sidebar fetched ten titles from the content system one request at a time, that is O(k) with k = 10, and also ten round trips, about 5 ms in one data centre. If someone later asks for the top hundred, it is a hundred round trips. A loop of network calls is priced in round trips, and the fix is to batch them into one request.
The estimate says one machine can run the platform, and that the snapshot is the part to watch. The next chapter, Measuring before believing, starts on the morning after a release, when the p99 latency of /hit went from 4 ms to nearly a second and nothing in the estimate predicted it.
Free textbook plus problem sets. Rigorous and unusually well written.