Prev Next

Golang / GoLang Production Patterns and Web Standards Interview Questions

What are the best practices and anti-patterns for using context.WithValue?

context.WithValue should be used sparingly — only for request-scoped data that crosses API boundaries and would be impractical to pass as explicit parameters. It is not a general-purpose parameter-passing mechanism.

// ANTI-PATTERN: using a plain string as a context key
ctx = context.WithValue(ctx, "userID", 42)
// Any package can read/overwrite this key — key collisions guaranteed

// CORRECT: define an unexported typed key per package
// This prevents any other package from accidentally colliding
type contextKey string

const (
    requestIDKey contextKey = "requestID"
    userIDKey    contextKey = "userID"
)

// Better: use a struct type as the key (common in stdlib)
type requestIDKeyType struct{}

func WithRequestID(ctx context.Context, id string) context.Context {
    return context.WithValue(ctx, requestIDKeyType{}, id)
}

func RequestIDFromContext(ctx context.Context) (string, bool) {
    id, ok := ctx.Value(requestIDKeyType{}).(string)
    return id, ok
}

// GOOD USES of context values:
// - Request/trace IDs for logging and distributed tracing
// - Authentication tokens / user identity
// - Feature flags tied to the request

// BAD USES of context values:
// - Optional function parameters
// - Database connections (pass as explicit dependency)
// - Configuration that should be in a struct
// - Anything that the function should document as a dependency

// The Go proverb: 'Use context values only for request-scoped data
// that transits processes and API boundaries, not for passing
// optional parameters to functions.'

Context value lookups are O(n) in the number of values stored — each WithValue wraps the context in a new layer. Storing many values is inefficient. If you have many related values, wrap them in a single struct: context.WithValue(ctx, reqKey{}, &RequestData{UserID: 1, TraceID: "abc"}).

Why should context keys be unexported typed constants rather than plain strings?
What is the recommended data to store in context values?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.

Invest now!!! Get Free equity stock (US, UK only)!

Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.

The Robinhood app makes it easy to trade stocks, crypto and more.


Webull! Receive free stock by signing up using the link: Webull signup.

More Related questions...

Why does Go treat errors as values instead of using exceptions, and what are the advantages? How do you wrap errors in Go 1.13+ and use errors.Is and errors.As for inspection? What are the best practices for defining custom error types in Go? What is context.Context in Go, what does it carry, and how do you create one? How does context propagate through an HTTP request lifecycle in Go? What are the best practices and anti-patterns for using context.WithValue? How do you build a production-ready HTTP server using Go's standard net/http package? What is the standard Go HTTP middleware signature and how do you chain multiple middleware? How has http.ServeMux evolved in Go 1.22 and what routing patterns does it support? How do you encode and decode JSON in Go and what are the common pitfalls? What are the rules for writing HTTP responses correctly in Go handlers? How do you implement dependency injection in Go without a framework? How do you implement structured logging in Go using the slog package? What are the idiomatic Go patterns for managing application configuration? How do you interact with a SQL database in Go using the standard database/sql package? How do you implement graceful shutdown of an HTTP server in Go? How do you test HTTP handlers in Go without starting a real server? What are table-driven tests in Go and why are they the preferred testing pattern? How do you write testable Go code using interfaces and mocks without a framework? How do you implement rate limiting in a Go HTTP server? How do you implement CORS correctly in a Go HTTP server? How and when should you use panic and recover in production Go code? How do you manage environment-specific settings and feature flags in Go? How do you implement health check and readiness endpoints for a Go service? How do you add observability (metrics and distributed tracing) to a Go service? How do build tags work in Go and when do you use them? What are the best practices for using Go's HTTP client in production? What patterns make HTTP error handling consistent and DRY in Go? What are the common API versioning strategies in Go HTTP services? How do Go programs handle OS signals and interact with the operating system? How do you profile a Go service in production using pprof? How does Go's module system work and what are the key commands? How do you validate HTTP request inputs in Go without a framework? How do you implement streaming HTTP responses in Go? How do you write and interpret Go benchmarks? How do you embed static files into a Go binary using go:embed? How do you implement timeouts for non-HTTP operations like database queries and external calls? What are the conventions for returning structured error responses from a Go REST API? How do you implement pagination for list endpoints in a Go REST API? How do you implement JWT authentication middleware in Go? How do you implement HTTP response caching in a Go service? How does gRPC work in Go and when would you choose it over REST/JSON? What linters and static analysis tools are essential for production Go code quality? What is the recommended project structure for a production Go service? How do you implement load shedding and request queue limits in a Go HTTP server? How do you correctly propagate errors from concurrent goroutines in a Go service? How do you document a Go REST API and maintain an OpenAPI specification? What is the production readiness checklist for a Go HTTP service?
Show more question and Answers...

GoLang System Architecture and Testing Interview Questions

Comments & Discussions