Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
105: Whiteboard Practice: Concurrency Puzzles in Go
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.WithTimeoutof 500ms to bound the entire operation. - Uses a buffered channel or a
sync.WaitGroupwith aselectblock 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.
There are no comments for now.