Chapter 04 / 10 · Foundations

The operating system’s three lies

A throttled container, a silent kill with exit code 137 and a snapshot lost in a power cut, each explained by a promise the kernel keeps imperfectly.

This chapter lets you explain three behaviours of hitcount that make no sense from its source code. During a traffic spike its latency jumped by almost a tenth of a second while its CPU graph showed spare capacity. One night it disappeared with exit code 137 and no error message in its logs. And after a power cut, it came back with every counter at zero, even though it had been saving them every ten seconds.

Each of these is the operating system keeping a promise imperfectly. The kernel tells every process three convenient things: you have the CPU to yourself, you have memory to yourself, and what you wrote has been saved. Programs are written as though those were true, and mostly they are. This chapter is about where each one leaks.

One change to hitcount first. Version 2 writes all its counters to a file, counts.json, every ten seconds, and reads that file back when it starts, so a restart does not lose a day of counts.

hitcount does not have the CPU to itself

A machine runs far more threads than it has cores. The kernel’s scheduler decides which runnable thread runs on which core, and for how long. A thread runs until it blocks (waiting for a read, a lock, a timer) or until its time slice ends, a few milliseconds, at which point a timer interrupt lets the kernel take the core back and give it to someone else. Switching threads means saving one thread’s registers and loading another’s, a few microseconds directly. The indirect cost is often larger: the incoming thread finds the caches full of the previous thread’s data, and has to fetch its own back.

Go adds a layer. hitcount runs thousands of goroutines, but the kernel sees only a handful of threads. The Go runtime multiplexes goroutines onto those threads itself, and switching goroutines happens in user space without a system call, in a fraction of a microsecond. This is why a Go server can afford one goroutine per connection where a thread per connection would be expensive.

UnitMemoryCreated inSwitched byIsolation
Processits own address space~a millisecondkernel, microsecondsfull; a crash stays inside
OS threada stack of up to ~8 MB reserved, shared heaptens of microsecondskernel, microsecondsnone between threads
Goroutine / async taska few KB, growing as neededunder a microsecondlanguage runtime, ~100s of nsnone

The table also explains a familiar rule of thumb. Work that computes wants about one thread per core: more threads than cores just adds switching. Work that waits, as hitcount mostly does, wants many cheap waiters, which is what goroutines and event loops provide.

Predict first

hitcount runs in a container limited to 1 CPU on a 16-core host. During a traffic spike, its CPU graph shows it using about 60% of its limit, averaged per minute. Yet its p99 latency rises by roughly 90 ms. Where do the 90 ms come from?

Show the worked answer

A CPU limit on Linux containers is a quota per period: by default, 100 ms of CPU time in every 100 ms of wall-clock time for a 1-CPU limit. The quota is shared by all the container’s threads.

Go versions before 1.25 set the number of threads running Go code to the number of cores the host has, 16, without looking at the container’s limit. During the spike, 16 threads run in parallel, and together they use up the 100 ms quota in about 6 ms of wall-clock time. The kernel then throttles the container: none of its threads may run for the remaining ~94 ms of the period. Any request that arrives during that window waits. Averaged over a minute, usage looks like 60% because most periods are quiet; the spikes are invisible in the average and obvious in the tail.

The fix is to make the runtime’s parallelism match the limit, so it never burns the quota in a burst. Go 1.25 does this by default; older versions need GOMAXPROCS set explicitly, or a library that reads the container limit. The cost is less parallelism during short bursts, which is the honest description of a 1-CPU limit anyway.

Its memory is virtual

The addresses hitcount uses are not physical addresses in RAM. They are virtual, and every memory access is translated by the hardware, using page tables the kernel maintains, in units of 4 KiB pages. A small cache of recent translations, the TLB, makes the common case cost nothing extra. This fiction buys a great deal. Processes cannot read each other’s memory, because their page tables do not map each other’s pages. The kernel can hand out memory lazily: when hitcount asks for a gigabyte, the kernel records the promise, and only assigns physical pages when each page is first touched. That first touch triggers a page fault, a trap into the kernel that finds a free physical page, maps it, and resumes the program. A minor fault of this kind costs on the order of a microsecond. A major fault, where the page’s contents must be read from disk, costs a disk read, and turns a memory access into something a hundred thousand times slower.

This is why two memory numbers appear on every dashboard. Virtual size is what the process has been promised, and for a Go program it is often several gigabytes, because the runtime reserves address ranges it may never use. Resident set size (RSS) is what is actually occupying RAM. RSS is the number that matters, because it is what the container’s memory limit is measured against.

Here is how that limit killed hitcount. Version 2 ran in a container with a 256 MiB memory limit. Its map keys were raw paths, before the canonicalisation fix from the previous chapter. A crawler started requesting posts with a random tracking parameter on each URL, /posts/unicode?ref=8f3a…, about 100 times a second. Every one became a new key with its own Page struct, title string and map entry, roughly 200 bytes in all.

At 200 bytes per key, 256 MiB holds about 1.3 million keys. At 100 new keys a second, that is roughly 13,000 seconds, about three and a half hours. Through those hours RSS climbed steadily. When it reached the limit, the kernel first tried to reclaim memory it could drop, such as cached file pages. Nothing hitcount held was droppable. So the kernel’s out-of-memory killer sent it SIGKILL. A process cannot catch or log that signal; it simply stops. The container runtime reported exit code 137, which is 128 plus signal number 9. There was no panic, no stack trace and no last log line, because the process was never given a chance to write one.

Then it got worse. The container restarted, loaded counts.json, and the snapshot contained a million junk keys. hitcount started near its limit and was killed again within minutes, and again, a crash loop. The fix had three parts. Canonicalise paths so the query string never reaches the key. Count only paths that the content system says exist, refreshed every few minutes. And put a hard cap on the number of keys, refusing new ones past it, so no future bug can grow the map without bound. The cost is that a brand-new post is not counted until the list of known paths refreshes. We wrote down that we accept a few minutes of missed views on new posts in exchange for a memory footprint that cannot be driven by strangers.

What it wrote is not on disk yet

When hitcount calls write on a file and the call returns successfully, the bytes have been copied into the kernel’s page cache, in RAM. The kernel will write them to the storage device later, in an order of its choosing; on Linux’s default settings, dirty data is usually written back within about thirty seconds. Until then, the “written” data exists only in memory.

It is worth separating two kinds of crash. If the hitcount process dies, the data it wrote is still in the kernel’s page cache, and the kernel will still write it to disk. Only if the machine itself stops, through a power cut, a kernel panic or a hypervisor failure, is unflushed data lost. That is why durability bugs survive testing: killing the process in a test does not reproduce them.

Predict first

Version 2 saves with os.WriteFile("counts.json", data, 0644), which opens the file with truncation, writes the bytes, and closes it. The call returns nil. The process exits cleanly a second later. Five seconds after that, the power fails. When the machine comes back, what is in counts.json?

Show the worked answer

It may be the complete new snapshot, but nothing guarantees that. Truncation is a metadata change, and the new contents were sitting in the page cache. Depending on the filesystem and its options, after the power cut you can find the new file, the old file, a file of the right length full of zeros, a partially written file, or an empty file. The clean exit of the process changed nothing; the data was in the kernel’s hands, not the device’s.

The real outage followed from what hitcount did with the damaged file. On start-up it failed to parse the JSON, treated the error as “no snapshot yet”, and started every counter at zero. Ten seconds later it wrote a fresh snapshot of almost nothing over the remains of the old one.

The fix uses two operations the kernel provides for exactly this. fsync on a file blocks until that file’s data has reached the device. rename replaces one name with another atomically: anyone looking at the directory sees either the old file or the new one, never a mixture. Together they give a sequence in which a crash at any point leaves one complete snapshot:

a crash after any step leaves one complete snapshot on diskwrite counts.tmpcrash: old counts.jsonstill intactfsync(counts.tmp)crash: old file intact,new bytes on devicerename → counts.jsoncrash: either name,both completefsync(directory)the rename itselfsurvives power lossthe naive version truncates counts.json firstand leaves a window where no valid snapshot exists
Fig 1 · Write to a temporary file, flush it, rename it into place, flush the directory. A crash after any step leaves a complete snapshot
func saveSnapshot(dir string, data []byte) error {
    tmp, err := os.CreateTemp(dir, "counts-*.tmp")
    if err != nil {
        return err
    }
    defer os.Remove(tmp.Name()) // harmless once the rename has happened
    if _, err := tmp.Write(data); err != nil {
        tmp.Close()
        return err
    }
    if err := tmp.Sync(); err != nil { // fsync: the bytes reach the device
        tmp.Close()
        return err
    }
    if err := tmp.Close(); err != nil {
        return err
    }
    if err := os.Rename(tmp.Name(), filepath.Join(dir, "counts.json")); err != nil {
        return err
    }
    d, err := os.Open(dir)
    if err != nil {
        return err
    }
    defer d.Close()
    return d.Sync() // fsync the directory, so the rename itself is durable
}

The last step surprises people. A rename changes the directory, not the file, and the directory’s change sits in the page cache like any other write until the directory itself is flushed. Without that final fsync, a power cut can leave the old name in place even though the new file’s data is safely on disk.

The second half of the fix is in start-up. A snapshot that fails to parse is now a reason to refuse to start and raise an alert, not a reason to start from zero. The service is down until someone looks, which is the right trade for a counter: a few minutes of missing counts is better than silently replacing a year of them.

The cost of all this is small for hitcount. An fsync takes from well under a millisecond on a local SSD to several milliseconds on a network-attached cloud disk, and we do it twice every ten seconds. What the design does not buy is per-hit durability. If the power fails, we lose up to ten seconds of counts, and we wrote that down: these numbers choose which links appear in a sidebar, and ten seconds of them is not worth more. If hitcount billed advertisers per view, that sentence would be wrong. Each hit would have to be appended to a log and flushed before the request was acknowledged, with many hits grouped into each flush to keep the cost bearable. That design is the write-ahead log, and it is the starting point of every database you will meet in the System Design pathway.

The page cache works for reads too

The page cache that delays writes also speeds up reads, and it explains a puzzle from the platform version’s deploy logs. After an ordinary deploy, hitcount restarted and was ready in under a second. After the host machine was rebooted for a kernel update, the same restart took about five seconds, long enough for the orchestrator’s readiness check to give up and restart it again.

The difference is where counts.json was. The platform’s snapshot is about 600 MB. When hitcount restarts on a running machine, the file it wrote a minute ago is still in the page cache, so reading it runs at memory speed, a few gigabytes a second, and takes a fraction of a second. After a reboot the page cache is empty, and the file comes from the cloud disk, which on a common configuration delivers something like 125 to 250 MB a second. 600 MB at that rate is three to five seconds. Nothing in hitcount changed; the kernel’s cache did.

Two lessons follow. Measure start-up time cold, after dropping the caches or rebooting, because that is the start-up that happens during an incident. And set readiness timeouts from that cold number, with a margin. We raised the readiness check’s allowance to thirty seconds and added a log line reporting how long the snapshot took to load, so the next change in that number is visible.

The page cache has one more effect worth knowing. On Linux, file pages a container has read or written are charged to that container’s memory usage, so a container’s memory graph includes cached file data. That memory is reclaimable, which is why the kernel tries to drop it before killing anything. A container whose memory graph sits near its limit is not necessarily in danger; one whose resident anonymous memory, the heap, sits near it is.

The three promises, side by side

The promiseWhat actually happensWhere it leaked for hitcountWhat we did
You have the CPUtime slices; containers get a quota per periodthrottled for ~90 ms during burstsmatch runtime parallelism to the CPU limit
You have the memoryvirtual pages, assigned on first touch, capped by the cgroupkilled with exit code 137, then a crash loopcanonical keys, known paths only, a hard cap
What you wrote is savedbytes sit in the page cache until flushedan empty snapshot after a power cuttemp file, fsync, rename, fsync directory; refuse to start on a bad file

When the fictions are good enough

Most of the time, the right response to these leaks is to let the fiction stand. hitcount should not call fsync on every hit, pin goroutines to cores, or manage its own memory pages. Each of those would cost speed or complexity to defend against a failure the requirements say we can tolerate. The operating system’s defaults are tuned for programs like ours, and they are good.

Revisit the decision when the requirements move: when lost data becomes lost money, when a container limit is tightened to save cost, when another service is placed on the same machine and competes for its caches and cores, or when data grows past memory and starts living on disk. Each of those turns one of the three promises from “true enough” into something the design must handle.

The scheduler’s freedom to pause a thread anywhere has one more consequence, and in hitcount it is the bug that has been sitting in p.Views++ since the first chapter. The next chapter, Concurrency: two requests, one counter, runs thousands of requests at once against that line and counts what goes missing.