DEV Community

Duck
Duck

Posted on Edited on

4 concurrency bugs I found reviewing my own Go service

I've been practicing code review for Go, mostly on other people's code. At some point it felt a bit dishonest not to point the same checklist at my own. So I took prohealth-api, a hospital booking API I built in Go (Gin, PostgreSQL, Redis Streams), and read every goroutine in it with four questions in mind.

It has two pieces of background work: an outbox worker that moves events from Postgres to a Redis Stream, and a notification consumer that reads that stream through a consumer group. Plus the HTTP server, of course. Small service, not much concurrency. I still found four things to fix. All of them are in one commit.

The checklist

For every go statement:

  1. Who stops it? A context, a closed channel, the end of its input. If nothing stops it, it leaks.
  2. Who waits for it? If main returns, is anyone waiting, or is the work cut off halfway?
  3. What happens on error? Returned, retried with a delay, or retried in a tight loop?
  4. Are resources released? Tickers, timers, response bodies, rows.

Each bug below was found by one of these questions.

Bug 1: the HTTP server ignored shutdown

Who stops it?

main already used signal.NotifyContext, so SIGTERM cancelled a context and the background worker stopped. The server didn't:

ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()

go c.OutboxWorker.Run(ctx)
// ...
r.Run(":" + port)
Enter fullscreen mode Exit fullscreen mode

Gin's r.Run blocks until the process dies and never looks at ctx. So on a deploy, the worker shut down nicely while requests in flight were simply dropped when the process was killed.

The fix is to own the http.Server and call Shutdown yourself:

srv := &http.Server{Addr: ":" + port, Handler: r}
go func() {
    if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
        log.Fatal(err)
    }
}()

<-ctx.Done()
cancel() // a second Ctrl+C now kills the process
shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 15*time.Second)
defer cancelShutdown()
if err := srv.Shutdown(shutdownCtx); err != nil {
    log.Printf("server shutdown: %v", err)
}
Enter fullscreen mode Exit fullscreen mode

Shutdown stops accepting new connections and waits for active requests to finish, up to the timeout. Three details that are easy to get wrong:

  • ListenAndServe returns http.ErrServerClosed after Shutdown. That's the normal path, not an error, so it must not hit log.Fatal.
  • The timeout context is built from context.Background(), not from ctx. ctx is already cancelled at this point; deriving from it would give Shutdown zero time.
  • Call cancel() right after <-ctx.Done(). Until then NotifyContext keeps catching the signal, so a second Ctrl+C does nothing and a stuck Shutdown means waiting out the full timeout. Calling it restores the default handling, so a second Ctrl+C kills the process.

Bug 2: nobody waited for the workers

Who waits for it?

Even after bug 1, main started the worker with a bare go and returned as soon as the server was done. The consumer had the same shape inside its own Run:

func (c *NotificationConsumer) Run(ctx context.Context) {
    go c.recoverPendingMessages(ctx)
    c.consumeNewMessages(ctx)
}
Enter fullscreen mode Exit fullscreen mode

When Run returns, the reclaim loop may still be in the middle of handling a message. When main returns, everything dies wherever it is. For an outbox worker that means a job can be pushed to Redis but never marked as published.

A sync.WaitGroup is enough here:

func (c *NotificationConsumer) Run(ctx context.Context) {
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        c.recoverPendingMessages(ctx)
    }()
    c.consumeNewMessages(ctx)
    wg.Wait()
}
Enter fullscreen mode Exit fullscreen mode

And in main, the worker gets the same treatment, with workers.Wait() after srv.Shutdown.

wg.Add(1) goes before go, never inside the goroutine. If it's inside, Wait can run before Add and return immediately. I used a WaitGroup rather than errgroup because neither loop returns an error; they log and keep going. If they did return errors, errgroup.WithContext would be the better fit, since the first error would cancel the others.

Bug 3: a hot loop when Redis was down

What happens on error?

The consumer reads with XReadGroup and a 5 second block. redis.Nil just means nothing arrived, so that case loops. Every other error was logged at Info level and the loop tried again at once.

If Redis is down, the call fails instantly, so this becomes a busy loop: full CPU, and a log line per iteration. Exactly when you most want readable logs.

After the fix it backs off, and the wait still respects shutdown:

const (
    minReadBackoff = 500 * time.Millisecond
    maxReadBackoff = 30 * time.Second
)

// inside the loop
if err != nil {
    if errors.Is(err, redis.Nil) {
        continue
    }
    if ctx.Err() != nil {
        continue // shutting down: the select at the top of the loop returns
    }
    slog.Error("xreadgroup error", "err", err, "retry_in", backoff)
    select {
    case <-ctx.Done():
    case <-time.After(backoff):
    }
    backoff = min(backoff*2, maxReadBackoff)
    continue
}
backoff = minReadBackoff
Enter fullscreen mode Exit fullscreen mode

A few things that matter here:

  • The select on ctx.Done(). With a plain time.Sleep, a shutdown during a 30 second backoff would hang for up to 30 seconds.
  • Reset the backoff after a successful read, or one bad minute makes every later error wait 30 seconds.
  • errors.Is instead of ==, so a wrapped redis.Nil still matches.
  • time.After allocates a new timer on every call. In a hot path I'd reuse a time.Timer. Here it only runs on errors, so it's fine.

Bug 4: a ticker that was never stopped

Are resources released?

The outbox worker polls every five seconds:

ticker := time.NewTicker(5 * time.Second)
for {
    select {
    case <-ticker.C:
        w.process(ctx)
    case <-ctx.Done():
        return
    }
}
Enter fullscreen mode Exit fullscreen mode

There was no ticker.Stop(). The fix is one line: defer ticker.Stop().

I should be honest about how much this one matters. Before Go 1.23, a ticker that was never stopped stayed alive forever, which was a real leak. Since Go 1.23 the runtime can garbage-collect a ticker that nothing references anymore, even if Stop was never called. This project is on Go 1.25, so in practice it wasn't leaking.

I still added the defer. It states the intent, it's correct on older Go versions, and code like this tends to get copied into places where it's called many times. But I wouldn't call it a bug in a code review today without that caveat.

What I'd look at next

  • Running the tests with -race in CI. None of these bugs were data races, but the four questions don't find races; the race detector does.
  • The Redis lock used for booking has a TTL. If the work under the lock takes longer than the TTL, another instance can take it. Lease renewal or fencing tokens are the usual answers, and that's a post of its own.

Takeaway

None of this needed a profiler or a load test. Asking "who stops it, who waits for it, what happens on error, what gets released" for each goroutine found all four. The service is small, which is the point: these bugs show up in small services too, and they're cheap to fix before the first bad deploy or Redis outage.

The fixes are in this commit, and the code is on GitHub.

Top comments (3)

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

a runtime swallowing the first Ctrl+C turns a clean stop into a hang. nasty one to debug.

Collapse
 
kidkender profile image
Duck •

Yeah, and the code in the post has a version of that. Once NotifyContext has caught the signal, a second Ctrl+C does nothing, so if Shutdown hangs you're stuck until the 15s timeout. Calling cancel() right after <-ctx.Done() fixes it: it restores the default handling, so a second Ctrl+C kills the process straight away. I'll add that to the post.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

cancel() right after <-ctx.Done() is the fix. A 15s timeout as the only exit is what makes the hang nasty.