Mutexes and time: making a limiter safe and testable

Why a map shared by many requests needs a lock, how sync.Mutex protects it, how the time package measures elapsed time, and why a limiter takes its clock as a function so tests can control time.

Learning outcomes

  • Explain why concurrent map access is unsafe and how sync.Mutex makes a critical section.
  • Lock and unlock with defer, and keep the critical section small.
  • Use time.Time, time.Duration, Sub, Add and Truncate.
  • Inject the clock as a func() time.Time, default it to time.Now, and write a fake clock for tests.
  • Say why the check and the update of a limiter must happen under one lock.

Why shared state needs protection

The rate limiter from the previous lesson keeps track of how many requests each client has made. A natural implementation is a Go map:

go
buckets := make(map[string]*bucket)

Each key identifies a client, and each value stores that client's current rate-limiting state.

The problem is that an HTTP server handles incoming requests concurrently. Each request is served independently, and requests can execute at the same time. Two requests from the same user might therefore try to read and update the same map entry simultaneously.

A Go map is not safe for concurrent reads and writes without synchronization. If one request updates a map while another accesses it, the program can encounter a data race or a fatal concurrent map access error.

We need a way to ensure that only one request at a time modifies the shared limiter state.

Mutexes and critical sections

A mutex is a mutual exclusion lock. It allows one execution path to enter a protected section of code at a time.

Go provides sync.Mutex in the standard library.

A mutex has two main operations:

  • Lock() acquires the lock. If another execution path already holds it, the caller waits until the lock becomes available.
  • Unlock() releases the lock so another execution path can acquire it.

The code between acquiring and releasing a lock is commonly called a critical section. It is a section of code that accesses shared state and must not be executed concurrently by multiple callers.

Here is a small example:

go
package main

import (
	"fmt"
	"sync"
)

type Counter struct {
	mu    sync.Mutex
	value int
}

func (c *Counter) Increment() {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.value++
}

func (c *Counter) Value() int {
	c.mu.Lock()
	defer c.mu.Unlock()

	return c.value
}

func main() {
	counter := &Counter{}

	counter.Increment()
	counter.Increment()

	fmt.Println(counter.Value())
}

The counter protects its shared integer with a mutex. Both Increment and Value acquire the same lock before accessing it.

Why defer Unlock?

Notice this pattern:

go
c.mu.Lock()
defer c.mu.Unlock()

defer schedules the unlock operation to run when the function returns.

This is safer than manually placing Unlock() at the end of every possible execution path. If the function later gains an early return, the deferred unlock still runs.

For example:

go
func (c *Counter) IncrementIfPositive(amount int) bool {
	c.mu.Lock()
	defer c.mu.Unlock()

	if amount <= 0 {
		return false
	}

	c.value += amount
	return true
}

Without defer, an early return could accidentally leave the mutex locked. Future callers would wait indefinitely.

A mutex must be unlocked by the execution path that acquired it. Do not call Unlock without a matching successful Lock.

Keep the critical section small

A lock prevents other callers from accessing the protected state until it is released. Holding it for too long reduces concurrency.

For a rate limiter, the critical section should contain the operations that must be consistent:

  • Find or create the bucket for a key.
  • Read its current state.
  • Calculate the updated state.
  • Decide whether the request is allowed.
  • Save the updated state.

Avoid unrelated work while holding the lock. Do not perform network requests, wait for external services or do expensive processing inside the critical section.

A limiter should make its admission decision quickly and release the lock before the HTTP handler performs the actual business operation.

The check-then-act race

A common mistake is to protect the update but not the check that determines whether the update is permitted.

Suppose a bucket has one token remaining. Two requests arrive for the same key.

An unsafe implementation might do this:

  1. Read the token count.
  2. Check whether at least one token exists.
  3. Subtract one token.

If two requests execute these steps at the same time, both can read tokens = 1. Both conclude that a token is available. Both are admitted, even though only one token existed.

This is called a check-then-act race. The decision depends on a value that can change between checking it and acting on it.

The check and the update must happen under the same lock. The lock makes the entire decision one protected operation.

Show two requests for the same key reading a bucket with one token at the same time and both being allowed without a lock, then show the requests serialized by a mutex so the first consumes the token and the second is rejected.Show two requests for the same key reading a bucket with one token at the same time and both being allowed without a lock, then show the requests serialized by a mutex so the first consumes the token and the second is rejected.

A mutex is part of the struct's identity

A struct containing a mutex should not be copied after it has started being used.

Consider:

go
type Counter struct {
	mu    sync.Mutex
	value int
}

If you copy a Counter, you copy its mutex value too. The original and copied structs then have separate mutex values, even though developers may expect them to protect the same underlying data.

That can break the synchronization design.

For this reason, structs containing mutexes should generally be used through pointers. Their methods should use pointer receivers.

go
func (c *Counter) Increment() {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.value++
}

The receiver is *Counter, not Counter. This means the method operates on the original struct rather than a copy.

Go's go vet includes a check called copylocks. It can report code that copies values containing synchronization primitives such as mutexes.

You should take these warnings seriously. Do not silence them by copying a mutex-containing struct intentionally.

The zero value is ready to use

Unlike some types that require explicit initialization, the zero value of sync.Mutex is ready for use.

This is valid:

go
var mu sync.Mutex

mu.Lock()
mu.Unlock()

You do not need a constructor for a mutex itself.

A containing struct can therefore initialize its ordinary fields while leaving the mutex at its zero value.

What about RWMutex?

Go also provides sync.RWMutex, a read-write mutex.

It supports multiple simultaneous readers or one exclusive writer. Its operations include:

  • RLock() and RUnlock() for readers.
  • Lock() and Unlock() for writers.

This can help when a data structure has many reads and relatively few writes. However, it introduces additional complexity and is not automatically faster.

For the rate limiter, a plain sync.Mutex is the right default. Every request that updates a bucket needs exclusive access, and the critical section is short. Start with a simple mutex unless measurement shows that read concurrency is a real bottleneck.

Working with time in Go

Rate limiters depend on elapsed time. A token bucket refills based on how much time has passed, while a fixed window needs to identify the beginning of the current interval.

Go's time package provides the types and functions needed for these calculations.

Two types are especially important:

  • time.Time represents a point in time.
  • time.Duration represents a length of time.

A duration is stored as an integer number of nanoseconds, but Go provides constants that make duration expressions readable.

go
package main

import (
	"fmt"
	"time"
)

func main() {
	var interval time.Duration = 30 * time.Second

	fmt.Println(interval)
	fmt.Println(2 * time.Minute)
	fmt.Println(500 * time.Millisecond)
}

Common duration constants include:

ConstantMeaning
time.NanosecondOne nanosecond
time.MicrosecondOne microsecond
time.MillisecondOne millisecond
time.SecondOne second
time.MinuteOne minute
time.HourOne hour

These constants are useful for expressing limits and timeouts without manually converting units.

Getting the current time

Use time.Now() to obtain the current time:

go
now := time.Now()

The result is a time.Time value.

You can add a duration to a time:

go
expiresAt := now.Add(30 * time.Second)

You can subtract one time from another to obtain a duration:

go
elapsed := time.Now().Sub(now)

The same calculation can be written more concisely with time.Since:

go
elapsed := time.Since(now)

time.Since(t) is effectively the elapsed duration since t. When t comes from time.Now(), Go can use its monotonic clock reading to make elapsed-time calculations more reliable.

A monotonic clock measures elapsed time independently of changes to the system's wall clock. For example, if the system clock is adjusted by time synchronization, a monotonic reading is not moved backwards by that adjustment.

This distinction matters for rate limiters. We care about how much time has elapsed, not just what the calendar clock says.

Seconds and floating-point calculations

The Seconds() method converts a duration into a floating-point number of seconds:

go
elapsedSeconds := elapsed.Seconds()

A token bucket commonly uses a floating-point token count and refill rate.

For example, if a bucket refills at 2.5 tokens per second and 0.4 seconds have elapsed:

[ 0.4 \times 2.5 = 1 ]

One token has become available.

Floating-point tokens allow fractional refill. The limiter does not need to wait until a whole second has passed before adding a token.

An alternative is to represent tokens as integers and calculate refill using smaller units or scaled integer arithmetic. That can avoid floating-point rounding, but it requires more careful arithmetic and unit handling.

For the Week 1 implementation, use float64 tokens and a float64 refill rate. Be consistent about units: if the refill rate is tokens per second, multiply it by elapsed seconds.

Lazy refill with elapsed time

Recall the token bucket from lesson 1.9. It has a capacity, a refill rate and a current token count.

A bucket needs to remember the time at which its state was last updated. In Go, the relevant structure is:

go
type bucket struct {
	tokens float64
	last   time.Time
}

When a request arrives, the limiter calculates how many tokens should have been added since last.

The calculation is:

[ \text{elapsed} = \text{now} - \text{last} ]

[ \text{tokens} = \min(\text{capacity}, \text{tokens} + \text{elapsed seconds} \times \text{refill rate}) ]

After calculating the updated token count, the limiter records the current time as the new last.

This is lazy refill. No background timer is needed. The bucket is updated only when a request arrives.

Why clamp negative elapsed time?

In normal operation, the current time should be later than the previous update. However, code should not blindly assume that elapsed time is always positive.

A clock can move backwards because of clock adjustments, an injected test clock being set incorrectly, or a different time source that does not preserve monotonic behavior.

If elapsed time is negative, the refill calculation could subtract tokens instead of adding them.

A defensive implementation clamps negative elapsed time to zero:

go
elapsed := now.Sub(b.last)
if elapsed < 0 {
	elapsed = 0
}

This prevents a backwards clock movement from reducing the bucket's token count.

When both time values originate from time.Now(), Go can preserve monotonic readings during subtraction. But monotonic readings are not available in every time.Time value. For example, serialized timestamps and manually constructed times do not carry the same monotonic clock information.

The clamp is a useful defensive measure regardless.

Fixed windows and Truncate

A fixed-window limiter needs to identify which time interval contains a request.

Suppose the configured window size is one minute. A request at 12:34:27 belongs to the window beginning at 12:34:00.

Go's Time.Truncate method rounds a time down to a multiple of a duration, measured relative to Go's zero time.

go
windowStart := now.Truncate(time.Minute)

For a time such as 12:34:27, this produces 12:34:00.

You can use other durations too:

go
windowStart := now.Truncate(10 * time.Second)

This identifies the start of the ten-second interval containing the current time.

Truncate is relative to the zero time

Truncate does not mean "round down within the current hour" or "start counting from midnight today." It calculates the result relative to Go's zero time, which is January 1, year 1, at midnight UTC.

For common whole-second, minute and hour windows, this gives the expected boundaries.

For custom calendar periods, such as a local business day or a month, Truncate is not a replacement for explicit calendar calculations. A month is not a fixed duration, and local time zones can have daylight-saving transitions.

For the course's fixed-window limiter, use a duration such as one minute or ten seconds.

Injecting the clock

There is one problem with calling time.Now() directly throughout the limiter: the code becomes difficult to test deterministically.

Suppose you want to verify that a bucket refills after exactly two seconds. A test that depends on the real clock must wait for those two seconds to pass. It can also become flaky if the test machine is slow.

A better design is to make the clock a dependency.

An injected clock is a function supplied to an object that tells it the current time. Instead of calling time.Now() directly, the limiter calls its own now function.

The field has this type:

go
now func() time.Time

Production code passes time.Now. A test can pass a closure that returns a time value controlled by the test.

A closure is a function value that can access variables from the surrounding scope.

The production constructor

The token bucket constructor should accept the clock as an argument:

go
func NewTokenBucket(
	capacity int,
	refillPerSec float64,
	now func() time.Time,
) *TokenBucket

If the caller passes nil, the constructor can default the clock to time.Now.

This keeps the limiter convenient to use in production while allowing deterministic time control in tests.

The corresponding limiter structure has these fields:

go
type TokenBucket struct {
	mu           sync.Mutex
	buckets      map[string]*bucket
	capacity     float64
	refillPerSec float64
	now          func() time.Time
}

The mutex protects the map and the bucket state. The capacity and refill rate are configuration values. The clock function is the source of time for all limiter calculations.

The constructor should create the map and set the clock. It should not create a separate clock for each request.

A fake clock as a closure

A test can use a variable outside the closure and advance it whenever necessary:

go
package main

import (
	"fmt"
	"time"
)

func main() {
	current := time.Date(2026, time.January, 1, 12, 0, 0, 0, time.UTC)

	fakeNow := func() time.Time {
		return current
	}

	fmt.Println(fakeNow())

	current = current.Add(2 * time.Second)

	fmt.Println(fakeNow())
}

The closure returns the current value of current. Updating the variable changes what the closure returns.

A limiter using this clock does not know whether the time is real or simulated. It simply calls its now field.

This is the key design rule: the limiter should never call time.Now() directly after construction. It should always use the injected clock.

Show production code passing time.Now to the limiter, a test passing a closure over a variable it advances, and both paths reaching the limiter through its now field without the limiter calling time.Now directly.Show production code passing time.Now to the limiter, a test passing a closure over a variable it advances, and both paths reaching the limiter through its now field without the limiter calling time.Now directly.

Putting the token bucket together

The following pieces show the structure and the important decisions that the token bucket implementation must make. The exercise asks you to assemble them into a complete limiter.

Start with the bucket state:

go
type bucket struct {
	tokens float64
	last   time.Time
}

The limiter owns one bucket per key:

go
type TokenBucket struct {
	mu           sync.Mutex
	buckets      map[string]*bucket
	capacity     float64
	refillPerSec float64
	now          func() time.Time
}

Its constructor has the following signature:

go
func NewTokenBucket(
	capacity int,
	refillPerSec float64,
	now func() time.Time,
) *TokenBucket

The constructor should:

  1. Convert the capacity to float64.
  2. Create the bucket map.
  3. Use time.Now if the supplied clock is nil.
  4. Store the refill rate and clock.

The public method is:

go
func (tb *TokenBucket) Allow(key string) bool

Its logic should follow this sequence.

Step 1: Acquire the lock

The map and the buckets it contains are shared state. Acquire the mutex before reading or modifying them.

go
tb.mu.Lock()
defer tb.mu.Unlock()

The entire admission decision must happen while this lock is held.

Step 2: Read the injected clock

Get the current time from the configured clock:

go
now := tb.now()

Do not call time.Now() directly here. Using the field keeps production and test behavior consistent.

Step 3: Find or create the bucket

Look up the bucket using the request key.

If it does not exist, create a bucket with the full configured capacity and set its last update time to now.

A new client starts with a full bucket, so it can make an initial burst up to the configured capacity.

Step 4: Refill

For an existing bucket, calculate elapsed time:

go
elapsed := now.Sub(b.last)
if elapsed < 0 {
	elapsed = 0
}

Then calculate the available tokens:

go
tokens := b.tokens + elapsed.Seconds()*tb.refillPerSec
if tokens > tb.capacity {
	tokens = tb.capacity
}

The result must never exceed the configured capacity.

Step 5: Make the admission decision

If fewer than one token is available, the request is rejected. Save the refilled token count and the current update time before returning.

If at least one token is available, subtract one token and admit the request.

The check and token consumption must remain inside the same critical section. Otherwise, two requests could both consume the same available token.

The exercise will ask you to implement the complete method and verify the behavior with deterministic time.

The fixed-window structure

The fixed-window limiter needs different state. It tracks a request count and the start of the current window.

A suitable entry is:

go
type window struct {
	count int
	start time.Time
}

The limiter structure is:

go
type FixedWindow struct {
	mu      sync.Mutex
	windows map[string]*window
	limit   int
	size    time.Duration
	now     func() time.Time
}

Its constructor should have this signature:

go
func NewFixedWindow(
	limit int,
	size time.Duration,
	now func() time.Time,
) *FixedWindow

As with the token bucket, the constructor initializes the map and defaults a nil clock to time.Now.

The method is:

go
func (fw *FixedWindow) Allow(key string) bool

Its decision process is:

  1. Acquire the mutex.
  2. Read the current time from fw.now().
  3. Calculate the window start using now.Truncate(fw.size).
  4. Find or create the entry for the key.
  5. If the stored window start differs from the current window start, reset its count.
  6. Reject the request if the count has reached the limit.
  7. Otherwise, increment the count and admit the request.

The reset, check and increment must all happen while holding the same mutex. If the count check and increment are separate operations, concurrent requests can exceed the limit.

These structures and method signatures are the shapes exercises 1.11 and 1.14 ask you to build. They are not complete implementations. You should assemble the logic, handle invalid configuration according to the exercise requirements and verify the behavior with the supplied tests.

A note about per-key memory

Both limiter designs store state in a map keyed by client identity.

That map grows as new keys arrive. If a service receives traffic from millions of distinct keys, retaining every bucket forever can consume significant memory.

A production limiter needs a strategy for evicting idle entries. For example, it might periodically remove buckets that have not been used for a configured period.

Eviction introduces additional design decisions, including how to coordinate cleanup with request processing. It is an optional extension, not a requirement for the first implementation.

Common mistakes

Knowledge assessment

Question 1 of 4

A token bucket checks whether at least one token remains and then decrements the token count. Why must both operations happen under the same mutex?

Pick an answer, then say how sure you are.

Practical applications

  • Exercise 1.11: Build the token bucket with a mutex, per-key bucket state, lazy refill and an injected clock.
  • Exercise 1.14: Build the fixed-window limiter with a mutex, per-key counters, time.Truncate and an injected clock.
  • Exercise 1.15: Test both algorithms using a fake clock that advances without time.Sleep.

References

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

Finished Lesson 1.10?