# Concurrency bugs: state that is both shared and mutable needs one owner

> A product has 10 items left, and 100 people click Buy at the same time. The system sells 100 items, every test passes, and wrapping the code in a transaction does not help. This article explains that concurrency bugs come from state that is shared and mutable, with no single owner that checks and writes in one step. It shows the fix in one process and in the database. It is part seven of the bug map series.

- URL: https://zero2scale.me/en/posts/concurrency-bugs
- Language: English
- Published: 2026-12-05
- Tags: fundamentals, bugs, static-analysis, go

The shop in phase 2 of this site has a purchase function that looks like this:

```go
type Store struct {
	mu    sync.Mutex
	stock int
	sold  int
}

// Buy is the buggy version
func (s *Store) Buy() bool {
	if s.stock > 0 { // check
		charge()
		s.stock-- // act: stock may no longer be greater than 0
		s.sold++
		return true
	}
	return false
}
```

A test buys 11 times from a stock of 10, then checks that it sold 10 and that the stock is 0.

```text
--- PASS: TestBuyStopsAtZero (0.01s)
```

Now let 100 goroutines buy at the same time, with `charge()` taking 1 ms like a call to a payment gateway. Here are three runs:

```text
buggy:       sold  97, stock  -87
buggy:       sold 100, stock  -90
buggy:       sold 100, stock  -90
```

Every line in the function is correct. It checks before it subtracts, and it subtracts one at a time. So why did it sell 90 items too many? This article is part seven of the series that started with [the bug map](/en/posts/a-map-of-software-bugs). The previous part covered [resource and memory bugs](/en/posts/resource-and-memory-bugs) and ended with stuck goroutines. This part covers group 5, concurrency, where goroutines start to fight over the same data.

## Each step is correct, but the interleaving is wrong

When the stock is 1, buyer A checks it, sees that it is greater than 0, and starts the charge. Meanwhile buyer B checks too and also sees 1, because A has not subtracted yet. Both charge the card and both subtract, so the stock becomes -1. Each goroutine is correct on its own. What is wrong is the order in which their statements mix together (the interleaving).

This kind of bug is a race condition. The result depends on who runs first. The most common shape is check-then-act: the value you checked may no longer be true when you act on it. In security, the same shape is called TOCTOU (time of check to time of use).

This bug has already moved real money. In 2015, Egor Homakov found that a balance transfer between Starbucks gift cards had two steps: save the transfer, then confirm it. He sent two confirmations at the same time for a $5 transfer from a card that held $5. The system made both transfers. The total on his cards went from $15 to $20, and he had added no money.

The short answer of this article is that a concurrency bug needs three things at once. The state is **shared**. The state is **mutable**. And there is no **single owner** that reads, decides and writes in one step. Remove any one of the three and the bug goes away:

1. **Do not share it.** Keep the state inside one goroutine or one request.
2. **Do not mutate it.** Build it once, then only read it.
3. **Give it one owner.** If the state must be shared and mutable, let one owner do the check and the write as one step that cannot be split (an atomic step). The owner can be a mutex, a goroutine that holds a channel, or a database.

This is the same idea as [the article on SSE and Datastar](/en/posts/server-sent-events-with-datastar), where the server is the only owner of state. That article looked at how many copies get out of sync. This one looks at what happens when many writers change the same copy at once.

## A data race and a race condition are not the same thing

If every sale subtracts one from `stock` and adds one to `sold`, then `sold + stock` must always be 10, however much the code oversells. But one run in a test gave `sold 54, stock -65`, which adds up to -11. Some additions and subtractions simply disappeared. The code oversells, and its counters are wrong as well.

The cause is that `s.stock--` is not one step. It reads the value, subtracts one, and writes the result back. If two goroutines read the same value at the same time, both write the same value back, and one subtraction is lost. *The Go Memory Model* calls this a data race: a write to a memory location at the same time as another goroutine reads or writes that location, without synchronization. It also warns that a race on data larger than one word, such as a slice or an interface, can produce inconsistent values and lead to memory corruption.

Go has a race detector that finds data races at run time:

```text
$ go test -race -run TestBuyConcurrent ./stock
==================
WARNING: DATA RACE
Write at 0x00c0001ae050 by goroutine 25:
  g5/stock.(*Store).Buy()
      .../stock/main.go:23 +0x7c

Previous read at 0x00c0001ae050 by goroutine 83:
  g5/stock.(*Store).Buy()
      .../stock/main.go:21 +0x38
```

Line 21 is `if s.stock > 0` and line 23 is `s.stock--`. The race detector points exactly at the check and the act.

Now try a common fix: lock both steps, but lock them separately.

```go
// BuyLockedTwice locks both steps, but separately
func (s *Store) BuyLockedTwice() bool {
	s.mu.Lock()
	ok := s.stock > 0
	s.mu.Unlock() // releases the lock between check and act
	if !ok {
		return false
	}
	charge()
	s.mu.Lock()
	s.stock--
	s.sold++
	s.mu.Unlock()
	return true
}
```

```text
$ go test -race -run TestBuyLockedTwiceConcurrent -v ./stock
=== RUN   TestBuyLockedTwiceConcurrent
    stock_test.go:38: sold 100, stock -90; want 10, 0
--- FAIL: TestBuyLockedTwiceConcurrent (0.00s)
```

There is no `WARNING: DATA RACE`. Every read and write happens under the lock, so the data race is gone. But the code still oversells by 90, because the lock is released between the check and the act. The race detector did not catch this bug. The line `if s.sold != 10 || s.stock != 0` in the test did.

This is the difference to remember. A data race is about memory. A race condition is about your business rules. The race detector knows about the first kind. It does not know that stock must never go below zero. Only a test that checks your own invariant knows that.

Uber has about 46 million lines of Go code and 2,100 microservices. When it deployed the race detector across the company, it found more than 2,000 data races and fixed more than 1,000 of them, in 790 patches from 210 developers over six months. The results are in a paper at PLDI 2022. These numbers count only data races. They do not include race conditions like `BuyLockedTwice`, which the tool cannot see.

## A mutex makes check and act one step, but only in one process

In one process, the fix is to put the check and the reservation under the same lock, then charge the card outside the lock.

```go
// BuyFixed checks and reserves in one step under the lock, then charges outside it
func (s *Store) BuyFixed() bool {
	s.mu.Lock()
	if s.stock == 0 {
		s.mu.Unlock()
		return false
	}
	s.stock-- // reserve first, so anyone who comes later sees the new value
	s.sold++
	s.mu.Unlock()
	charge() // if the charge fails, give the stock back (see the article on errors)
	return true
}
```

```text
fixed:       sold  10, stock    0
--- PASS: TestBuyFixedConcurrent (0.00s)
```

A piece of code that must run without anyone else in between is a critical section. Keep it as short as possible. Putting `charge()` under the lock would also be correct, but every buyer would then wait in line through the payment gateway one at a time. Reserving first and charging later keeps the lock short. You must then decide how to return the stock if the charge fails. That is the "half-finished work must be undoable" rule from [the article on error handling](/en/posts/error-handling-bugs).

The remaining problem is that production does not run one process. z2s-web-app itself runs two replicas (`replicas: 2` in `deploy/prod-deployment-template.yaml`). A mutex in each pod locks only that pod's memory. Two buyers sent to different pods never see each other's lock.

## With many processes, the owner must be the database

When the state lives in a database, the same bug looks like this. The code reads the stock, decides in Go, and writes back the value it computed.

```go
// buyBuggy reads the stock, decides in Go, and writes back the computed value
func buyBuggy(ctx context.Context, db *pgxpool.Pool) error {
	var stock int
	if err := db.QueryRow(ctx, `SELECT stock FROM products WHERE id = 1`).Scan(&stock); err != nil {
		return err
	}
	if stock <= 0 { // checks a value that may already be stale
		return nil
	}
	time.Sleep(time.Millisecond) // charge the card
	if _, err := db.Exec(ctx, `UPDATE products SET stock = $1 WHERE id = 1`, stock-1); err != nil { // overwrites other buyers' writes
		return err
	}
	_, err := db.Exec(ctx, `INSERT INTO orders (product_id) VALUES (1)`)
	return err
}
```

I ran it against PostgreSQL 18.6 with 100 goroutines and a pool of 20 connections, and compared four versions. The first is the code above. The second is the same code inside a transaction. The third adds `FOR UPDATE` to the `SELECT` in that transaction. The fourth lets the database check and subtract in one statement.

```text
buggy:     orders 100, stock 9
tx:        orders  99, stock 3
tx:        orders 100, stock 1
forupdate: orders  10, stock 0
fixed:     orders  10, stock 0
```

The first version created 100 orders, but the stock went down by only one. Every request read 10 and wrote 9, over and over. This bug is called a lost update: one writer's change is overwritten by another writer's change.

The second version shows the most common misunderstanding. A transaction does not make the code inside it run one caller at a time. PostgreSQL's default isolation level is Read Committed. Each statement sees the data that was committed when the statement started. Two transactions can therefore read the same stock value and overwrite each other as before.

The third version locks the row when it reads it. The PostgreSQL manual says that `FOR UPDATE` locks the rows that the `SELECT` returns as though for an update. Other transactions that try to lock, modify or delete those rows must wait. The check and the write become one step again.

The fourth version uses one statement:

```go
tag, err := tx.Exec(ctx, `UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock > 0`)
if err != nil {
	return err
}
if tag.RowsAffected() == 0 { // sold out: no row matched the condition
	return nil
}
```

The check (`stock > 0`) is in the `WHERE` clause of the statement that writes. In Read Committed, if the `UPDATE` finds a row that another transaction is changing, it waits for that transaction to commit or roll back. It then evaluates the `WHERE` clause again against the newest version of the row. The database is the single owner that checks and subtracts in one step. This version is the shortest and holds its lock for the shortest time. Use `FOR UPDATE` when the decision is too complex for a `WHERE` clause and you need Go code between the read and the write.

Recall [the article on Functional Core, Imperative Shell](/en/posts/functional-core-imperative-shell). The fourth version means that part of the rule "never sell more than the stock" must live in the shell's SQL statement. A pure function in the core can decide from the data it receives. It cannot know whether the data in the database changed while it was deciding.

## Not sharing, or not mutating, is the easiest path

The best lock is the one you do not need. z2s-web-app reads every article at startup and builds a `content.Site` once. ARCHITECTURE.md says that the `*Site` is built once at startup and shared read-only by every request, so there are no locks. Every request can read `Site` at the same time without conflict, because nobody writes to it. The pure functions in `internal/core` have no shared state to fight over in the first place.

The values from `fiber.Ctx` are an example of not sharing. They are valid only inside the handler, and [the Opengrep article](/en/posts/opengrep-in-the-age-of-agents) shows a rule that catches them when they are passed to another goroutine. The language uses the same approach to remove bugs. Since Go 1.22, each iteration of a `for` loop creates new variables. Goroutines started in different iterations no longer share the loop variable.

This repository has one piece of state that is both shared and mutable: the contact form limiter, which allows 5 submissions per IP address every 10 minutes (`internal/shell/web/contact.go`). The limiter in Fiber v3.7.0 keeps its counters in memory by default. The comment in `config.go` says it is "an in memory store for this process only". With two replicas, each pod counts on its own. One client may send up to 10 messages if its requests reach both pods, and the counters reset on every deploy. For spam control, this error is acceptable. For a quota that involves money, or for product stock, the counter must move to an owner that every pod shares, such as Valkey. The limiter already supports that through `Storage`.

## Deadlock: two owners that wait for each other

When one operation needs two owners, a new problem appears. An example is a transfer between two accounts, where each account has its own lock.

```go
// Transfer is the buggy version: it locks in the order the arguments arrive
func Transfer(from, to *Account, amount int64) {
	from.mu.Lock()
	defer from.mu.Unlock()
	time.Sleep(time.Millisecond) // other work while holding the lock
	to.mu.Lock() // another goroutine holds this lock and waits for ours
	defer to.mu.Unlock()
	from.balance -= amount
	to.balance += amount
}
```

If a transfer from a to b and a transfer from b to a run at the same time, the first goroutine holds a's lock and waits for b. The second holds b's lock and waits for a.

```text
stuck after 2s: both transfers are waiting for each other
```

The fix is a lock order that every caller uses. For example, always lock the account with the smaller ID first, whichever way the money moves.

```go
// TransferOrdered always locks the smaller ID first, whichever way the money moves
func TransferOrdered(from, to *Account, amount int64) {
	first, second := from, to
	if to.ID < from.ID {
		first, second = to, from
	}
	first.mu.Lock()
	defer first.mu.Unlock()
	time.Sleep(time.Millisecond)
	second.mu.Lock()
	defer second.mu.Unlock()
	from.balance -= amount
	to.balance += amount
}
```

```text
done: a = 90000 b = 110000
```

The Go runtime has a built-in deadlock detector, but it reports only when every goroutine in the program is blocked:

```text
fatal error: all goroutines are asleep - deadlock!
```

In the `Transfer` example above, the main goroutine still waits on a timer, so the detector stays silent. A real server is the same. It always has a goroutine waiting for connections. A deadlock in a server does not crash it. It makes the affected requests hang without a sound.

Tu and colleagues studied 171 concurrency bugs from six Go programs, including Docker, Kubernetes and gRPC, in a paper at ASPLOS 2019. 85 were blocking bugs, where goroutines get stuck. 86 were non-blocking bugs, which give wrong results without getting stuck. Go's built-in deadlock detector caught only 2 of 21 reproduced blocking bugs. The race detector caught 10 of 20 reproduced non-blocking bugs within 100 runs. Another finding: about 58% of the blocking bugs came from message passing, not shared memory. Switching from a mutex to a channel therefore does not remove this group of bugs. It moves the owner to the goroutine that holds the channel, which must still answer the same question: who waits for whom?

The database helps more here. PostgreSQL detects deadlocks itself and aborts one transaction in the cycle. The manual recommends the same fix as above: every program should lock multiple rows in the same order.

## Tools find data races, but not your business rules

| Bug | Tool | Caught? |
|---|---|---|
| A data race, such as `s.stock--` from many goroutines | `go test -race` | yes, only in code that tests run |
| Concurrent writes to one map | the runtime | yes, the program crashes at once |
| Copying a struct that contains a `sync.Mutex` | `go vet` (copylocks) | yes, at lint time |
| Check-then-act with two separate locks | none | no, it needs a test that checks the invariant |
| A lost update in the database | none | no, it needs a test against a real database |
| A deadlock in a server | the runtime's built-in detector | almost never |

The race detector finds only races that happen at run time. The Go documentation says it cannot find races in code paths that are not executed. For a typical program, it increases memory use by 5-10x and execution time by 2-20x. It suits tests better than production.

The second row is good news in Go. Maps are not safe for concurrent writes, and the runtime stops the program as soon as it detects one. Here is a view counter written like this:

```go
var views = map[string]int{}

func countView(slug string) {
	views[slug]++ // many requests write to the same map at the same time
}
```

Called from 1,000 goroutines, it gave the same result in all three runs:

```text
fatal error: concurrent map writes
```

`go vet` catches a copied mutex, which locks the copy instead of the real value:

```go
// Inc takes Counter by value, so it locks the copy's mutex, not the real one
func (c Counter) Inc() {
	c.mu.Lock()
	c.n++
	c.mu.Unlock()
}
```

```text
copylock/main.go:14:9: Inc passes lock by value: g5/copylock.Counter contains sync.Mutex
```

Every example in this article ran with Go 1.27.4 and PostgreSQL 18.6.

What about this repository? `mise run test` runs `go test ./...` without `-race`. I ran `go test -race -count=1 ./...`, and every package passed. That result says little. No test calls `t.Parallel()`, and only the tests in `internal/shell/mail` use goroutines. Every handler is tested one request at a time, so the race detector has no chance to see anything.

A test that really catches this group of bugs has three parts. It calls the code from many goroutines at once, it checks your own invariant, and it runs with `-race`. The `TestBuyConcurrent` example above is less than ten lines long, and it catches both the data race and the race condition.

## Agents write tests one request at a time

Agents write code that works when called once, and tests that call it once. Concurrency bugs never show themselves under those conditions. A prompt like "add a view counter" often returns a map like `views` above. A prompt like "fix the race" often returns a lock around only the line that the race detector pointed at, which is `BuyLockedTwice`. The race detector goes quiet, but the bug stays. A prompt like "wrap it in a transaction to make it safe" often returns the `tx` version, which still oversells.

When you read a diff that an agent wrote, as [the article on reading code](/en/posts/reading-code) suggests, ask three questions:

1. Who else writes this state, and can they write at the same time? With several replicas, do they all see the same state?
2. Is anything between the check and the write, such as a released lock, a network call or another query?
3. Which test calls this code concurrently, and which invariant does it check?

## A table to keep

| Bug | Why it happens | Why tests miss it | What helps |
|---|---|---|---|
| Check-then-act | The checked value changes before the act | Tests call the code once at a time | Check and write in one step under one owner |
| Data race | `x++` is read, compute and write | The race depends on timing | A mutex, `sync/atomic`, `go test -race` |
| Two separate locks | The lock is released between check and act | The race detector stays silent | One lock around both check and act, a test that checks the invariant |
| Lost update | The code computes in Go and overwrites | Tests use a fake database or call once at a time | `UPDATE ... WHERE stock > 0`, `SELECT ... FOR UPDATE` |
| Trusting a transaction to fix it | Read Committed does not serialize callers | It fails only under concurrent calls | Let the database check, or lock the row |
| State split across replicas | Each pod has its own mutex and memory | Dev runs one process | Move the state to an owner that every pod shares |
| Deadlock | Two owners wait for each other | The colliding order is rare | Always lock in the same order |
| Concurrent map writes | Maps are not safe for concurrent writes | Tests call the code once at a time | A mutex around the map, or no shared map |

## What to do differently

Every time you see state that lives longer than one request, ask two questions. Is it shared? Is it mutable? If both answers are yes, name the single owner that does the check and the write as one step, and check that every replica sees that owner. If the state does not need to be shared or mutable, choose that path first. It is simpler than any lock. And every piece of code that can run concurrently should have at least one test that really calls it concurrently.

The next article in this series covers group 6, security. In that group, the person who sends the input is an adversary, and the TOCTOU from this article becomes a vulnerability.

## References

- [Hacking Starbucks for unlimited coffee](https://sakurity.com/blog/2015/05/21/starbucks.html) (Egor Homakov, Sakurity blog, 2015): a race condition in gift card balance transfers that turned $15 into $20.
- [The Go Memory Model](https://go.dev/ref/mem) (Go documentation, 2022): the definition of a data race, and the effect of races on multiword data.
- [A Study of Real-World Data Races in Golang](https://arxiv.org/abs/2204.00764) (Chabbi, Ramanathan, PLDI 2022): the data races found and fixed in Uber's Go codebase.
- [Understanding Real-World Concurrency Bugs in Go](https://doi.org/10.1145/3297858.3304069) (Tu, Liu, Song, Zhang, ASPLOS 2019): 171 bugs, the share caused by message passing, and the results of the deadlock detector and the race detector.
- [Data Race Detector](https://go.dev/doc/articles/race_detector) (Go documentation): the race detector finds only races that happen at run time, and its overhead.
- [PostgreSQL: Transaction Isolation](https://www.postgresql.org/docs/current/transaction-iso.html) (PostgreSQL documentation): Read Committed is the default, and `UPDATE` evaluates `WHERE` again after waiting for a changed row.
- [PostgreSQL: Explicit Locking](https://www.postgresql.org/docs/current/explicit-locking.html) (PostgreSQL documentation): `FOR UPDATE`, deadlock detection, and locking in a consistent order.
- [Go 1.22 Release Notes](https://go.dev/doc/go1.22): each iteration of a `for` loop creates new variables.
- [fiber/middleware/limiter/config.go](https://github.com/gofiber/fiber/blob/main/middleware/limiter/config.go) (Fiber v3): the default `Storage` is memory in a single process.
