Chapter 05 / 10 · Foundations

Concurrency: two requests, one counter

100,000 hits go in and 97,412 come out. Lost updates, the invariants locks protect, and a deadlock in the snapshot code.

This chapter lets you look at a piece of shared state and answer one question precisely: who is allowed to touch it, and when? Once you can answer that, choosing between a lock, an atomic operation and a single owner becomes a decision with known costs rather than a matter of taste.

Go’s HTTP server serves each connection on its own goroutine, and the runtime spreads goroutines across every core. During a spike, hundreds of goroutines run hit at the same moment, on eight cores, all reading and writing pages and total. We test it: a load generator sends exactly 100,000 hits for one page from 200 connections. Afterwards /top reports 97,412 views. We run it again and get 96,880. On the third run hitcount crashes with fatal error: concurrent map writes. These are two different bugs, and they fail in opposite ways.

How an increment goes missing

The first chapter showed what p.Views++ becomes: load the value into a register, add one, store it back. Each core has its own registers. If two cores run those three steps on the same page and their steps interleave, both can load the same old value.

time →Core 1Core 2load Views = 41add → 42store Views = 42load Views = 41add → 42store Views = 42two hits handled · Views moved by one · core 2 loaded before core 1 stored
Fig 1 · The lost update. Both cores load 41 before either stores, so two hits leave the counter at 42

Both cores did exactly what the code says. The result is still wrong, and only sometimes, which is what makes this class of bug expensive. A data race is two accesses to the same memory from different threads, at least one of them a write, with nothing ordering them. Even when the compiler emits a single INCQ instruction, the core performs the load, add and store internally, and without a special locked form of the instruction another core’s write can land in between.

Predict first

We write a test: 100 goroutines each increment total 1,000 times with no synchronisation. We run it on a laptop with 8 cores, and then in CI on a runner with one core. What totals do we see?

Show the worked answer

On 8 cores, a total below 100,000 that changes from run to run. How far below depends on timing, on the compiler’s choices and on how often goroutines collide.

On a single-core runner the test very often passes with exactly 100,000. With one core, only one goroutine runs at a time, and the Go scheduler rarely switches goroutines in the middle of three instructions. The race is still there; it just almost never fires. This is how racy code reaches production with a green test suite.

The dependable way to find it is the race detector. go test -race instruments every memory access and reports any pair of unordered accesses it observes, with the stack of each, whether or not the interleaving actually produced a wrong answer on that run. It slows the program several times over, so it belongs in tests and staging, not in production.

The map fails differently. Inserting into a map can make it grow, which moves entries into a new, larger table. A goroutine reading or writing during that move can see a half-moved table: entries missing, entries twice, internal pointers to memory that is about to be reused. Rather than let that corrupt the program quietly, the Go runtime checks for concurrent writes in many cases and stops the whole process with a fatal error that cannot be recovered. A crash is unpleasant, but it is a better failure than a counter that is silently wrong, because somebody notices it.

Three ways to make the increment safe

A mutex (mutual exclusion lock) lets one goroutine at a time into a section of code. Taking and releasing an uncontended mutex costs about 20 ns. Here is the store with one:

type store struct {
    mu    sync.Mutex // guards pages and total.
                     // Invariant: total == sum of p.Views over all pages.
    pages map[string]*Page
    total int64
}

func (s *store) hit(path string, ms int64, hasMs bool) {
    s.mu.Lock()
    defer s.mu.Unlock()
    p, ok := s.pages[path]
    if !ok {
        p = &Page{Path: path} // title fetched elsewhere, never under the lock
        s.pages[path] = p
    }
    p.Views++
    s.total++
    if hasMs {
        p.ReadMs += ms
        p.Reads++
    }
}

An atomic operation does a read-modify-write as one indivisible step, using the processor’s locked instructions: atomic.Int64’s Add, for example. It costs a few nanoseconds uncontended, more when many cores fight over the same cache line. It protects one word of memory and nothing else. A third option is to have no shared state at all: one goroutine owns the map, and handlers send it paths over a channel. Nothing needs a lock because only one goroutine ever touches the data.

ApproachWhat it guaranteesWhat it costsRight when
One mutex around the storeall fields change together; readers see a consistent state~20 ns per hit uncontended; waiting when contendedupdates are short and the state is related
Atomic per countereach counter is exact on its owna few ns; no help with map inserts or multi-field updatesone independent number, such as a request count
Sharded store (N maps, N locks)consistency within each shard onlymore code; /top must merge shardsa profile shows one lock is genuinely contended
Single owner + channelno shared memory at all~100s of ns per send; one core’s throughput at mostthe logic is complex and naturally sequential

For hitcount, the arithmetic picks the first row. Each hit holds the lock for perhaps 100 ns. At 2,000 hits a second, the lock is held for 2,000 × 100 ns = 0.2 ms out of every second, 0.02% of the time. The chance that a hit finds the lock taken is about the same, and the wait when it does is about 100 ns. Contention only becomes noticeable as that fraction approaches tens of percent: at 100 ns per hit, that is millions of hits a second. We write the decision down: one mutex guards the whole store, because at our load it is held 0.02% of the time and it keeps every invariant in one place.

What does the lock protect?

The comment on mu is not decoration. A lock protects an invariant, a statement about the data that must hold whenever nobody is in the middle of changing it. For hitcount there are two. The total equals the sum of all pages’ views. And each page’s ReadMs and Reads describe the same set of reports, so that their ratio is a real average.

That second invariant is why atomics alone are not enough. Suppose we replaced the mutex with atomics, one per field, to avoid locking. A page has Reads = 1 and ReadMs = 45,000. A new report arrives. The handler atomically adds 45,000 to ReadMs; before it increments Reads, the stats page reads both fields and computes 90,000 ÷ 1, an average of 90 seconds that never existed. Each field was updated atomically; the pair was not. Atomic operations do not compose. The moment an invariant spans two values, it needs something that covers both, which is what the mutex does.

Readers need the lock too. /top reads Views while handlers write it. On 64-bit hardware an aligned 8-byte load will not see half of one value and half of another, but Go’s memory model makes no promise about a racy program at all: the compiler may keep a value in a register, reorder reads, or assume nothing else changes it. The race detector reports the read, and it is right to. Either /top takes the lock while it copies what it needs, or it reads from a separate copy that is never written.

A deadlock in the snapshot code

Locks fix races and introduce a failure of their own. hitcount version 2 has two locks. s.mu guards the store, as above. snapMu makes sure only one snapshot is written at a time. The snapshot loop takes snapMu, then s.mu to read the store. Later someone adds an admin endpoint to rename a page when a post’s URL changes. It takes s.mu, moves the entry to its new key, and then, still holding s.mu, calls the snapshot function so the rename is saved immediately. The snapshot function takes snapMu.

One afternoon the timing lines up. The snapshot loop takes snapMu and asks for s.mu. At the same moment, a rename has taken s.mu and asks for snapMu. Each goroutine holds what the other needs and waits for it. Neither will ever let go. Within milliseconds every incoming hit calls s.mu.Lock() and joins the wait. hitcount stops answering. Its CPU usage drops to zero, which is the signature of a deadlock rather than an overload.

Go does detect deadlocks, but only when every goroutine in the program is blocked. The HTTP server’s listening goroutine is waiting in the network poller, which does not count, so the runtime sees a healthy program. The fastest way to diagnose this in production is a goroutine dump (send SIGQUIT, or fetch /debug/pprof/goroutine): two goroutines blocked in Lock, each holding the lock the other wants, and two thousand more queued behind them.

A deadlock needs four conditions at once: exclusive locks, holding one lock while waiting for another, no way to take a lock away, and a cycle in who waits for whom. The practical fixes break the second or the fourth. One is a global order: every code path takes snapMu before s.mu, never the reverse, so no cycle can form. The better fix here is to stop holding locks while calling into other code. The rename now updates the map, releases s.mu, and then signals the snapshot loop on a channel. The snapshot loop, in turn, holds s.mu only while copying the counts, and writes the file after releasing it, so no lock is ever held during disk I/O.

That last change has a cost: the copy. For two thousand pages it is a few hundred kilobytes and tens of microseconds. For the platform’s 5 million pages it is hundreds of megabytes, and the performance chapter will show what happens when someone tries to avoid it.

A write another core may never see

Races are not only about lost updates. They are also about whether one goroutine’s write becomes visible to another at all. hitcount’s graceful shutdown shows how.

When the container is asked to stop, a signal handler should let the snapshot loop finish its current write and save one last time. The first attempt used a plain boolean:

var stopping bool // set by the signal handler, read by the snapshot loop

go func() {
    <-sigterm
    stopping = true
}()

for !stopping {
    s.snapshotIfDue()
}
s.snapshotNow()

Nothing in this code orders the write to stopping before the read in the loop. Go’s memory model, like those of C++, Java and Rust, says that without such an ordering the reading goroutine is not guaranteed to see the write, ever. In practice, two things can happen. The compiler, seeing no synchronisation inside the loop, may load stopping into a register once and test the register forever. And on processors with weaker ordering rules than x86, including the ARM chips in many cloud servers, writes from one core can become visible to another in a different order from the one the code wrote them in.

The unpleasant part is that this version usually works. With a function call in the loop body, the current compiler happens to reload the variable each time, and on an x86 laptop the ordering is strict enough to hide the problem. It fails after a compiler upgrade changes inlining, or after a move to ARM servers, and the symptom is a container that ignores its stop signal until it is killed, losing every count since the last snapshot.

The language defines a happens-before relation that does guarantee visibility. Unlocking a mutex happens before the next lock of it. A send on a channel happens before the matching receive completes, and closing a channel happens before a receive that sees it closed. An atomic store happens before an atomic load that observes it. Writes made before any of those events are visible after the matching event. So the fix is to communicate the stop through one of them: close a done channel and have the loop select on it, or use an atomic.Bool. The cost is nothing measurable. The rule that falls out is simple to state: if two goroutines share a variable and one writes it, every access needs a synchronising operation between them, even when the variable is a single boolean and no update can be “lost”.

Event loops: fewer interleavings, not none

The Node.js version of hitcount runs all JavaScript on one thread. While one handler runs, no other JavaScript runs, so counts.set(path, (counts.get(path) || 0) + 1) on an in-memory map is safe without a lock. Interleaving happens only where code waits, at each await, and between those points every handler has the data to itself.

Now the team runs four Node processes to use four cores, and moves the counts into Redis so the processes can share them:

app.post('/hit', async (req, res) => {
  const key = 'views:' + canonical(req.query.page)
  const v = await redis.get(key)       // other handlers run while we wait
  await redis.set(key, Number(v) + 1)  // ...and one of them may have written in between
  res.status(204).end()
})

This is the lost update again, now across processes and a network. Two handlers read 41, both write 42. The fix is to make the read-modify-write one operation on the server that owns the data: await redis.incr(key). Redis runs each command on its own single thread, so the increment is indivisible. The general lesson carries straight into the Distributed Systems pathway: an operation that reads, decides and writes is only safe when one owner performs all three.

Event loops have a failure of their own. Because one thread runs everything, a handler that computes for a long time stops every other handler. Building the platform-wide /top over 5 million pages in JavaScript would take on the order of a second, during which no hit is counted and no other request is answered. Heavy computation on an event loop belongs in a worker thread, another process, or a precomputed result.

When not to add a lock

Locks are for state that is shared and mutable. Data written once before any goroutine starts, such as configuration, needs no lock. Data owned by exactly one goroutine needs no lock. Immutable data can be shared freely, and that gives a useful pattern for readers: build a new top-ten list, then publish it by swapping a single pointer with an atomic store. Readers load the pointer and use whatever list it points to, which never changes after publication. Readers never wait; the cost is building a fresh copy for every update.

The habit to avoid is adding locks until the race detector goes quiet. Every lock added without knowing which invariant it guards is another candidate for a deadlock cycle. If you cannot say in one sentence what a lock protects, the design is not finished. Revisit hitcount’s single mutex if a mutex profile (the performance chapter shows how) reports real waiting on it, or if a hit ever needs to do slow work, such as I/O, that would have to happen while holding it.

So far every request began when bytes arrived on hitcount’s socket. The next chapter, One request across the network, starts further back, in a reader’s browser on another continent, and accounts for the 800 milliseconds that pass before the 40 microseconds of work in hit begin.