Skip to Content
Course content

105: Whiteboard Practice: Concurrency Puzzles in Go

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When you're sitting in a technical interview or staring at a production bug involving concurrency, the temptation is always to reach for the simplest pattern: spin up a goroutine, send a result over a channel, and move on. It feels intuitive. But in Go, the "intuitive" way is often how you accidentally create a memory leak that doesn't show up until your server has been running for three days and suddenly hits an OOM (Out of Memory) crash.

Let's look at a classic whiteboard puzzle: the "First-Response Wins" pattern. Imagine you have three different API mirrors providing the same piece of data. To minimize latency, you want to query all three simultaneously and return the result from whichever one responds first. The other two responses? You don't care about them.

The "Fire and Forget" Trap

A naive implementation usually looks something like this. You create an unbuffered channel, launch three goroutines, and wait for the first value to hit that channel.

func getFirstResponse(urls []string) string {
    ch := make(chan string)
    for _, url := range urls {
        go func(u string) {
            res := fetch(u) // Assume this is a slow network call
            ch <- res
        }(url)
    }
    return <-ch // Return the first one that arrives
}

On the surface, this works. It's fast. It's concise. If you run this in a test suite with a few iterations, it passes every time. But there is a silent killer hiding in those goroutines.

Where the Memory Leak Hides

Here is the problem: we used an unbuffered channel. In Go, sending to an unbuffered channel blocks until there is a receiver. We have three goroutines trying to send a result, but the main function returns as soon as the first result is received. That means the other two goroutines are now blocked forever, waiting for a receiver that will never come.

They aren't just "stopped"; they are leaked. Their stacks stay in memory, and any resources they held (like open HTTP connections) remain open. I've seen this exact pattern bring down production clusters because the developers assumed "the garbage collector will handle it." It won't. The GC cannot collect a goroutine that is blocked on a channel send.

Closing the Loop with Context and Buffering

To fix this, we need a way to tell the losing goroutines to pack up and go home. The professional way to handle this is a combination of a buffered channel—to ensure a send can happen even if no one is listening—and a context.Context to signal cancellation.

func getFirstResponse(ctx context.Context, urls []string) string {
    // Buffer the channel so senders don't block even if we stop listening
    ch := make(chan string, len(urls))
    
    // Create a derived context that we can cancel manually
    ctx, cancel := context.WithCancel(ctx)
    defer cancel() // Ensure all goroutines are signaled to stop when we return

    for _, url := range urls {
        go func(u string) {
            // We pass the context down to the fetch function
            res, err := fetchWithContext(ctx, u) 
            if err == nil {
                ch <- res
            }
        }(url)
    }

    select {
    case res := <-ch:
        return res
    case <-ctx.Done():
        return "" // Handle timeout or external cancellation
    }
}

Notice the trade-offs here. We've added a bit more boilerplate, but we've gained absolute control over the lifecycle of our concurrency. By buffering the channel to the size of our request list, we guarantee that even if the main function returns, any late-arriving results can be placed in the buffer and then discarded when the channel is garbage collected. More importantly, by using context.WithCancel, we can tell the fetchWithContext function to abort the underlying HTTP request immediately, saving bandwidth and CPU on both our end and the server's end.

When you're writing concurrent Go, always ask yourself: "What happens to this goroutine if the main function returns early?" If the answer is "it waits forever," you have a bug.




📋 Practical Task

The Leak-Proof Asset Aggregator

You are building a system that fetches metadata for a user profile from three different internal microservices (Profile, Preferences, and Social). The goal is to aggregate these three pieces of data into a single object. However, if any one of these services takes longer than 500ms, you should return the partial data you've collected so far rather than making the user wait.

Your Task: Implement a function AggregateUserData(userID string) UserProfile that:

  • Launches three concurrent requests to the mock services.
  • Uses a context.WithTimeout of 500ms to bound the entire operation.
  • Uses a buffered channel or a sync.WaitGroup with a select block to collect results.
  • Ensures that no goroutines are leaked, regardless of whether the timeout is hit or all requests succeed.

Constraints: You must prove that your solution handles the "slow service" scenario without leaving orphaned goroutines in the background.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.