Prev Next

Golang / GoLang Concurrency Mastery Interview Questions

Summarise: channel vs mutex decision guide, and the top concurrency pitfalls.

This summary covers the most tested concurrency patterns and pitfalls in Go technical interviews.

Channel vs Mutex — Decision Guide
ScenarioRecommended Tool
Passing data ownership between goroutinesChannel
Signalling an event / broadcastingChannel (close for broadcast)
Parallel pipeline of transformationsDirectional channels
Limiting concurrency (semaphore)Buffered channel or golang.org/x/sync/semaphore
Protecting a shared countersync/atomic or sync.Mutex
Protecting a shared map or structsync.Mutex or sync.RWMutex
One-time initialisationsync.Once
Wait for a group of goroutinessync.WaitGroup or errgroup
Read-heavy shared statesync.RWMutex or sync.Map
Request cancellation / deadlinescontext.Context
Top 10 Concurrency Pitfalls
PitfallSymptomFix
Goroutine leakNumGoroutine grows indefinitelyPass context; close channels; use goleak
Data raceInconsistent output; rare crashesRun -race; mutex/atomic/channels
Deadlock'all goroutines asleep'Consistent lock order; context timeouts
Nil interface error trapif err != nil passes on nil *TReturn bare nil, not (*T)(nil)
Loop variable captureAll goroutines print same valuePass as arg; use Go 1.22+ range
Mutex copied by valueBroken synchronisation silentlyAlways use *T containing mutex
time.After leak in loopGoroutine/timer accumulationUse NewTimer+Stop; prefer context
Send on closed channelpanic: send on closed channelOnly sender closes; done pattern
Lock held during I/OHigh latency under concurrencyRelease before I/O; re-acquire after
Missing defer wg.Done()wg.Wait() never returnsAlways defer wg.Done() in goroutine
// Five essential concurrent patterns

// 1. Worker with cancellation
go func() {
    for { select { case <-ctx.Done(): return; case job := <-jobs: process(job) } }
}()

// 2. One-time safe initialisation
var once sync.Once
once.Do(func() { /* runs exactly once across all goroutines */ })

// 3. Concurrent tasks with error collection
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return task1(ctx) })
g.Go(func() error { return task2(ctx) })
if err := g.Wait(); err != nil { handle(err) }

// 4. Non-blocking channel operation
select { case ch <- val: ; default: /* channel full */ }

// 5. Timeout with automatic cleanup
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
Which tool is most appropriate for protecting a struct field read by 100 goroutines/sec and written once per minute?
What is the single most important flag to add to Go test runs for catching concurrency bugs early?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.

Invest now!!! Get Free equity stock (US, UK only)!

Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.

The Robinhood app makes it easy to trade stocks, crypto and more.


Webull! Receive free stock by signing up using the link: Webull signup.

More Related questions...

Explain Go's GMP scheduler model. What are M, P, and G and how do they interact? What is work stealing in Go's scheduler and why does it matter for performance? Why can Go run millions of goroutines while equivalent OS-thread workloads fail? What is the difference between unbuffered and buffered channels in Go? What happens when you send to, receive from, or close a nil or closed channel? How does the select statement work in Go and what are its key properties? What is a data race in Go, how do you detect it, and what are the three main fixes? When do you use sync.Mutex versus sync.RWMutex, and what are the critical usage rules? How does sync.WaitGroup work and what are the most common mistakes? What is sync.Once and what guarantees does it provide? What causes deadlocks in Go and how do you detect and prevent them? What are directional channels in Go and why use them in function signatures? What causes goroutine leaks and how do you prevent and detect them? Implement fan-out and fan-in concurrency patterns in Go. How do you use a nil channel in select to dynamically enable or disable cases? When should you use the sync/atomic package instead of sync.Mutex? Implement a bounded worker pool pattern in Go. What are the differences between time.After, time.NewTimer, and time.NewTicker, and which leaks resources? How does context.Context enable clean goroutine cancellation and why is 'defer cancel()' critical? How do you use a buffered channel as a semaphore to limit goroutine concurrency? What is the 'done channel' pattern and why has context.Context largely superseded it? What is the goroutine loop-variable capture bug and how do you fix it? How does golang.org/x/sync/errgroup simplify concurrent error handling? When should a channel carry 'chan struct{}' versus a typed value, and why is close() used for broadcast? What is GOMAXPROCS, how does it affect parallelism, and what is the container pitfall? How does Go's select handle multiple ready cases, and how do you implement true priority? What is sync.Cond and when do you use it instead of channels? Implement Go's canonical pipeline pattern with cancellation from the Go blog. What is Go's memory model and why does it matter for concurrent code? What is the check-then-act race condition (TOCTOU) and how do you fix it? What is asynchronous preemption in Go (1.14+) and why was it introduced? How do you safely use a map from multiple goroutines in Go? How do you use a buffered channel as a task queue with natural backpressure? How does Go handle goroutines that make blocking syscalls — what happens to M and P? Implement a simple publish-subscribe broker using Go channels. What is the lock-held-during-I/O anti-pattern and how do you fix it? Write a complete example of implementing operation timeouts in Go using select. How do you write tests that detect goroutine leaks automatically? Implement a concurrent word count across multiple files — a classic Go interview puzzle. How does GOMAXPROCS=1 change behaviour and when is it actually useful? How do you implement a high-performance sharded concurrent map in Go? What are the specific happens-before guarantees for channel operations in Go's memory model? How do you implement a hedged request pattern using select and goroutines? How does sync.Pool reduce GC pressure in high-throughput Go services? What is a livelock and how does it differ from a deadlock in Go programs? How do you implement backpressure in Go to prevent overloading downstream systems? Implement a lock-free stack using atomic CAS operations and explain the ABA problem. Summarise: channel vs mutex decision guide, and the top concurrency pitfalls.
Show more question and Answers...

GoLang Production Patterns and Web Standards Interview Questions

Comments & Discussions