Goroutines, WaitGroup and the race detector

Start concurrent work with goroutines, wait for it with sync.WaitGroup, and find unsynchronised access with go test -race. This is how you prove a limiter is safe under load.

Learning outcomes

  • Start a goroutine with go and explain why main does not wait for it.
  • Use sync.WaitGroup (Add, Done, Wait) to wait for a batch of goroutines.
  • Explain what a data race is with a counter example, and fix it with a mutex.
  • Run go test -race and read a race report.
  • Write a test that hammers a limiter from many goroutines and checks the total allowed.
Prerequisite conceptsMutexGo testing

Why concurrency matters in a backend

A backend receives requests from many clients at nearly the same time. Even if your server has one process, multiple requests can be handled concurrently. One request might be checking a rate limit while another is updating the same user's request count.

Go makes concurrent work straightforward. You can start independent tasks without creating and managing operating-system threads yourself. But concurrent execution introduces a new responsibility: shared data must be accessed safely.

In this lesson, you will learn how to start concurrent work, wait for it to finish, recognise a data race, and use Go's race detector to find unsafe access to shared memory. We will keep the examples close to the rate limiter you have been building.

By the end, you should understand why the Allow method of a token bucket needs a mutex when multiple requests can call it concurrently.

Starting concurrent work with goroutines

A Goroutines is a function executing independently within a Go program. You start one using the go keyword before a function call.

Consider this program:

go
package main

import (
	"fmt"
	"time"
)

func greet() {
	fmt.Println("Hello from the goroutine")
}

func main() {
	go greet()
	fmt.Println("Hello from main")
	time.Sleep(100 * time.Millisecond)
}

The statement go greet() starts greet as a separate goroutine. The main function continues without waiting for greet to finish.

You might see either message first. The Go scheduler decides when goroutines run, and you should not assume a particular execution order.

Why main does not wait automatically

Every Go program starts with a main goroutine, which executes the main function. When main returns, the program exits. Go does not automatically wait for other goroutines to finish.

For example:

go
package main

import "fmt"

func work() {
	fmt.Println("work finished")
}

func main() {
	go work()
	fmt.Println("main finished")
}

This program may print only main finished. The main goroutine can return before the newly started goroutine gets a chance to print.

The important distinction is that starting a goroutine does not mean the work has completed. It only schedules the work for execution.

The previous example used time.Sleep to give the goroutine time to run. That is useful for demonstrating the problem, but it is not a correct way to coordinate concurrent work.

A sleep does not tell you whether the goroutine finished. It only delays the current goroutine for a duration. If the delay is too short, the work may not finish. If it is too long, the program wastes time.

Use an explicit synchronisation mechanism when one goroutine must wait for another.

Goroutines are cheap, but not free

Goroutines are lighter than operating-system threads. Go starts them with relatively small stacks that can grow as needed, and its runtime schedules them onto available operating-system threads.

That makes it practical to handle many concurrent operations. However, each goroutine still consumes memory and runtime resources. Starting thousands of unnecessary goroutines can increase memory use and scheduling overhead.

Do not create a goroutine for every tiny operation without considering how much work it performs and how many can exist simultaneously.

Waiting for a group of goroutines

A WaitGroup is a synchronisation primitive from Go's sync package. It lets one goroutine wait until a group of other goroutines has completed.

A WaitGroup maintains a counter:

  • Add(n) increases the counter by n.
  • Done() decreases the counter by one.
  • Wait() blocks until the counter reaches zero.

Here is a complete example:

go
package main

import (
	"fmt"
	"sync"
)

func process(id int, wg *sync.WaitGroup) {
	defer wg.Done()

	fmt.Printf("worker %d finished\n", id)
}

func main() {
	var wg sync.WaitGroup

	wg.Add(3)

	for i := 1; i <= 3; i++ {
		go process(i, &wg)
	}

	wg.Wait()
	fmt.Println("all workers finished")
}

The main goroutine calls Add(3) before starting the workers. Each worker calls Done() when it finishes. The call to Wait() blocks until all three workers have called Done().

The defer wg.Done() statement is important. It schedules Done to run when the worker function returns, including when it returns through an early return statement.

The correct order: Add, start, Done, Wait

The safe pattern is:

  1. Call Add before starting the goroutines.
  2. Start the goroutines with go.
  3. Call Done exactly once for each unit added.
  4. Call Wait when the caller needs to wait for the group.

Calling Add before starting the goroutines ensures the counter is updated before a worker can finish and call Done.

Avoid this pattern:

go
go func() {
	wg.Add(1)
	defer wg.Done()
	doWork()
}()
wg.Wait()

The main goroutine can reach Wait before the worker calls Add. The counter may still be zero, so Wait can return immediately. The work then continues after the caller believes it has finished.

Instead, move Add before the go statement:

go
wg.Add(1)
go func() {
	defer wg.Done()
	doWork()
}()
wg.Wait()

Here, doWork represents any function you want to execute concurrently.

Understanding the WaitGroup lifecycle

Show main calling Add(3), then starting three goroutines; show each goroutine calling Done once, the WaitGroup counter decreasing from 3 to 0, and Wait unblocking only when the counter reaches zero.Show main calling Add(3), then starting three goroutines; show each goroutine calling Done once, the WaitGroup counter decreasing from 3 to 0, and Wait unblocking only when the counter reaches zero.

What happens when Done is missing?

Every Add(1) must eventually be matched by one Done().

If a worker returns without calling Done, the counter never reaches zero. The caller remains blocked inside Wait.

A common mistake is forgetting Done entirely:

go
package main

import "sync"

func main() {
	var wg sync.WaitGroup

	wg.Add(1)

	go func() {
		doWork()
	}()

	wg.Wait()
}

This program hangs because the counter remains at one.

If the runtime determines that every goroutine is blocked and no goroutine can make progress, it reports a deadlock:

fatal error: all goroutines are asleep - deadlock!

The message does not necessarily mean you have a literal circular dependency. A missing Done is one common cause.

Do not copy a WaitGroup

A WaitGroup must not be copied after it has started being used. The same rule applies to mutexes, which you learned about in the previous lesson.

Pass a pointer when sharing a WaitGroup with workers:

go
func worker(wg *sync.WaitGroup) {
	defer wg.Done()
}

Go's go vet includes checks for copying synchronisation values such as mutexes and WaitGroups. Running it helps catch mistakes that are difficult to diagnose from ordinary test output.

Go 1.25 also provides WaitGroup.Go, which starts a function as a goroutine and tracks its completion. It is useful to know that newer API exists, but this course teaches the explicit Add, Done, and Wait pattern because it makes the lifecycle and counter visible.

Data races: when concurrent access becomes unsafe

A data race happens when all of these conditions are true:

  • Two goroutines access the same memory location.
  • At least one of those accesses is a write.
  • No synchronisation orders those accesses.

The problem is not simply that two goroutines run at the same time. Concurrent reads of the same value are safe when nobody is writing to it. The problem occurs when concurrent access includes a write without appropriate synchronisation.

Consider a shared counter:

go
package main

import (
	"fmt"
	"sync"
)

func main() {
	counter := 0

	var wg sync.WaitGroup
	wg.Add(2)

	for i := 0; i < 2; i++ {
		go func() {
			defer wg.Done()
			counter++
		}()
	}

	wg.Wait()
	fmt.Println(counter)
}

You might expect the result to be 2. However, counter++ is not one indivisible operation. It involves reading the current value, adding one, and writing the result.

Both goroutines can read the same value before either writes its update.

How an update gets lost

Suppose the counter starts at 5.

Show a horizontal timeline with two goroutines: both read counter = 5, both calculate 6, and both write 6; highlight that the final value is 6 rather than the expected 7 because one increment was lost.Show a horizontal timeline with two goroutines: both read counter = 5, both calculate 6, and both write 6; highlight that the final value is 6 rather than the expected 7 because one increment was lost.

This is a lost update. Both goroutines performed an increment operation, but the final value reflects only one increment.

The program is incorrect even if it sometimes prints 2. A particular execution producing the expected result does not make an unsynchronised program safe.

The Go memory model defines how operations performed by different goroutines are ordered and observed. Without a valid synchronisation relationship, you cannot rely on the order in which concurrent reads and writes happen.

Fixing shared access with a mutex

A mutex provides mutual exclusion. It ensures that only one goroutine at a time can execute a protected critical section.

A critical section is the part of a program that accesses shared state and must not overlap with another such access.

The sync.Mutex type provides two main methods:

  • Lock() acquires the lock. If another goroutine already holds it, the caller waits.
  • Unlock() releases the lock, allowing another waiting goroutine to acquire it.

Here is the corrected counter:

go
package main

import (
	"fmt"
	"sync"
)

func main() {
	counter := 0

	var mu sync.Mutex
	var wg sync.WaitGroup

	wg.Add(2)

	for i := 0; i < 2; i++ {
		go func() {
			defer wg.Done()

			mu.Lock()
			counter++
			mu.Unlock()
		}()
	}

	wg.Wait()
	fmt.Println(counter)
}

The increment is now protected by the mutex. One goroutine must finish its critical section before another can enter it.

A more robust version uses defer to release the lock:

go
package main

import (
	"fmt"
	"sync"
)

func increment(mu *sync.Mutex, counter *int, wg *sync.WaitGroup) {
	defer wg.Done()

	mu.Lock()
	defer mu.Unlock()

	*counter++
}

func main() {
	counter := 0

	var mu sync.Mutex
	var wg sync.WaitGroup

	wg.Add(2)

	for i := 0; i < 2; i++ {
		go increment(&mu, &counter, &wg)
	}

	wg.Wait()
	fmt.Println(counter)
}

The expression *counter++ increments the value pointed to by counter. It is equivalent to (*counter)++.

Using defer mu.Unlock() makes it harder to accidentally leave the lock held when a function returns early. Keep the locked section small, because other goroutines cannot enter it until the lock is released.

Why this matters for maps

A Go map is not safe for concurrent writes. If multiple goroutines write to the same map without synchronisation, the runtime can terminate the program with a fatal error such as:

fatal error: concurrent map writes

A mutex-protected map prevents this by ensuring that only one goroutine at a time modifies the map.

For a rate limiter, the map might store token bucket state for each user:

go
type Limiter struct {
	mu      sync.Mutex
	buckets map[string]*Bucket
}

If multiple HTTP requests call Allow at the same time, they may try to find, create, or update entries in buckets. Protecting the map and the mutable bucket state with the same mutex is one way to make those operations safe.

The exact lock scope depends on the implementation. The important rule is that every concurrent access to shared mutable state must follow the same synchronisation strategy.

A note about atomics

Go also provides atomic operations in the sync/atomic package. Atomics can safely perform certain operations on shared values without using a mutex.

They are useful for simple counters and flags, but they do not automatically make a group of related operations atomic. For example, updating a map entry and checking another field together usually needs a mutex or a more carefully designed synchronisation strategy.

For the rate limiter in this course, use a mutex. It makes the relationship between the shared state and the protected operations easier to understand.

Finding races with the race detector

Go includes a race detector that instruments your program to identify data races during execution.

You enable it with the -race flag.

Run your tests with:

bash
go test -race ./...

Run an executable with:

bash
go run -race .

The detector observes memory accesses while the program executes. If it finds conflicting accesses without appropriate synchronisation, it prints a race report.

Reading a race report

A simplified report looks like this:

WARNING: DATA RACE
Write at 0x00c0000120a0 by goroutine 8:
  main.main.func1()
      /app/main.go:18 +0x...

Previous write at 0x00c0000120a0 by goroutine 7:
  main.main.func1()
      /app/main.go:18 +0x...

The report gives you two important stacks:

  • Write at identifies one conflicting memory access and the goroutine that performed it.
  • Previous write at identifies the earlier conflicting access and its goroutine.

A report can also show Read at when one access is a read and the other is a write.

The stack trace points to the code that performed the access. Read both stacks and work backwards to identify which shared variable is being accessed and why the accesses are not synchronised.

The detector may report additional information about where the goroutines were created. That helps connect the conflicting operations to the code that started the concurrent work.

What the race detector cannot prove

The detector only finds races that actually execute.

Suppose a test starts two goroutines, but their execution happens to avoid the unsafe access pattern. The detector may report nothing. That does not prove the program has no races.

You must exercise the code paths and concurrency patterns that could expose unsafe access.

The race detector also has a cost. It can slow tests by several times and use substantially more memory. It is valuable during development and in CI, but it is not a substitute for understanding and designing correct synchronisation.

Testing concurrent rate limiter access

A rate limiter is a useful place to apply these ideas. Its Allow method can be called by many HTTP request handlers at the same time.

Imagine a simple limiter with a fixed capacity and no refill. It allows a request while fewer than capacity requests have been admitted.

Here is a deliberately simple implementation for the example:

go
package ratelimit

type SimpleLimiter struct {
	capacity int
	allowed  int
}

func NewSimpleLimiter(capacity int) *SimpleLimiter {
	return &SimpleLimiter{
		capacity: capacity,
	}
}

func (l *SimpleLimiter) Allow() bool {
	if l.allowed >= l.capacity {
		return false
	}

	l.allowed++
	return true
}

This implementation is intentionally unsafe. It has no mutex protecting allowed.

Now consider a test that starts eight goroutines, each making one thousand calls:

go
package ratelimit

import (
	"sync"
	"sync/atomic"
	"testing"
)

func TestSimpleLimiterConcurrent(t *testing.T) {
	limiter := NewSimpleLimiter(100)

	var wg sync.WaitGroup
	var allowed atomic.Int64

	for i := 0; i < 8; i++ {
		wg.Add(1)

		go func() {
			defer wg.Done()

			for j := 0; j < 1000; j++ {
				if limiter.Allow() {
					allowed.Add(1)
				}
			}
		}()
	}

	wg.Wait()

	if got := allowed.Load(); got != 100 {
		t.Fatalf("allowed = %d, want 100", got)
	}
}

The test uses an atomic counter to collect the number of successful calls. This keeps the test's own result collection safe, independently of whether the limiter is safe.

The limiter itself is the subject under test. Because its allowed field is not protected, multiple goroutines can read and update it concurrently. The test may observe an incorrect total, and the race detector should report conflicting accesses to that field.

Fixing the limiter

The implementation needs a mutex around the check and increment. Both operations must be protected together because they form one logical decision.

go
package ratelimit

import "sync"

type SimpleLimiter struct {
	mu       sync.Mutex
	capacity int
	allowed  int
}

func NewSimpleLimiter(capacity int) *SimpleLimiter {
	return &SimpleLimiter{
		capacity: capacity,
	}
}

func (l *SimpleLimiter) Allow() bool {
	l.mu.Lock()
	defer l.mu.Unlock()

	if l.allowed >= l.capacity {
		return false
	}

	l.allowed++
	return true
}

Now the check and increment happen while holding the same lock. No two goroutines can simultaneously observe the same available capacity and both consume it.

Run the test with the race detector:

bash
go test -race ./internal/ratelimit

The test should pass, and the detector should not report a race in this limiter.

Why the test checks an exact total

The important invariant is that a limiter with capacity 100 and zero refill allows exactly 100 calls, regardless of how many goroutines make requests.

An invariant is a condition that must remain true throughout correct execution. Here, the total number of successful admissions cannot exceed the capacity, and after all 8,000 attempts finish, it must equal 100.

Do not write a concurrent test that expects goroutine 1 to finish before goroutine 2, or that expects successful calls in a particular order. The scheduler is not deterministic. The test should verify the result that must be true for every valid execution.

The provided TestW1B4_TokenBucketConcurrent uses this same principle: eight goroutines each make 1,000 calls against a token bucket with capacity 100 and zero refill, and the test expects exactly 100 successful calls.

That test is useful because an implementation without correct synchronisation can lose updates or admit too many requests. Running it with -race helps detect the underlying unsafe memory accesses, while the exact-count assertion checks the limiter's behaviour.

Loop variables and collecting results

When starting goroutines inside a loop, pay attention to loop variable capture.

In Go 1.22 and later, loop variables declared by a for loop using := have per-iteration semantics. This makes the following pattern safe from the classic loop-variable capture problem:

go
package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup

	for i := 0; i < 3; i++ {
		wg.Add(1)

		go func() {
			defer wg.Done()
			fmt.Println(i)
		}()
	}

	wg.Wait()
}

Each iteration has its own i because the loop declares it with :=.

If you assign to a variable declared outside the loop, or work with older language versions, you must be more careful. A common explicit approach is to pass the value as an argument:

go
for i := 0; i < 3; i++ {
	wg.Add(1)

	go func(id int) {
		defer wg.Done()
		fmt.Println(id)
	}(i)
}

This makes the value each goroutine receives explicit.

When multiple goroutines need to collect results into a shared slice or map, protect those writes with a mutex or use a channel. A channel is a Go mechanism for communication and synchronisation between goroutines. It can be useful when workers send results to one receiving goroutine, but we will not use channels as the primary coordination mechanism in this lesson.

Output from concurrent goroutines is not ordered

When multiple goroutines print to standard output, their output can appear in an unexpected order. If they print multiple values or lines, the output may interleave.

For example, you cannot rely on this:

worker 1 started
worker 1 finished
worker 2 started
worker 2 finished

A valid execution might print worker 2's messages before worker 1's, or interleave messages from both workers.

This is another consequence of nondeterministic scheduling. If output order matters, coordinate the work explicitly. Do not make tests depend on incidental print order.

Connecting concurrency to the token bucket

In lesson 1.10, you learned that a token bucket stores mutable state such as its current token count and the time at which it was last refilled.

The Allow method typically performs several related steps:

  1. Read the current time.
  2. Calculate elapsed time since the previous refill.
  3. Add the tokens earned during that interval.
  4. Update the last refill time.
  5. Check whether at least one token is available.
  6. Consume a token if the request is allowed.

Those steps must be treated as one protected state transition when multiple goroutines can call Allow on the same limiter instance.

If two requests check the available token count at the same time, both might believe a token is available. Without synchronisation, both could consume what should have been a single token.

The mutex protects the entire state transition, not just one individual field assignment.

This is why concurrency correctness is part of the rate limiter's behaviour. A limiter that returns correct results in a single-threaded test can still be incorrect when used by a real HTTP server.

Common mistakes to avoid

Calling Add inside the goroutine

The caller may reach Wait before the counter is incremented. Always call Add before starting the goroutine.

Forgetting Done

A missing Done leaves the WaitGroup counter above zero and can cause Wait to block forever. Put defer wg.Done() near the beginning of the worker function.

Assuming goroutines run in a particular order

The scheduler does not guarantee an execution order. Test invariants and final results, not timing or ordering.

Protecting only part of a shared operation

Checking a counter and then incrementing it must happen under the same lock. Protecting only the increment still allows multiple goroutines to make decisions based on the same old value.

Assuming a passing test proves race freedom

A race may not occur in every execution. Run tests with -race, exercise concurrent paths, and inspect any reports.

Holding a mutex longer than necessary

A goroutine waiting for a lock cannot enter the protected section. Keep critical sections short and avoid unrelated work while holding the lock.

Knowledge assessment

Question 1 of 4

What happens if main returns while another goroutine is still executing?

Pick an answer, then say how sure you are.

Practical applications

  • Exercise 1.14: Fixed window limiter. You will protect the fixed-window state with a mutex so concurrent requests cannot corrupt its count or admit more requests than the configured limit.
  • Exercise 1.15: Concurrent race test. You will write tests that exercise shared limiter state from multiple goroutines and verify correctness without assuming a particular execution order.
  • Provided TestW1B4_TokenBucketConcurrent. This test starts eight goroutines, each making 1,000 calls, and verifies that exactly 100 requests are allowed by a token bucket with capacity 100 and zero refill.
  • Week 1 verification. You will run the race detector with go test -race to check the concurrent code paths in the rate limiter.

References

Everything above is explained on this page; these are where it comes from (Go 1.2x).

Finished Lesson 1.13?