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
143: Context Propagation Best Practices
I've seen this bug in almost every mid-sized Go project I've joined. It usually starts with a developer trying to be "helpful" by ensuring a function always has a context, but in doing so, they accidentally create a zombie process that refuses to die when a user disconnects.
type UserService struct {
db *sql.DB
}
func (s *UserService) GetUserStats(id int) (*Stats, error) {
// Oops: We're creating a fresh background context here
// instead of accepting one from the caller.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return s.db.QueryStats(ctx, id)
}
func HandleRequest(w http.ResponseWriter, r *http.Request) {
service := &UserService{db: globalDB}
stats, err := service.GetUserStats(123)
// ... handle response
}
The Ghost Query Problem
At first glance, the code above looks responsible. It has a timeout! It prevents the database call from hanging forever. But here is the problem: we've broken the chain of propagation.
Imagine the user hits the endpoint, but then immediately closes their browser or hits "Stop". The http.Request context is automatically cancelled by the Go standard library. However, GetUserStats doesn't know that. It created its own context.Background(), which is a root context that never gets cancelled by external events.
The server will keep grinding away at that database query for the full 5 seconds, even though there is no one left to receive the answer. In a high-traffic system, this leads to "ghost load"—your database is pegged at 100% CPU, but your logs show no active users. You're wasting resources on work that has already been abandoned.
Passing the Torch
The fix is simple but requires a discipline shift: Context must always flow from the top down. Never create a new root context inside a business logic function if that function is part of a request chain.
type UserService struct {
db *sql.DB
}
// We now accept ctx as the first argument. This is the Go way.
func (s *UserService) GetUserStats(ctx context.Context, id int) (*Stats, error) {
// We wrap the incoming context rather than replacing it.
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
return s.db.QueryStats(ctx, id)
}
func HandleRequest(w http.ResponseWriter, r *http.Request) {
service := &UserService{db: globalDB}
// We pass the request context directly into the service.
stats, err := service.GetUserStats(r.Context(), 123)
// ... handle response
}
Now, if the user cancels the request, r.Context() is cancelled. Because GetUserStats used context.WithTimeout(ctx, ...), the new child context is also cancelled immediately. The database driver sees the cancellation and kills the query on the server side. Everything stops exactly when it should.
Why you should never put Context in a struct
You'll be tempted to do this to avoid adding ctx context.Context to every single function signature. I get it; it feels like boilerplate. But please, don't do it.
Contexts are intended to be transient. They represent the lifecycle of a single request, not the lifecycle of a service. If you store a context in a struct, you're tying that struct to a specific point in time. If that struct is a long-lived singleton (like a database repository), you'll end up with a context that expired three days ago, and every single method call will fail instantly with context deadline exceeded.
If you find yourself hating the ctx argument, remember: that explicit passing is actually a feature. It tells any engineer reading your code exactly which functions are "cancellable" and where the request boundaries lie.
📋 Practical Task
Fixing the Leaky Request Pipeline
You have been handed a piece of a legacy payment system. The ProcessPayment function is causing database connection spikes because it isn't respecting cancellations from the API layer.
Your Task: Refactor the following code to correctly propagate the context from the PaymentHandler down to the PaymentRepo. Ensure that the timeout is still enforced, but it must be a child of the request context.
package main
import (
"context"
"fmt"
"net/http"
"time"
)
type PaymentRepo struct{}
func (r *PaymentRepo) Execute(ctx context.Context, amount int) error {
// Simulate DB work
select {
case <-time.After(2 * time.Second):
fmt.Println("Payment processed")
return nil
case <-ctx.Done():
fmt.Println("DB query cancelled!")
return ctx.Err()
}
}
type PaymentService struct {
repo *PaymentRepo
}
// BUG: This function creates its own background context
func (s *PaymentService) ProcessPayment(amount int) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return s.repo.Execute(ctx, amount)
}
func PaymentHandler(w http.ResponseWriter, r *http.Request) {
svc := &PaymentService{repo: &PaymentRepo{}}
err := svc.ProcessPayment(100)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write([]byte("Success"))
}
There are no comments for now.