Goroutines
A goroutine is a lightweight thread managed by the Go runtime — start one with the go keyword.
Introduction
A goroutine is a lightweight thread managed by the Go runtime — start one with the go keyword. Goroutines multiplex onto OS threads (M:N scheduling), enabling millions of concurrent tasks with kilobytes of stack each.
Goroutines power HTTP servers (one per request), worker pools, background jobs, and streaming pipelines. Without synchronization (channels, WaitGroup, mutex), shared state races corrupt data — interviewers always probe this gap.
This lesson covers spawning goroutines, the GOMAXPROCS setting, and common patterns for graceful shutdown with context cancellation.
The story
Google's gRPC servers handle each incoming RPC in its own goroutine — lightweight green threads scheduled by the Go runtime across OS threads. A Docker registry mirror spawns goroutines per layer download, saturating network bandwidth without the memory overhead of one OS thread per connection.
Goroutines communicate via channels (next lesson), but launching them is trivial: go processRequest(req) — the concurrency model that makes Go the default language for cloud-native infrastructure.
Understanding the topic
Key concepts
- go func() starts goroutine — non-blocking, runs concurrently.
- Main goroutine exiting kills all goroutines — wait before exit.
- runtime.GOMAXPROCS sets OS thread count; defaults to CPU cores.
- Goroutine stack starts ~2KB, grows dynamically.
- Closure captures variables by reference — mind loop vars (fixed Go 1.22).
- Leak: goroutine blocked forever on channel — always plan exit path.
Step-by-step explanation
- go statement schedules function on runtime scheduler.
- Scheduler assigns goroutines to GOMAXPROCS logical processors.
- Blocking syscall may spawn additional OS thread.
- Main returns → program exits regardless of background goroutines.
- Use sync.WaitGroup or channel to synchronize completion.
- context.Context signals cancellation across goroutine tree.
Practical code example
Worker pool spawning goroutines with WaitGroup and context:
package mainimport ("context""fmt""sync""time")func worker(ctx context.Context, id int, jobs <-chan int, wg *sync.WaitGroup) {defer wg.Done()for {select {case <-ctx.Done():returncase job, ok := <-jobs:if !ok {return}fmt.Printf("worker %d processed job %d\n", id, job)time.Sleep(50 * time.Millisecond)}}}func main() {ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)defer cancel()jobs := make(chan int, 10)var wg sync.WaitGroupfor i := 1; i <= 3; i++ {wg.Add(1)go worker(ctx, i, jobs, &wg)}for j := 1; j <= 5; j++ {jobs <- j}close(jobs)wg.Wait()}
Line-by-line code explanation
func worker(ctx context.Context, id int, jobs <-chan int, wg *sync.WaitGroup) {is the function each goroutine runs. The jobs parameter is receive-only, and the WaitGroup is passed as a pointer so all workers share one counter.defer wg.Done()tells the WaitGroup this worker has finished, no matter which return path the function takes.case <-ctx.Done():is one branch of a select inside an endless for loop. When the context times out or is cancelled, the worker returns.case job, ok := <-jobs:receives the next job. The ok value is false once the channel is closed and empty, and the worker then returns.fmt.Printf("worker %d processed job %d\n", id, job)reports which worker took which job. The worker then sleeps 50 milliseconds to pretend to do work, so the order of these lines can vary between runs.ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)creates a context that expires after half a second.defer cancel()releases its resources when main returns.jobs := make(chan int, 10)makes a buffered channel with room for 10 values, so main can queue the 5 jobs without waiting for a worker to be ready.go worker(ctx, i, jobs, &wg)starts a goroutine. It sits in a loop that runs three times, and each pass calls wg.Add(1) first so the WaitGroup counts that worker.close(jobs)runs after main has sent jobs 1 to 5. It tells the workers no more jobs are coming, andwg.Wait()then blocks main until all three workers have returned.
Key takeaway: Always provide cancellation path. close(jobs) signals no more work. WaitGroup ensures main waits for workers.
Real-world use
Where you'll use this in production
- net/http handles each request in a goroutine automatically.
- Background email/notification senders decoupled from API response.
- Parallel health checks aggregating microservice status.
- Fan-out/fan-in data processing pipelines.
Best practices
- Every goroutine must have a planned exit (context, close, timeout).
- Use WaitGroup or errgroup for coordinated shutdown.
- Don't spawn unbounded goroutines — use worker pools with limits.
- Pass dependencies as params, not global vars.
- Monitor goroutine count in production via runtime/metrics or pprof.
Common mistakes
- Main exits before goroutines finish — incomplete work.
- Goroutine leak on blocked channel send/receive.
- Unbounded go per incoming request without backpressure.
- Race on shared variables without sync or channels.
- Capturing loop variable in closure pre-1.22.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionGoroutine vs OS thread?+
Answer
2BeginnerQuestionWhat happens if main returns while goroutines run?+
Answer
3IntermediateQuestionGOMAXPROCS effect?+
Answer
4IntermediateQuestionDetect goroutine leak?+
Answer
5AdvancedQuestionDesign worker pool processing 10K jobs/sec.+
Answer
Summary
go keyword launches lightweight concurrent goroutines. Main must wait for workers — WaitGroup, channels, or errgroup. Always plan goroutine exit to prevent leaks. Use worker pools instead of unbounded goroutine spawning. Next lesson: channels — communicating between goroutines.