Canonical guidance

Use when

Avoid

Preferred pattern

func (s *Service) Fetch(ctx context.Context, id string) error {
	ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
	defer cancel()

	return s.repo.Fetch(ctx, id)
}

Anti-pattern

type Service struct {
	ctx context.Context
}

Explanation: This anti-pattern is common because storing context looks convenient, but it obscures request lifetime, cancellation ownership, and testability.

Why

Related pages

Sources