From source code to a running process
We meet hitcount and follow it from Go source to machine instructions, a process, its system calls and the stack trace it prints when it crashes.
This chapter follows one small program from the text you type to the instructions a processor runs. The aim is practical. When a stack trace, a profile or a crash report shows you something strange later on, you should be able to say which layer it came from and what that layer was doing.
The program is hitcount, and it stays with us for the whole pathway. A blog of about two thousand posts puts a small script on every page. When a reader leaves a post, the script sends one HTTP request to hitcount naming the page and how long the reader stayed. hitcount adds one to that page’s counter. A second endpoint returns the ten most-read pages, which the blog shows in its sidebar. On an ordinary day hitcount sees about 50 requests a second. When a post reaches the front page of a link aggregator, that climbs to around two thousand.
Here is the first version, in Go. It is deliberately naive, and most of the chapters that follow find something wrong with it. For now, read it as a list of things the machine will have to do.
type Page struct {
Path string
Title string
Views int64
ReadMs int64 // total reported time on page, in milliseconds
Reads int64 // how many time-on-page reports we received
}
var pages = map[string]*Page{}
var total int64
func hit(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
path := q.Get("page")
p, ok := pages[path]
if !ok {
p = &Page{Path: path, Title: fetchTitle(path)}
pages[path] = p
}
p.Views++
total++
if ms, err := strconv.ParseInt(q.Get("ms"), 10, 64); err == nil {
p.ReadMs += ms
p.Reads++
}
w.WriteHeader(http.StatusNoContent)
}
func top(w http.ResponseWriter, r *http.Request) {
list := make([]*Page, 0, len(pages))
for _, p := range pages {
list = append(list, p)
}
sort.Slice(list, func(i, j int) bool { return list[i].Views > list[j].Views })
if len(list) > 10 {
list = list[:10]
}
json.NewEncoder(w).Encode(list)
}
func main() {
http.HandleFunc("/hit", hit)
http.HandleFunc("/top", top)
http.ListenAndServe(":8080", nil)
}fetchTitle asks the blog’s content system for a post’s title the first time hitcount sees its path. We will come back to it in the network chapter, because it is the line most likely to take the whole service down.
What the processor does with p.Views++
A processor understands a small vocabulary of instructions. Load a value from memory into a register. Add two registers. Store a register back to memory. Compare two values. Jump to a different instruction, either always or only if the last comparison came out a certain way. A register is one of a few dozen slots inside the core that hold a 64-bit value each and can be read in a single cycle. Everything else in your program, including structs, maps, closures and HTTP handlers, is eventually expressed in that vocabulary.
Take the single line p.Views++. On a 64-bit x86 machine it becomes something close to this:
MOVQ p, AX ; AX = address of this Page struct
MOVQ 32(AX), CX ; CX = the 8 bytes found at AX + 32 (the Views field)
INCQ CX ; CX = CX + 1
MOVQ CX, 32(AX) ; write CX back to AX + 32Two details are worth slowing down for. First, why 32? A Go string is stored as a pointer and a length, 16 bytes in total. Path occupies bytes 0 to 15 of the struct and Title bytes 16 to 31, so Views starts at byte 32. At run time the field has no name. It is an offset from an address, decided by the compiler. Second, the increment is three separate steps: read the old value, compute the new one, write it back. The compiler may fuse them into one instruction, INCQ 32(AX), but the core still performs a read, an add and a write internally. That fact is harmless today and becomes the central bug of the concurrency chapter, when two cores run those steps on the same page at the same moment.
The core runs a loop it never leaves: fetch the instruction at the address held in the instruction pointer, decode it, execute it, move the pointer on. There is no if in silicon. The line if !ok becomes a test of a register followed by a conditional jump that skips the block when the page is already known. Modern cores do not wait to find out which way that jump goes. They predict it and carry on executing down the predicted path, throwing the work away if the guess was wrong. A wrong guess costs on the order of 15 to 20 cycles. For hitcount the guess is almost always right, because after the first few minutes nearly every request is for a page that already exists. Branches that go the same way most of the time are close to free; branches that depend on unpredictable data are not, and that is one reason the same algorithm can run at very different speeds on different inputs.
Three roads from source text to instructions
Go is compiled ahead of time. go build reads the source, checks the types, optimises, and writes machine code for one operating system and one processor family into a single executable file of several megabytes. By the time hitcount starts, every instruction it will run already exists.
That is one of three common roads. Suppose a colleague writes the same service in Python. CPython compiles the source to bytecode, a compact list of operations for an imaginary machine, and then a loop written in C reads those operations one at a time and carries each one out. p.views += 1 becomes five or so bytecode operations (load the object, load the attribute, load the constant, add, store the attribute), and each of those costs the interpreter dozens of real machine instructions to dispatch and execute. A third colleague writes it in JavaScript for Node.js. V8 starts the same way as CPython, interpreting bytecode, but it watches which functions run often and what types flow through them. Once hit is hot, V8 compiles it to machine code specialised for the types it has seen, a just-in-time (JIT) compiler. If a later call breaks the assumption, say a string arrives where a number always had, V8 throws the specialised code away and falls back.
| Road | hitcount written in | Start-up | Steady state | What you notice |
|---|---|---|---|---|
| Ahead-of-time compile | Go, Rust, C | milliseconds | fast from the first request | a build step; one binary per OS and CPU |
| Bytecode interpreter | CPython | tens to hundreds of ms of imports | slowest per operation | hot loops are worth moving into C libraries |
| Bytecode + JIT | Node.js, Java, C# | fast to start, slow to warm | close to compiled once warm | benchmarks change over the first seconds or minutes |
The rows blur in practice. PyPy runs Python with a JIT. Java compiles to bytecode ahead of time and then JITs it. “Compiled versus interpreted” describes an implementation, not a language. What the table gives you is a way to explain behaviour you will see.
We restart all three versions of hitcount and immediately send 20,000 requests. Then we wait a minute while traffic flows and send another 20,000. Which version’s numbers change most between the two runs, and why?
Show the worked answer
The Node.js version changes most. During the first burst, V8 is still interpreting hit and the HTTP parsing code, and it spends some of its time compiling them. After a minute of traffic those paths are compiled, and per-request cost drops noticeably. The Go version is about the same in both runs, because nothing about its instructions changes after start-up. The Python version is also roughly the same in both runs, and slower than either of the others per request, because CPython (without a JIT) interprets every operation every time.
The practical rule: say whether a benchmark was warm or cold, and for a JIT runtime, discard the first part of any measurement. Also notice what the question did not ask. At 50 requests a second, all three versions are idle most of the time. The differences only matter at the spike, and even then, as later chapters show, much of each request’s time is spent in the kernel and on the network, not in our code.
What happens when you run ./hitcount
An executable is a structured file. On Linux the format is ELF, and its header lists sections: machine code (.text), read-only constants such as the string "page" (.rodata), global variables with initial values (.data), and global variables that start at zero (.bss, where total lives). The header also names the program’s entry point.
When you type ./hitcount, the shell asks the kernel to create a new process and then calls execve, which replaces that process’s program with ours. The kernel builds a fresh, empty address space, maps the file’s sections into it (lazily: the bytes are only read from disk when first touched, which the operating system chapter explains), sets up a stack holding the command-line arguments and environment, and jumps to the entry point.
For a Go program the entry point is not main. It is the Go runtime, which sets up its memory allocator and garbage collector, starts a few operating system threads, and creates the scheduler that will run goroutines on them. Then it runs package initialisation, which is where pages = map[string]*Page{} is actually created, and only then calls main.main. A C program built the usual way has a different preamble: before its own code runs, a dynamic loader (on Linux, ld-linux-x86-64.so.2) finds and maps the shared libraries it needs, such as the C library. Go binaries are commonly built statically, with everything inside, which is why they can be copied into a nearly empty container image and run.
This layer explains one of the more confusing errors in operations work. Someone builds a program on a normal Linux distribution, copies it into a minimal Alpine container, and runs it. The shell replies no such file or directory, while ls shows the file sitting right there. The missing file is not the program. It is the dynamic loader named inside the program’s header, which Alpine does not ship because it uses a different C library. Once you know the kernel reads that header and goes looking for the loader, the message stops being absurd.
The only way out of the process is a system call
Inside its address space, hitcount can compute freely. It cannot touch the network card, the disk, or another process’s memory. Every one of those requests goes through a system call: a special instruction (syscall on x86-64) that switches the core into kernel mode at a fixed, trusted entry point. The kernel checks the arguments, does the work, and returns a result. The direct cost of the switch is in the range of a hundred nanoseconds to a microsecond on current hardware, depending on the call and on the security mitigations the kernel has enabled, and the kernel’s work also disturbs the caches our code was using.
You can watch hitcount make these calls with strace. Trimmed and simplified, start-up and one request look like this:
socket(AF_INET6, SOCK_STREAM|SOCK_NONBLOCK, IPPROTO_IP) = 3
bind(3, {sin6_port=htons(8080), ...}, 28) = 0
listen(3, 4096) = 0
epoll_ctl(4, EPOLL_CTL_ADD, 3, {EPOLLIN, ...}) = 0
...
accept4(3, {...}, [28], SOCK_NONBLOCK) = 7
read(7, "GET /hit?page=/posts/unicode&ms=41200 HTTP/1.1\r\nHost"..., 4096) = 312
write(7, "HTTP/1.1 204 No Content\r\nDate: "..., 87) = 87The small numbers returned by socket and accept4 are file descriptors: indexes into a table the kernel keeps for each process, listing the files, sockets and pipes it has open. Descriptor 3 is the listening socket; descriptor 7 is one reader’s connection. Our hit function runs between the read and the write, and nothing it does there needs the kernel. One request costs a handful of system calls, and the user-space work in between is a few microseconds.
Here is how that boundary caused an outage in a service shaped like hitcount. Someone added a debugging line to hit: log.Printf("hit %s", path). Go’s standard logger takes a lock and writes each line to standard error with its own write system call. In a container, standard error is a pipe, and on the other end is the container runtime’s logging process, which copies each line into a log file.
On a quiet day nothing happened. Then a post went viral. Traffic rose to 2,000 requests a second, which meant 2,000 log lines a second, and the logging process on the host fell behind because it was also handling every other container’s output. A Linux pipe holds 64 KiB by default, roughly a thousand of these lines. Once it filled, each write blocked until the reader made room. The goroutine doing that write blocked while holding the logger’s lock, so every other request’s log call waited for the lock. Within a second every handler in hitcount was parked behind one slow pipe. The CPU graph showed the service nearly idle, and it answered nothing.
The fix was to stop logging each hit, keep a counter of hits instead, and log a summary line every ten seconds. Where per-event logs were genuinely needed, a buffered logger that drops lines when its buffer is full would also have worked. Both fixes cost something: we lose individual log lines, sometimes exactly the ones we would want after an incident. We made that choice deliberately. A counter of page views can lose a debug line; it cannot stop answering because a log file is slow.
The call stack, physically
When top calls sort.Slice, which calls our comparison function, each call gets a stack frame: a block of memory holding the return address and the function’s local variables. Returning releases the frame. Allocating a frame is just moving the stack pointer, which is why local variables that stay on the stack cost almost nothing compared with objects allocated on the heap. Goroutine stacks start small, a few kilobytes, and the runtime grows them by copying when a call chain needs more.
Frames are also what a stack trace prints. Suppose a later version adds a helper that shortens long titles and is handed a nil page by mistake. hitcount crashes with:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x6d2f1a]
goroutine 41 [running]:
main.shortTitle(...)
/src/hitcount/top.go:58
main.top({0x8a1e40, 0xc0001c2000}, 0xc0001b8100)
/src/hitcount/top.go:31 +0x1ba
net/http.HandlerFunc.ServeHTTP(...)
/usr/local/go/src/net/http/server.go:2171
...Read it from the top. The first frame is where the fault happened; each frame below it is the caller of the one above. The bug is in shortTitle at line 58 or in top at line 31, which handed it the nil, and not in the HTTP server further down, which merely called our code. The address is informative too. addr=0x10 is 16: the program tried to read the field at offset 16 of a struct whose address was zero. Offset 16 in Page is Title. The operating system never maps the first page of the address space, precisely so that reads through a nil pointer fault instead of returning garbage. The processor raised the fault, the kernel turned it into a signal, and the Go runtime turned the signal into the panic you see.
When this level of detail is not worth your time
Most days you will not read assembly or strace output, and you should not. hitcount’s correctness depends on the logic in hit and top, and its speed at 50 requests a second is not in question. The layer model earns its keep when a symptom does not make sense at the level where you are looking: a file that exists but is “not found”, a service that stops answering while its CPU is idle, a crash address that names a field. Those are the moments to drop a layer, find the instruction, frame or system call involved, and come back up.
Revisit this chapter when a profile shows time in functions you did not write, such as runtime internals or system calls, or when the same code behaves differently on two machines. Those are both signs that something below your source code is doing the work.
Everything in this chapter moved numbers around: a count, a length, an offset of 32. The next chapter, Bits, numbers and text, asks what those numbers actually are. It follows hitcount’s counters to the edge of their bits, finds out why its average reading time stopped moving, and explains why a post called “Café” once appeared in the sidebar as “Café”.