Interviews for mid and senior Go roles rarely test syntax. They test whether you have run Go services under real load and know what happens when a dependency hangs, a pod receives SIGTERM, a goroutine never exits or the heap grows faster than the container allows. This guide covers the concepts behind strong answers to situational questions about Go in production. Each section explains the mechanism, shows a short runnable example built around an invented system and lists the traps that separate someone who has read about Go from someone who has operated it. Read the explanations for the why, not only the API. When an interviewer describes a symptom such as rising memory, stuck deploys or intermittent 502s, you should be able to trace it back to one of these mechanisms.
Study order
If time is short, go in this order.
- Context propagation, deadlines and cancellation
Almost every situational question about timeouts, slow dependencies or cancelled requests is really a question about how context flows.
- Goroutine lifecycle, bounded concurrency and leaks
Leaks and unbounded fan-out are the most common Go production incidents, and interviewers probe whether you know who stops each goroutine.
- HTTP server timeouts and client connection reuse
Unsafe net/http defaults cause hung requests and connection churn; knowing them signals real operational experience.
- Graceful shutdown and signal handling
Deploy-time errors are a frequent scenario, and the answer requires ordering signals, draining and cleanup correctly.
- Data races, mutexes, atomics and the race detector
Concurrency correctness underpins everything else and the race detector is expected knowledge at mid level.
- Error wrapping, sentinel errors and typed errors
Error design shows up in code review questions and in how you map failures to responses and alerts.
- Structured logging, metrics and profiling with slog and pprof
Senior candidates are expected to explain how they would diagnose a live problem, which means profiles, logs and metrics.
- GOMAXPROCS, GOMEMLIMIT and the GC in containers
Memory and CPU behaviour in Kubernetes is a common senior-level follow-up once the basics are covered.
Context propagation, deadlines and cancellation
context.Context carries a deadline, a cancellation signal and request-scoped values across API boundaries. In a production service, every inbound request gets a context from net/http, and that context should flow into every database query, RPC and blocking operation the request triggers. When the client disconnects or the deadline passes, the work downstream stops instead of burning CPU and connections for a response nobody will read.
Deadlines compose. If the checkout handler for a ticketing service called Gatehouse has a 2 second budget and the seat-map call gets context.WithTimeout(ctx, 300*time.Millisecond), the effective deadline is whichever comes first. This is how you stop one slow dependency from consuming the whole request budget.
Cancellation is cooperative. Cancelling a context only closes a channel; your code, or the library you call, must select on ctx.Done() or pass the context to something that does. Always call the cancel function returned by WithTimeout or WithCancel, usually with defer, so the runtime can release the timer and child bookkeeping.
Go
package main
import (
"context"
"errors"
"fmt"
"time"
)
func fetchSeatMap(ctx context.Context, eventID string) (string, error) {
select {
case <-time.After(300 * time.Millisecond): // simulated slow dependency
return "seatmap:" + eventID, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
_, err := fetchSeatMap(ctx, "concert-42")
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("seat map timed out, serving cached layout")
}
}The 100 ms budget wins over the 300 ms dependency; the caller degrades instead of waiting.
Traps
- Using
context.Background()inside a handler instead ofr.Context()silently drops the client's cancellation and the request deadline. - Forgetting to call
cancelkeeps the timer and the child context alive until the parent ends;go vetreports this as a lost cancel. - Storing a context in a struct field makes its lifetime unclear; pass it as the first parameter of each call instead.
- Putting optional parameters or dependencies in
context.WithValuehides them from the function signature; keep values to request-scoped data such as trace IDs. - Starting background work that must outlive the request with the request context gets it cancelled as soon as the response is written; use
context.WithoutCancel(Go 1.21+) or a separate context.
Goroutine lifecycle, bounded concurrency and leaks
Goroutines are cheap to start but never free to forget. Every goroutine you launch needs a clear answer to two questions: who waits for it, and what makes it stop. A goroutine blocked forever on a channel send, a receive with no sender or a call without a timeout is a leak. Its stack and everything it references stay alive, and over hours the service's memory and goroutine count climb steadily.
Unbounded fan-out is the other classic failure. Launching one goroutine per item for a batch of 50,000 photos will open 50,000 connections to the image store at once. Bound the concurrency with a worker pool, a buffered-channel semaphore, or errgroup.Group with SetLimit, which blocks Go until a slot is free.
errgroup.WithContext also gives you first-error cancellation: when one task fails, the derived context is cancelled so the others can stop early, and Wait returns the first error. In the example, a listing service called Roomly resizes 200 photos with at most 8 in flight.
A panic in any goroutine that is not recovered crashes the whole process. net/http recovers panics in handlers, but not in goroutines those handlers start.
Go
package main
import (
"context"
"fmt"
"golang.org/x/sync/errgroup"
)
func resize(ctx context.Context, id int) error {
if err := ctx.Err(); err != nil {
return err // another task already failed
}
if id == 137 {
return fmt.Errorf("photo %d: corrupt header", id)
}
return nil
}
func main() {
g, ctx := errgroup.WithContext(context.Background())
g.SetLimit(8)
for id := 1; id <= 200; id++ {
g.Go(func() error { return resize(ctx, id) })
}
if err := g.Wait(); err != nil {
fmt.Println("batch failed:", err)
}
}Requires golang.org/x/sync. Since Go 1.22 each loop iteration has its own id, so the closure capture is safe.
Traps
- Before Go 1.22, closures in loops shared one loop variable; in older modules you must copy it (
id := id) or pass it as an argument. - A goroutine sending to an unbuffered channel whose reader returned early on timeout blocks forever; give the channel a buffer of 1 or select on
ctx.Done(). runtime.NumGoroutine()exported as a metric is the cheapest leak detector; a count that only grows is a bug, not load.- Calling
wg.Addinside the goroutine races withwg.Wait; call it before thegostatement, or usewg.Goon Go 1.25+. - A panic in a background goroutine kills the process, including all in-flight requests; recover at the top of long-lived goroutines and log it.
Graceful shutdown and signal handling
Orchestrators such as Kubernetes stop a pod by sending SIGTERM, waiting for the grace period (30 seconds by default) and then sending SIGKILL. A Go service that ignores SIGTERM dies mid-request, and clients see connection resets during every deploy.
The standard pattern is signal.NotifyContext to turn the signal into a cancelled context, then http.Server.Shutdown with its own timeout. Shutdown closes the listeners so no new connections are accepted, closes idle connections and waits for active requests to finish. After it returns, ListenAndServe has already returned http.ErrServerClosed, which is the expected result and not an error.
Order matters. Stop accepting traffic first, let in-flight work drain, then close the things requests depend on: consumers, database pools, tracing exporters that need a final flush. Your shutdown timeout must be shorter than the orchestrator's grace period, otherwise SIGKILL arrives before your cleanup does.
Go
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
srv := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
}),
ReadHeaderTimeout: 5 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %v", err)
}
}()
<-ctx.Done()
log.Println("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("forced shutdown: %v", err)
}
// close DB pools, flush telemetry here
}20 seconds of drain time fits inside a 30 second Kubernetes grace period.
Traps
- Deriving the shutdown timeout from the already-cancelled signal context makes
Shutdownreturn immediately; use a fresh context. Shutdowndoes not wait for hijacked connections such as WebSockets; track them yourself or useRegisterOnShutdownto notify them.log.Fatalcallsos.Exit, which skips deferred functions, so cleanup in defers never runs.- Load balancers may keep routing to the pod for a few seconds after SIGTERM; failing the readiness probe and pausing briefly before
Shutdownavoids dropped requests.
Error wrapping, sentinel errors and typed errors
Go errors are values, and production code needs them to carry two things: context for the human reading the log, and identity for the code deciding what to do. fmt.Errorf with %w adds context while keeping the original error in the chain, and errors.Is and errors.As walk that chain.
Use sentinel errors (var ErrInsufficientFunds = errors.New(...)) when callers only need to know which condition happened. Use a custom error type when they need data from it, such as the limit that was exceeded. In the example, a payments service called Ledgerline maps ErrInsufficientFunds to HTTP 402 and *LimitError to 429, while anything else becomes a 500.
Wrapping is part of your API. Once you wrap with %w, callers can depend on the inner error, so wrapping a driver-specific error from your repository layer leaks that dependency upward. Use %v when you want the message but not the identity, or translate to your own domain error at the boundary.
Handle each error once: either log it or return it with context. Doing both produces the same failure five times in the logs.
Go
package main
import (
"errors"
"fmt"
)
var ErrInsufficientFunds = errors.New("insufficient funds")
type LimitError struct {
Account string
Limit int64
}
func (e *LimitError) Error() string {
return fmt.Sprintf("account %s exceeds daily limit of %d cents", e.Account, e.Limit)
}
func debit(account string, cents int64) error {
if cents > 500_000 {
return &LimitError{Account: account, Limit: 500_000}
}
if cents > 12_000 {
return ErrInsufficientFunds
}
return nil
}
func transfer(from string, cents int64) error {
if err := debit(from, cents); err != nil {
return fmt.Errorf("transfer from %s: %w", from, err)
}
return nil
}
func main() {
err := transfer("acc-881", 20_000)
fmt.Println(errors.Is(err, ErrInsufficientFunds)) // true
var le *LimitError
if errors.As(transfer("acc-881", 900_000), &le) {
fmt.Println("limit:", le.Limit) // limit: 500000
}
}Context is added at each layer; identity survives for errors.Is and errors.As.
Traps
- Comparing with
err == ErrXfails once anything wraps the error; useerrors.Is. - Returning a typed nil pointer (
var e *LimitError; return e) aserrorproduces a non-nil interface, soerr != nilis true. - Matching on
err.Error()strings breaks as soon as someone rewords a message. - Logging and returning the same error duplicates it in every layer; decide where it is handled.
- Passing a value instead of a pointer to
errors.Aspanics; the target must be a non-nil pointer to an interface or to a type implementing error.
HTTP server timeouts and client connection reuse
The zero values in net/http are unsafe for production. http.DefaultClient has no timeout, so a dependency that accepts the connection and never answers blocks your goroutine forever. A bare http.Server has no read or write timeouts, so slow or malicious clients can hold connections open indefinitely. Set ReadHeaderTimeout at minimum, plus ReadTimeout, WriteTimeout and IdleTimeout sized to your endpoints, and set Client.Timeout or per-request context deadlines on every outbound call.
Connection reuse depends on two habits. First, create one client per dependency and share it; a Transport owns a pool of keep-alive connections, and a new client per request means a new TCP and TLS handshake every time. Second, always close the response body, and drain it if you did not read it to the end, or the connection cannot go back to the pool.
MaxIdleConnsPerHost defaults to 2. A service calling one upstream at 500 requests per second will keep closing and reopening connections, which shows up as many sockets in TIME_WAIT. Clone http.DefaultTransport and raise that value rather than building a Transport from scratch, which would lose defaults like proxy support and dial timeouts.
Go
package main
import (
"fmt"
"io"
"net/http"
"time"
)
func newRatesClient() *http.Client {
t := http.DefaultTransport.(*http.Transport).Clone()
t.MaxIdleConnsPerHost = 20
return &http.Client{Timeout: 3 * time.Second, Transport: t}
}
var ratesClient = newRatesClient() // shared, safe for concurrent use
func fetchRates(url string) ([]byte, error) {
resp, err := ratesClient.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
io.Copy(io.Discard, resp.Body) // drain so the connection is reused
return nil, fmt.Errorf("rates: unexpected status %d", resp.StatusCode)
}
return io.ReadAll(io.LimitReader(resp.Body, 1<<20))
}
func main() {
body, err := fetchRates("https://example.com/")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(len(body), "bytes")
}One client per upstream, a hard timeout, a drained body and a cap on how much is read.
Traps
Client.Timeoutcovers the whole exchange including reading the body, so a 3 second timeout will cut off a large streaming download.WriteTimeouton the server also limits long-lived responses such as server-sent events; usehttp.ResponseControllerto extend deadlines per request.- Reading an unbounded body with
io.ReadAlllets one bad upstream exhaust memory; wrap it inio.LimitReaderorhttp.MaxBytesReader. - An HTTP error status is not a Go error:
erris nil for a 503, so checkStatusCodeexplicitly.
Data races, mutexes, atomics and the race detector
A data race happens when two goroutines access the same memory concurrently and at least one writes, without synchronisation. In Go the result is undefined behaviour, not just a stale value: torn reads of interfaces or slices can crash the program. Concurrent writes to a built-in map are detected by the runtime and cause a fatal error that recover cannot catch.
Protect shared state with sync.Mutex or sync.RWMutex when you update several fields or a map together, and use sync/atomic types such as atomic.Int64 for single counters or flags. Channels are the right tool when ownership of data moves between goroutines, not as a general replacement for locks.
In the example, an API gateway called Tollbooth counts requests per key. The map needs the mutex; the global counter is an atomic so it can be read by a metrics endpoint without contending on the lock.
Run tests with go test -race in CI. The detector finds races only in code paths that actually execute, so it is as good as your concurrent test coverage, and it adds significant CPU and memory overhead, which is why it is usually kept out of production builds.
Go
package main
import (
"fmt"
"sync"
"sync/atomic"
)
type QuotaTracker struct {
mu sync.Mutex
usage map[string]int
total atomic.Int64
}
func NewQuotaTracker() *QuotaTracker {
return &QuotaTracker{usage: make(map[string]int)}
}
func (q *QuotaTracker) Record(apiKey string) int {
q.total.Add(1)
q.mu.Lock()
defer q.mu.Unlock()
q.usage[apiKey]++
return q.usage[apiKey]
}
func main() {
q := NewQuotaTracker()
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
q.Record(fmt.Sprintf("key-%d", i%3))
}()
}
wg.Wait()
fmt.Println(q.total.Load(), q.usage["key-0"]) // 1000 334
}Mutex for the map, atomic for the single counter; go run -race reports nothing.
Traps
- Copying a struct that contains a
sync.Mutexcopies the lock state; use pointer receivers and letgo vet(copylocks) catch it. - Concurrent map writes trigger a fatal runtime error, not a panic, so no
recoverwill save the process. - Returning a map or slice from behind a lock still shares the underlying data; copy it before releasing the lock.
- Holding a lock while doing I/O, such as a network call, turns one slow dependency into contention across every request.
Structured logging, metrics and profiling with slog and pprof
In production you debug through telemetry. log/slog (Go 1.21+) gives structured, levelled logs with key-value attributes; a JSON handler produces output your log pipeline can index by order_id or trace_id instead of parsing free text. Attach request-scoped attributes once with logger.With and pass that logger down, rather than repeating fields at every call.
net/http/pprof exposes CPU, heap, goroutine, block and mutex profiles over HTTP. When an order service called Shelfwise shows rising latency, go tool pprof http://host:6060/debug/pprof/profile?seconds=30 captures a CPU profile from the live process, and /debug/pprof/goroutine?debug=2 dumps every goroutine's stack, which is the fastest way to find a leak or a deadlock.
Importing the package registers its handlers on http.DefaultServeMux. Serve that mux only on an internal port and route your public traffic through your own ServeMux, otherwise profiling endpoints become reachable from the internet. Pair logs and profiles with metrics such as request latency histograms, goroutine count and GC pause times, usually exported through Prometheus or OpenTelemetry.
Go
package main
import (
"log/slog"
"net/http"
_ "net/http/pprof" // registers /debug/pprof on DefaultServeMux
"os"
"time"
)
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
slog.SetDefault(logger)
go func() {
// internal only: never expose this port publicly
slog.Error("pprof server stopped", "err", http.ListenAndServe("localhost:6060", nil))
}()
mux := http.NewServeMux()
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
id := r.PathValue("id")
w.Write([]byte("order " + id))
slog.Info("order served", "order_id", id, "duration_ms", time.Since(start).Milliseconds())
})
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
slog.Error("server stopped", "err", srv.ListenAndServe())
}Public routes on a dedicated mux (Go 1.22 method and path patterns), pprof on localhost only.
Traps
- Registering public handlers on
http.DefaultServeMuxafter importingnet/http/pprofexposes profiling endpoints to anyone who can reach the server. - Block and mutex profiles are empty until you enable them with
runtime.SetBlockProfileRateandruntime.SetMutexProfileFraction. - Using high-cardinality values such as user IDs as metric labels explodes time-series storage; put them in logs or traces instead.
- Building expensive log arguments before a disabled Debug call still costs CPU; check
logger.Enabledor useslog.LogValuer.
GOMAXPROCS, GOMEMLIMIT and the GC in containers
The Go runtime makes two decisions that interact badly with containers if you do not know them. GOMAXPROCS sets how many OS threads run Go code simultaneously. Before Go 1.25 it defaulted to the number of host CPUs, ignoring the cgroup CPU limit, so a pod limited to 2 CPUs on a 64-core node ran 64 Ps and got throttled by the kernel, causing latency spikes. Go 1.25 made the default respect the cgroup CPU limit on Linux; on older versions teams set it explicitly or used the automaxprocs library.
The garbage collector is paced by GOGC (default 100): it starts a cycle when the heap grows by that percentage over the live heap left after the last collection. It knows nothing about the container memory limit, so a service with a 300 MiB live heap can target around 600 MiB and be OOM-killed in a 512 MiB container. GOMEMLIMIT (Go 1.19+) sets a soft limit; as the total Go-managed memory approaches it, the GC runs more often to stay under it. Setting it to roughly 90 percent of the container limit leaves headroom for memory the runtime does not manage, such as cgo allocations.
The limit is soft. If the live heap genuinely exceeds it, the runtime caps the CPU spent on GC instead of thrashing, and memory keeps growing. GOMEMLIMIT prevents premature OOMs from GC pacing; it does not fix a leak.
Go
package main
import (
"fmt"
"runtime"
"runtime/debug"
)
func main() {
// Container limit of 512 MiB; keep 10% headroom for non-heap memory.
// In deployment, prefer the GOMEMLIMIT env var, e.g. GOMEMLIMIT=460MiB.
const containerLimit = 512 << 20
prev := debug.SetMemoryLimit(containerLimit * 9 / 10)
fmt.Println("previous limit:", prev) // math.MaxInt64 when unset
fmt.Println("GOMAXPROCS:", runtime.GOMAXPROCS(0)) // 0 reads without changing
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("heap in use: %d KiB, GC cycles: %d\n", m.HeapInuse>>10, m.NumGC)
}Reading and setting runtime limits; in real deployments set them through environment variables.
Traps
- Setting
GOMEMLIMITequal to the container limit leaves no room for goroutine stacks overhead, cgo or OS buffers, so the kernel can still OOM-kill the pod. - Setting
GOGC=offwithGOMEMLIMITis a valid tuning for some workloads, but without the limit it disables collection entirely. runtime.ReadMemStatsbriefly stops the world; for frequent sampling preferruntime/metrics.- Raising
GOMAXPROCSabove the CPU quota does not add throughput; it increases throttling and tail latency.
Common questions
Short answers to the usual doubts.
How do I find a goroutine leak in a running service?
Watch the goroutine count metric over time; if it only rises, fetch /debug/pprof/goroutine?debug=2 and look for many goroutines parked at the same line, typically a channel send or receive or a network read without a deadline. In tests, the goleak package from Uber can fail a test that leaves goroutines behind.
Should I use channels or mutexes for shared state?
Use a mutex when several goroutines read and update the same structure, such as a cache or counter map. Use channels when you are handing work or ownership of data from one goroutine to another, such as a job queue. Forcing everything through channels usually produces more complex code, not safer code.
Is the race detector safe to run in production?
It is designed for tests and staging. It typically multiplies memory use and slows execution several times over, so most teams run go test -race in CI and sometimes a race-enabled build in a canary or load-test environment, not on the main fleet.
Do I still need automaxprocs?
On Go 1.25 or later running on Linux, the default GOMAXPROCS already respects the cgroup CPU limit and updates if the limit changes, so the library is usually unnecessary. On older Go versions it remains a common way to avoid CPU throttling in containers.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Go in productionTake the test