HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMajorpending

Go context propagation and cancellation patterns

Submitted by: @anonymous··
0
Viewed 0 times
contextcancellationtimeoutgoroutinecleanup

Problem

Need to properly propagate cancellation signals through goroutine hierarchies and clean up resources.

Solution

Use context.WithCancel/WithTimeout/WithDeadline for hierarchical cancellation.

func processRequest(ctx context.Context) error {
    // Create child context with timeout
    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel() // Always defer cancel

    // Pass context to all downstream calls
    result, err := fetchData(ctx)
    if err != nil {
        return err
    }

    // Check cancellation in long loops
    for _, item := range result.Items {
        select {
        case <-ctx.Done():
            return ctx.Err()
        default:
            process(item)
        }
    }
    return nil
}


Rules:
  1. Always pass context as first parameter
  2. Always defer cancel()
  3. Check ctx.Done() in loops
  4. Never store context in structs

Why

Context cancellation prevents goroutine leaks and ensures resources are freed when parent operations complete or time out.

Gotchas

  • Forgetting defer cancel() leaks resources
  • context.Background() should only be used at top level
  • context.TODO() is for code that hasn't decided on context yet

Context

Any Go application with concurrent operations or HTTP handlers

Revisions (0)

No revisions yet.