Skip to Content
Course content

143: Context Propagation Best Practices

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

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"))
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.