Background refresh with atomic.Pointer

Use a context-owned ticker to rebuild the index, then publish each immutable snapshot with atomic.Pointer so list requests can read it without a data race.

Learning outcomes

  • Give every background goroutine an owner and a cancellation path using context.Context.
  • Run periodic refreshes with time.Ticker and a select loop.
  • Identify the data race caused by sharing a plain pointer between the refresher and HTTP handlers.
  • Publish immutable snapshots with atomic.Pointer so each request uses one consistent snapshot.
  • Preserve the last successful snapshot when a refresh fails and perform an initial load before the first ticker event.
Prerequisite conceptsBitsetData race

The open-hours index from the previous lesson is an in-memory snapshot. When an open_slots record changes, the restaurant list keeps using the old opening hours until you rebuild the index.

You need a background refresh that loads the latest slots and builds a replacement without blocking HTTP handlers. Readers must keep using a complete snapshot while the next one is being prepared. A failed refresh must not discard the last working index.

Goroutine ownership

A background refresher needs a clear owner and a way to stop. The application starts it, and application shutdown requests that it exit.

This is the Goroutine lifecycle: every goroutine you start should have an owner responsible for its lifetime and an explicit cancellation path.

A Go context.Context provides a cancellation signal through its Done channel. Calling the associated cancel function closes that channel, but it does not forcibly terminate the goroutine.

go
ctx, cancel := context.WithCancel(context.Background())
go openHours.Run(ctx, refreshInterval())

// When the application shuts down:
cancel()

The goroutine must observe ctx.Done() and return. Code that performs blocking operations should also pass the context into those operations so cancellation can reach them.

For the open-hours refresher, cancellation should interrupt the waiting loop and allow the goroutine to exit. The application owns the context, so the refresh loop does not need to decide when the server shuts down.

Configurable refresh intervals

The API reads HOURS_REFRESH_INTERVAL from the environment. Its value is a Go duration, such as 2s. The default is 1m.

Read and parse this setting before starting the refresher:

go
func refreshInterval() time.Duration {
    const fallback = time.Minute

    value := os.Getenv("HOURS_REFRESH_INTERVAL")
    if value == "" {
        return fallback
    }

    every, err := time.ParseDuration(value)
    if err != nil || every <= 0 {
        slog.Warn("invalid HOURS_REFRESH_INTERVAL; using default",
            "value", value)
        return fallback
    }
    return every
}

The result controls how often the background goroutine attempts to rebuild the open-hours index. The end-to-end tests set a short interval so they can observe changes without waiting for the production default.

A shorter interval makes opening-hours changes visible sooner, but it also increases database activity. The exercise expects changes to become visible within three configured refresh intervals.

Tickers and periodic work

A time.Ticker sends a time value on its channel at regular intervals. Create one with time.NewTicker:

go
ticker := time.NewTicker(every)
defer ticker.Stop()

The duration must be positive. time.NewTicker panics if you pass zero or a negative duration, so validate the configuration before starting the loop.

The first tick arrives after one full interval, not immediately. With HOURS_REFRESH_INTERVAL=2s, the first tick arrives approximately two seconds after the ticker is created.

This matters during application startup. You cannot rely on the ticker to provide the initial index. The API must attempt one rebuild before starting the periodic refresh loop.

A ticker maintains a periodic schedule independently of how long the previous operation takes. If a receiver is slow, ticker events can be dropped rather than accumulating an unlimited backlog. That is useful for the open-hours index. Replaying several missed refresh events would not make the resulting snapshot more accurate.

Stop the ticker when its owning goroutine exits. The deferred call runs whether the loop exits because of cancellation or another return path. It makes the ticker's lifetime match the goroutine's lifetime.

The refresh loop

The refresher waits for one of two events: a cancellation signal or a ticker event. A select handles both without polling the clock or consuming CPU while waiting.

go
func (h *Holder) Run(ctx context.Context, every time.Duration) {
    if every <= 0 {
        every = time.Minute
    }
    ticker := time.NewTicker(every)
    defer ticker.Stop()

    for {
        select {
        case <-ctx.Done():
            return
        case <-ticker.C:
            if err := h.Rebuild(ctx); err != nil {
                slog.Error("open hours rebuild", "err", err)
            }
        }
    }
}

There are several important details.

First, the goroutine blocks inside select until a tick or cancellation arrives. It does not repeatedly check the clock in a tight loop.

Second, Rebuild runs in the background goroutine. HTTP handlers can continue reading the currently published index while the refresher loads slots from MySQL and builds a replacement.

Third, a failed refresh is logged. The loop does not terminate on an ordinary rebuild error. A later tick can attempt another refresh.

Finally, cancellation causes Run to return. The deferred ticker.Stop() then stops future ticker events.

The loop handles one rebuild at a time. It does not start another goroutine for every tick, so two refresh operations do not overlap.

The shared pointer problem

The background goroutine needs to publish a new index. HTTP handlers need to read the current index.

A plain pointer might appear sufficient:

go
type Holder struct {
    current *Index
}

The refresher could replace it after building the new index:

go
h.current = Build(slots)

A request handler could read it:

go
index := h.current

The problem is that these operations can happen concurrently. One goroutine might write h.current while another reads it.

That is a Data race. In Go, unsynchronized concurrent access to the same memory location, where at least one access is a write, creates a data race. The fact that a pointer assignment looks like one operation does not make concurrent access safe.

Run the race detector while developing concurrent code:

bash
go test -race ./...

The race detector instruments executed code and reports conflicting accesses that occur during a test run. Its report identifies the goroutines and memory locations involved.

A clean run is useful evidence, not proof that every execution is race-free. The detector can only report races on code paths exercised by the tests.

You have two common ways to protect this shared state:

  • A sync.RWMutex lets writers replace the pointer under a write lock and readers access the protected value under a read lock.
  • An atomic.Pointer[T] lets goroutines load and replace a pointer safely.

A mutex is useful when readers and writers need to coordinate changes to mutable state. Here, the index is a complete snapshot. The refresher constructs a replacement separately, so an atomic pointer is a natural fit.

Atomic pointer publication

An atomic.Pointer provides safe concurrent pointer loads and stores. It lets the refresher publish a completed index without requiring handlers to acquire a mutex.

The holder can store its current index using atomic.Pointer[Index]:

go
type Holder struct {
    current atomic.Pointer[Index]
    load    func(context.Context) ([]Slot, error)
}

func (h *Holder) Current() *Index {
    return h.current.Load()
}

The zero value of atomic.Pointer[Index] contains a nil pointer. Therefore, Current() returns nil until the first successful rebuild.

The holder's rebuild operation loads the source slots, constructs a complete replacement and publishes it:

go
func (h *Holder) Rebuild(ctx context.Context) error {
    slots, err := h.load(ctx)
    if err != nil {
        return err
    }

    next := Build(slots)
    h.current.Store(next)
    return nil
}

Notice the order. The replacement is fully built before Store publishes it. Readers continue using the old pointer while the new index is being constructed.

The store changes which snapshot future readers can obtain. It does not modify the previous snapshot.

Snapshot consistency

The previous lesson established that an Index contains the restaurant ID mapping and the per-minute bitsets. Treat the entire Bitset index as immutable after construction.

Imagine a request loads snapshot A just before a refresh publishes snapshot B. The request keeps its pointer to A and can finish using it. A later request loads the holder and obtains B.

The first request does not switch to B halfway through its calculation. Publishing B changes the holder's pointer, not the value of A.

A refresh goroutine builds snapshot B separately while request handlers continue reading snapshot A. One atomic store publishes B. New requests load B, while an existing request finishes using A.A refresh goroutine builds snapshot B separately while request handlers continue reading snapshot A. One atomic store publishes B. New requests load B, while an existing request finishes using A.

This pattern is commonly called copy-on-write. Instead of modifying an object that readers are already using, the writer creates a new object and publishes it after construction succeeds.

An atomic operation also provides memory-ordering guarantees. The writes used to construct the new index happen before the Store. A Load that observes that stored pointer also observes the fully initialized snapshot.

The Go memory model defines the synchronization rules behind atomic operations. You do not need to add a separate lock around the pointer to make this publication safe.

Load the pointer once per request and keep it in a local variable:

go
index := holder.Current()
if index != nil {
    openIDs := index.OpenAt(localNow)
    // Use this snapshot for the rest of the request.
}

Calling Current() repeatedly could return different snapshots if a refresh happens between calls. One local pointer gives the request a consistent view for its entire calculation.

Failed refreshes

A refresh can fail because MySQL is unavailable, a query times out, or the loading function returns an error.

The important rule is that a failed refresh must not replace the existing snapshot.

Look at the order inside Rebuild:

go
slots, err := h.load(ctx)
if err != nil {
    return err
}

next := Build(slots)
h.current.Store(next)

If loading fails, execution returns before Store. The holder retains the last successfully published index.

This is preferable to replacing a working snapshot with nil or incomplete data. The snapshot may be stale, but requests can continue using it. A later successful refresh replaces it.

There are two distinct states:

  • Before the first successful rebuild, Current() returns nil.
  • After a successful rebuild, a later failure leaves the previous snapshot available.

Initial loading

The API should attempt an initial rebuild during startup. Give that database operation a timeout so an unavailable database cannot block startup indefinitely.

go
buildCtx, buildCancel := context.WithTimeout(
    context.Background(), 5*time.Second,
)
if err := openHours.Rebuild(buildCtx); err != nil {
    slog.Warn("open hours index not built at startup",
        "error", err)
}
buildCancel()

The API continues starting even if this initial load fails. It logs the failure instead of terminating the process.

Until the first successful load, every restaurant's is_open is false. The holder is still nil, so the restaurant service has no snapshot from which to calculate open status.

After the initial attempt, start the background refresh loop:

go
backgroundCtx, stopBackground :=
    context.WithCancel(context.Background())
defer stopBackground()

go openHours.Run(backgroundCtx, refreshInterval())

If startup loading failed, the next ticker event triggers another rebuild. When that rebuild succeeds, the holder publishes the first snapshot and subsequent requests can calculate is_open from it.

If the initial load succeeded, the same loop keeps the snapshot current.

The index already contains opening status for every minute of the day. A refresh does not control when a restaurant changes from open to closed. Each request evaluates the current local minute against the existing index. The refresh only updates the index when the underlying opening-hours records change.

Service integration

The restaurant service needs access to the holder and the Asia/Kolkata location. It does not own the refresh loop. Its responsibility is to read the published snapshot and populate is_open.

For each listing request, the service loads the pointer once. If the pointer is non-nil, it evaluates the request's time in Asia/Kolkata against that snapshot and sets the status for each restaurant.

If the pointer is nil, the service leaves every restaurant's is_open value false. It does not block a listing request while waiting for the initial refresh.

The responsibilities remain separate:

  • The holder owns the current snapshot and rebuild operation.
  • The background goroutine owns the periodic refresh loop.
  • The restaurant service reads one snapshot and calculates each restaurant's status.
  • Application startup owns the context and cancellation function.

This separation keeps database loading outside the restaurant list request path.

Shutdown and goroutine ownership

The application creates the refresh context and owns its cancellation function. When shutdown begins, cancellation tells the refresh goroutine to stop.

There is an important distinction between requesting cancellation and waiting for completion. Calling stopBackground() closes the context's Done channel. It does not prove that the goroutine has returned.

A graceful shutdown sequence should account for both operations:

  1. Stop accepting new HTTP requests and allow in-flight requests to finish.
  2. Cancel the background refresh context.
  3. Wait for owned background goroutines to return before closing resources they may still use.

A sync.WaitGroup or another completion mechanism can coordinate that wait. Cancel background work before closing the database or other resources that the goroutine may still need. Week 3 applies the same lifecycle principles to workers that must finish their in-flight work before the process exits.

The restaurant list refresh

The GET /v1/restaurants: open status exercise connects the loader, holder and background refresh loop to the restaurant list.

The restaurant service must use a consistent snapshot for each request. Changed opening-hours records must become visible within three configured refresh intervals, and a failed refresh must preserve the last successful snapshot.

The tests also run the API with the race detector. Pay attention to the difference between safely publishing a pointer and safely using the object it points to. The snapshot must remain immutable after publication.

Check your understanding

Question 1 of 4

The API starts with HOURS_REFRESH_INTERVAL=2s. The ticker has been created, but no initial rebuild has happened. What is the main risk?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (Go 1.25, time, sync/atomic, context).

Finished Lesson 2.16?