Languages and runtimes
What the compiler and garbage collector do on hitcount’s behalf, what they charge, and whether a rewrite in another language would change anything.
This chapter lets you predict what a language’s runtime adds to a service’s cost, in CPU, memory and behaviour under load, and judge when changing a runtime setting, or the language itself, would change the answer. Your language is not a transparent pipe to the machine. It brings a compiler that rewrites your code, often a garbage collector that manages memory for you, and sometimes a JIT, and their costs appear on your profiles under your function names.
Two things prompt the question for hitcount. The platform version’s memory graph is a sawtooth that climbs to 1.9 GB of its 2 GB limit before dropping, and a few percent of every CPU profile is the Go runtime’s own functions. And someone on the platform team has asked, reasonably, whether the service would be faster in Rust or simpler in Python.
What the compiler did with hit()
A compiler’s front end reads source text into a tree and checks it: names resolve, types agree, p.Views += "1" is rejected. Its back end lowers the tree to instructions and optimises them. Go’s compiler inlines small functions into their callers, removes array bounds checks it can prove unnecessary, deletes code whose result is never used, and runs escape analysis to decide what can live on the stack. You can ask it to explain itself:
$ go build -gcflags=-m ./...
./store.go:41:6: can inline canonical
./store.go:58:12: &Page{...} escapes to heap
./store.go:72:15: make([]row, 0, len(s.pages)) escapes to heap
./hit.go:19:23: inlining call to canonicalTwo practical consequences follow. Hand-optimising small things, such as caching a field in a local variable or writing a manual loop instead of a helper, usually produces the same machine code the compiler would have produced anyway, and makes the source harder to read. And because the compiler deletes work whose result is unused, a benchmark that computes something and throws it away may be measuring nothing, which is the “result never used” row in the previous chapter’s table.
Garbage collection, priced
Go, Java, C#, JavaScript and Python all reclaim memory automatically. Go uses a tracing garbage collector: starting from roots (global variables and every goroutine’s stack), it follows every pointer to mark each reachable object, then frees whatever was not marked. Go’s collector does most of this concurrently with the program, so its stop-the-world pauses are usually well under a millisecond. The cost has not disappeared; it has moved. Marking uses CPU, about a quarter of the available cores while a cycle runs, plus extra work charged to goroutines that allocate quickly during a cycle. And the collector needs memory headroom, because the program keeps allocating while marking happens.
Two numbers decide how much a program pays. The cost of one cycle grows with the amount of live memory and, above all, with the number of pointers the collector must follow. The number of cycles grows with how fast the program allocates relative to the headroom it is allowed. Go’s main setting, GOGC, sets the headroom: at the default of 100, a new cycle starts when the heap has grown to twice the live heap measured after the last cycle.
That rule explains the sawtooth. hitcount’s live heap is about 1 GB, mostly page data. With GOGC=100, the collector lets the heap grow to about 2 GB before starting a cycle, then marks, frees the garbage, and the heap drops back towards 1 GB. The peak of the sawtooth is the live heap times two.
The platform adds blogs, and hitcount’s live heap grows by 10%, from 1.0 GB to 1.1 GB. The container limit stays at 2 GB and nothing else changes. What happens?
Show the worked answer
The collector’s target becomes 2.2 GB. The heap grows towards it, passes 2 GB before the collector thinks a cycle is due, and the kernel kills the process with exit code 137, as in the operating system chapter. Go never reports an out-of-memory error, because Go never ran out of memory by its own accounting. It simply was not told about the container’s limit.
The trap is that nothing was close to failing in the usual sense. Live data was 55% of the limit. It was the runtime’s headroom policy, not the data, that crossed the line.
Since Go 1.19 the runtime accepts a soft memory limit, GOMEMLIMIT. Set to 1.8 GiB, it tells the collector to start cycles earlier whenever the heap approaches that figure, whatever GOGC would have said. hitcount now collects more often as it nears the limit and stays under it. The cost appears as the live heap approaches the limit: cycles run back to back, spending more and more CPU to reclaim less and less. Go caps the collector’s share of CPU in that situation, at roughly half, so the service degrades instead of spending all its time collecting, but by then it is effectively out of memory. So we also alert when the live heap passes 70% of the limit, which gives someone time to act.
The deeper fix is to give the collector less to do. Each page currently involves several pointers: the map key’s string, the *Page value, and the strings inside Page. That is about 20 million pointers to follow on every cycle. The flatter layout from the machine chapter helps here too:
type stat struct { // no pointers inside: the collector never scans these
Views, ReadMs, Reads int64
}
type store struct {
index map[string]uint32 // canonical path -> position in stats
stats []stat
titles []string
}Memory the collector knows contains no pointers is never scanned, so the 5 million stat records cost it nothing to mark. Pointers fall to roughly two per page, the key and the title, halving the marking work, and the scan for /top gets the cache-friendly layout as a side effect. The cost is code: an index to keep consistent and slots to reuse when pages are removed. We did it for the platform version only. The single blog’s two thousand pages cost the collector nothing worth recovering.
Other runtimes strike the same bargain in different ways. Java’s collectors are generational, collecting recently allocated objects often and cheaply because most objects die young. CPython frees most objects immediately by counting references to them, with a separate collector for cycles. Rust has no collector at all: the compiler tracks which variable owns each value and inserts the free when the owner goes out of scope. The invariant across all of them is that something must work out when memory is no longer needed, and that work is paid for in CPU, memory headroom, or the programmer’s time.
The same service in four runtimes
Back to the platform team’s question. The useful comparison is not a benchmark of the increment. It is what each runtime would change about hitcount’s specific problems.
| Runtime | Concurrency | The counter race | Memory per page | What it charges |
|---|---|---|---|---|
| Go | goroutines on all cores | silent for integers, fatal for maps; race detector finds both | ~200 bytes | GC CPU and headroom |
| Python (CPython) | one thread runs bytecode at a time (GIL); free-threaded builds are newer | rarer, not impossible; multiple processes need a shared store | several times Go’s, as every value is an object | interpreter overhead per operation |
| Node.js | one event loop thread per process | impossible between awaits; returns across awaits | somewhat more than Go’s | a blocked loop stops everything; JIT warm-up |
| Rust | threads or async tasks on all cores | a compile error: shared mutable data must be in a Mutex or atomic | close to the raw data | development time; no GC cost at all |
Python’s row deserves a closer look, because it changes the architecture, not just the speed. CPython’s global interpreter lock lets only one thread execute Python bytecode at a time, so a Python hitcount uses one core no matter how many threads it runs. To use eight cores, it would run eight processes, and eight processes do not share a map. The counters would move to Redis or a database, every hit would become a network round trip, and the lost update from the concurrency chapter would return in its Node-and-Redis form. The language choice would have decided the system’s shape.
Rust’s row deserves a closer look too, because it is the strongest argument for switching. Safe Rust refuses to compile a program that shares a mutable counter between threads without a lock or an atomic, so the first bug of the concurrency chapter could not have shipped. And with no collector, there is no headroom to budget and no sawtooth.
Now the decision, with costs on both sides. Rewriting in Rust would remove a memory cost we can buy for a few dollars a month (another gigabyte of RAM) and a class of bug we already catch with the race detector. It would cost weeks of work, a team learning a stricter language, and a new set of bugs in rewritten code that has worked for a year. hitcount’s CPU use at peak is half a core; its time goes to the network and the disk, which no language changes. We keep Go, set GOMEMLIMIT, and flatten the store. If the service were a high-frequency trading engine where a millisecond pause costs money, or if the GC’s share of CPU stayed above a quarter after tuning, the same reasoning could come out the other way.
When a JIT’s warm-up meets an autoscaler
The Node.js version of hitcount, which another team runs for a sister site, shows the runtime cost a JIT adds, and it is not the one people expect. Steady-state speed was fine. The trouble came from the first minute of each new instance’s life.
That deployment scales automatically: when average CPU across instances passes 70%, the platform starts more. During a spike, here is the sequence. CPU passes 70% and four new instances start. Each one begins by interpreting hitcount’s code and the HTTP library’s code, which is several times slower per request than the compiled form, and spends extra CPU compiling the hot functions it discovers. The load balancer sends each new instance its full share of traffic immediately. So the new instances run at high CPU while they warm up, average CPU across the fleet stays high, and the autoscaler starts four more, which are also cold. The fleet overshoots, then shrinks once everything is warm, and the cycle can repeat at the next spike.
A second, quieter cost came from types. hitcount’s handler received ms as a string from query strings and as a number from a newer JSON endpoint. V8 compiles a function specialised for the types it has seen; when a value of a new type arrives, it can throw that compiled code away (a deoptimisation) and compile a more general, slower version later. A handler that sees two types for the same value runs slower than one that always sees one. The fix there was to convert at the boundary, so everything inside the service sees a number.
The fix for the warm-up was to keep new instances out of the load balancer until they had handled a few thousand synthetic requests, and to scale on request rate rather than CPU. The cost is that new capacity arrives later, perhaps half a minute later, so the scaling threshold had to come down to start new instances earlier. A Go service starts at full speed and has neither problem; a Java service has both in larger measure. This is one of the places where runtime choice genuinely changes how a system behaves.
Types, and the price of crossing boundaries
A type system catches some of the bugs in this pathway and not others, and it helps to know which. Go would not let the first draft add an int64 to an int32 without an explicit conversion. But the conversion, int32(total), compiles happily and truncates silently. The type system made the narrowing visible in the source; it did not make it safe. And types stop at the edge of the process. Once a number is serialised as JSON, the receiving runtime applies its own types, which is how the 64-bit page IDs broke in JavaScript.
Calling between runtimes has a cost per crossing. A Python program calling into C, or a Go program calling C through cgo, pays to convert arguments and to coordinate the two runtimes on every call, tens of nanoseconds at the least and often much more. A loop that crosses once per item spends its time crossing. The pattern that works is the one this pathway keeps finding: hand the whole array to NumPy rather than calling it per number, make one system call with a large buffer rather than many with small ones, send one request with a hundred hits rather than a hundred requests. Cross boundaries rarely and carry a lot each time.
Static versus dynamic typing is a separate dial, and an engineering one. Static types are checked documentation and a safety net for refactoring, and they pay off more as a codebase and its team grow. Dynamic typing buys speed of change when the code is small. That is why many successful dynamic codebases add types gradually, through TypeScript or Python’s type hints, at the point where the cost of maintenance overtakes the cost of declaring types.
Build a small interpreter once
The exercise in this chapter that repays its time best is to build a tiny interpreter. Give hitcount a query language, something like top 10 where path starts "/posts/" by views, and implement it: a lexer that turns text into tokens, a parser that turns tokens into a tree, and an evaluator that walks the tree over the page data. A weekend is enough, and Crafting Interpreters covers the full journey if you want more. Most of what seems mysterious about languages, such as how scope works, why an error is reported where it is, what a stack trace is really listing, and what a REPL does, becomes ordinary once you have written each piece yourself.
When the runtime choice is worth revisiting
Most of the time the runtime is the least important thing to change. Team skill, libraries and operational experience usually outweigh the differences in the table above, and a rewrite throws away years of fixed bugs. Revisit the choice when a profile shows the runtime’s own costs dominating after its settings have been tuned: collection taking a large share of CPU, pause times that break a latency target measured in microseconds, start-up time that matters because instances start on every request, or memory per instance multiplied across thousands of replicas. Short of those, change the settings and the data layout first.
Every technique in this pathway so far has been arithmetic on hitcount’s own numbers. The last chapter, The mathematics you will actually use, makes that arithmetic explicit: what an average hides, how to combine percentiles, how much error sampling introduces, and the vectors, gradients and probabilities the AI Engineering pathway assumes.