Common Pitfalls
- Recognise the most common Go bugs from their production symptoms (panics, leaks, wrong totals, hangs).
- Fix each one idiomatically, and know which Go versions changed the rules (loop variables in 1.22, timers in 1.23).
- Configure linters and tests so these bugs are caught in CI rather than in an incident review.
- Answer "spot the bug" interview questions quickly and explain the underlying mechanism.
TL;DR
- Most Go production bugs come from a small set of mechanisms: shared backing arrays, zero/nil values, interface representation, goroutine lifetimes, and missing limits (timeouts, body sizes, pools).
- Version matters: per-iteration loop variables need
go 1.22+ ingo.mod; garbage-collectable unstopped timers and unbuffered timer channels needgo 1.23+. - Money: integers in minor units, overflow checks, never
float64; JSON amounts and 64-bit IDs as integers or strings, never floats. - Every network call needs a context and a timeout; every response body must be closed; every
rowsmust be closed androws.Err()checked. - Most of this list is caught automatically by
go vet,staticcheck, a fewgolangci-lintlinters,-race, andgoleak— turn them on.
Why it matters
The bugs below are not exotic. Each one has caused real incidents in payment and commerce systems: reconciliation breaks from float rounding, settlement files truncated by ignored Close errors, pods OOM-killed by leaked goroutines during a sale, a whole cluster stalled by an HTTP client without a timeout. Interviewers use them as "what's wrong with this code?" questions because they reveal whether you understand Go's mechanics or just its syntax.
Core concepts
The catalogue is grouped by mechanism. Each entry: symptom, the bug, the fix.
Data structures
1. Writing to a nil map
Symptom: panic: assignment to entry in nil map, often in a struct whose constructor was bypassed.
type Batch struct{ totals map[string]int64 }
var b Batch
b.totals["VND"] += 100 // panic: the zero-value map is nil
// Fix: initialise in a constructor (and make the zero value unusable or lazy).
func NewBatch() *Batch { return &Batch{totals: make(map[string]int64)} }
2. Slice aliasing through append
Symptom: occasionally wrong or duplicated last elements, depending on input size.
base := make([]LineItem, 2, 10)
withFee := append(base, fee) // writes base's backing array [2]
withTax := append(base, tax) // overwrites [2]: withFee now ends with tax
// Fix: cap the capacity so append must copy, or clone explicitly.
withFee = append(base[:len(base):len(base)], fee)
withTax = append(slices.Clone(base), tax)
Details in Go Fundamentals.
3. Sub-slices and substrings retain the whole array
Symptom: heap grows although "only a few bytes" are kept per request.
func requestID(body []byte) []byte {
return body[:16] // keeps the entire (maybe 1 MB) body alive
}
// Fix: copy what you keep (strings.Clone for substrings).
func requestIDFixed(body []byte) []byte { return bytes.Clone(body[:16]) }
4. range copies values
Symptom: updates "don't stick".
for _, acc := range accounts {
acc.Balance += interest(acc) // modifies a copy
}
// Fix: index into the slice.
for i := range accounts {
accounts[i].Balance += interest(accounts[i])
}
5. Pointers to the range variable
Symptom (before Go 1.22): every pointer in the result points to the last element.
var vip []*Account
for _, a := range accounts {
if a.Tier == "vip" {
vip = append(vip, &a) // pre-1.22: one shared variable; 1.22+: a copy per iteration
}
}
// Fix (all versions): point at the slice element itself.
for i := range accounts {
if accounts[i].Tier == "vip" {
vip = append(vip, &accounts[i])
}
}
Even on 1.22+, &a points to a copy, so mutations through it don't reach accounts.
6. Relying on map iteration order
Symptom: flaky tests, non-deterministic report output, signatures that don't verify.
// Fix: sort keys when order matters (Go 1.23+ iterators).
for _, k := range slices.Sorted(maps.Keys(totals)) {
fmt.Fprintf(w, "%s,%d\n", k, totals[k])
}
7. Byte-indexing UTF-8 text
Symptom: invalid UTF-8 in SMS, statements or ISO 20022 messages; downstream rejects.
memo := "Chuyển tiền học phí tháng 6"
short := memo[:10] // may cut inside a multi-byte character
// Fix: truncate on rune boundaries.
func truncateRunes(s string, n int) string {
if utf8.RuneCountInString(s) <= n {
return s
}
return string([]rune(s)[:n])
}
Types, numbers and interfaces
8. Typed nil inside an interface
Symptom: err != nil on the success path; logs show <nil> errors.
func validate(p Payment) error {
var verr *ValidationError
if p.Amount <= 0 {
verr = &ValidationError{Field: "amount"}
}
return verr // non-nil interface holding a nil pointer
}
// Fix: return the literal nil.
func validateFixed(p Payment) error {
if p.Amount <= 0 {
return &ValidationError{Field: "amount"}
}
return nil
}
9. float64 for money
Symptom: totals off by a cent/đồng; reconciliation breaks that grow with volume.
a, b := 0.1, 0.2
fmt.Println(a+b == 0.3) // false: 0.30000000000000004
// (0.1+0.2 == 0.3 with untyped constants prints true — constant arithmetic is exact,
// which makes the bug invisible in quick experiments.)
// Fix: int64 minor units plus currency; decimal libraries for rates and FX.
type Money struct {
Amount int64 // 150000 = 150,000 VND; 1999 = 19.99 USD
Currency string
}
Database side: NUMERIC/BIGINT, never FLOAT (see Schema Patterns: Money, Audit, Multi-tenancy).
10. Silent integer overflow and truncating conversions
Symptom: negative balances or absurd amounts on large transfers.
var amount int64 = 3_000_000_000 // 3 billion VND: an ordinary corporate transfer
fmt.Println(int32(amount)) // -1294967296: conversion silently wraps
// Fix: keep int64 end to end; check before narrowing; check addition overflow.
func toInt32(v int64) (int32, error) {
if v < math.MinInt32 || v > math.MaxInt32 {
return 0, fmt.Errorf("amount %d out of int32 range", v)
}
return int32(v), nil
}
VND amounts are large: int32 tops out around 2.1 billion VND (≈ USD 85k), which real transfers exceed. Protobuf fields for amounts should be int64.
11. JSON number precision
Symptom: IDs or amounts change by one after a round trip through map[string]any or a JavaScript client.
var m map[string]any
_ = json.Unmarshal([]byte(`{"amount": 9007199254740993}`), &m)
fmt.Printf("%.0f\n", m["amount"].(float64)) // 9007199254740992: float64 lost precision
// Fix 1: decode into typed structs with int64 fields.
// Fix 2: for dynamic JSON, dec.UseNumber() keeps json.Number (a string).
// Fix 3: send 64-bit IDs to JS clients as strings.
type Txn struct {
ID int64 `json:"id,string"` // encodes as "9007199254740993"
}
Integers above 2^53 cannot be represented exactly in a float64 or a JavaScript number.
12. Comparing time.Time with ==
Symptom: equal instants compare unequal; map lookups by time miss.
t1 := time.Now()
t2 := t1.In(time.UTC)
fmt.Println(t1 == t2, t1.Equal(t2)) // false true — == compares location and monotonic reading
// Fix: t.Equal(u), t.Before(u), t.After(u); use t.UTC().Truncate(...) or Unix values as keys.
13. Cut-off times in the server's time zone
Symptom: "same-day" transfers settle the next day (or vice versa) for 7 hours of every day, because containers run in UTC.
if time.Now().Hour() >= 15 { // 15:00 UTC is 22:00 in Vietnam
settleNextBusinessDay()
}
// Fix: business rules in the business time zone, loaded once.
var vn = mustLoad("Asia/Ho_Chi_Minh")
func mustLoad(name string) *time.Location {
loc, err := time.LoadLocation(name)
if err != nil {
panic(err) // startup-time invariant
}
return loc
}
func afterCutoff(now time.Time) bool { return now.In(vn).Hour() >= 15 }
scratch images have no tz database: use distroless (includes tzdata) or import _ "time/tzdata" to embed it. Inject the clock (now time.Time) so tests can cover the boundary.
Control flow and errors
14. defer inside a loop
Symptom: "too many open files" or DB connections exhausted during batch jobs.
for _, path := range files {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close() // runs only when the whole function returns
process(f)
}
// Fix: one function per iteration so defer runs each time.
for _, path := range files {
if err := processFile(path); err != nil {
return err
}
}
15. Deferred call arguments are evaluated immediately
Symptom: latency metrics all show ≈0 ms.
start := time.Now()
defer observeLatency(time.Since(start)) // time.Since runs NOW, at the defer statement
// Fix: defer a closure.
defer func() { observeLatency(time.Since(start)) }()
16. Shadowed err with :=
Symptom: validation failures are logged but the function returns nil.
func validateAll(entries []Entry) error {
var err error
for _, e := range entries {
if verr := validate(e); verr != nil {
err := fmt.Errorf("entry %s: %w", e.ID, verr) // := declares a NEW err
log.Printf("validation: %v", err)
}
}
return err // always nil
}
// Fix: assign, and collect every failure.
func validateAllFixed(entries []Entry) error {
var errs []error
for _, e := range entries {
if verr := validate(e); verr != nil {
errs = append(errs, fmt.Errorf("entry %s: %w", e.ID, verr))
}
}
return errors.Join(errs...)
}
The shadow analyzer (golang.org/x/tools/go/analysis/passes/shadow) flags these.
17. Ignoring errors that matter
Symptom: truncated settlement files, "committed" transactions that weren't, partial result sets.
_ = tx.Commit(ctx) // BUG: a failed commit means nothing was saved
w.Flush() // BUG: buffered data may not be written
f.Close() // BUG on files you wrote: Close reports delayed write errors
for rows.Next() {
// scan...
}
// BUG: missing rows.Err() — a connection reset mid-iteration looks like "no more rows"
// Fix: check them all; for deferred Close on writers, join the error into the result.
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate payments: %w", err)
}
errcheck (in golangci-lint) catches unchecked errors; rowserrcheck and sqlclosecheck catch the database/sql ones.
Concurrency
18. Unbuffered channel deadlocks and stuck senders
Symptom: fatal error: all goroutines are asleep - deadlock! in small programs; in servers, silently stuck goroutines (the runtime only detects deadlock when every goroutine is blocked).
results := make(chan Result)
results <- compute() // blocks forever: nobody is receiving yet
r := <-results
// Fix: receive in another goroutine, buffer exactly as needed, and pair every
// send with a cancellation path.
results := make(chan Result, 1)
go func() { results <- compute() }()
select {
case r := <-results:
use(r)
case <-ctx.Done():
return ctx.Err()
}
19. Goroutines that never exit
Symptom: go_goroutines climbs forever; memory follows; OOM at peak.
func score(ctx context.Context, p Payment) (Score, error) {
ch := make(chan Score) // BUG: unbuffered
go func() { ch <- fraud.Score(p) }()
select {
case s := <-ch:
return s, nil
case <-ctx.Done():
return Score{}, ctx.Err() // sender is now stuck forever
}
}
// Fix: make(chan Score, 1) and pass ctx into the work; test with goleak.
Full treatment in Goroutines & Channels.
20. time.After in a hot loop
Symptom (before Go 1.23): memory grows with message rate; heap profile full of time.NewTimer.
for {
select {
case m := <-msgs:
handle(m)
case <-time.After(30 * time.Second): // a new timer every iteration
flushIdle()
}
}
// Fix: one timer, reset per iteration. Since Go 1.23 (go.mod go >= 1.23) timer
// channels are unbuffered, so Reset needs no drain dance, and unreferenced
// timers are garbage-collected even if never stopped.
idle := time.NewTimer(30 * time.Second)
defer idle.Stop()
for {
select {
case m := <-msgs:
handle(m)
idle.Reset(30 * time.Second)
case <-idle.C:
flushIdle()
idle.Reset(30 * time.Second)
case <-ctx.Done():
return
}
}
21. Copying a mutex
Symptom: data races and lost updates despite "locking".
type Wallet struct {
mu sync.Mutex
balance int64
}
func (w Wallet) Deposit(n int64) { // value receiver: locks a COPY of mu
w.mu.Lock()
defer w.mu.Unlock()
w.balance += n // and updates a copy of balance
}
// Fix: pointer receivers for any type containing a lock; never copy after use.
func (w *Wallet) DepositFixed(n int64) {
w.mu.Lock()
defer w.mu.Unlock()
w.balance += n
}
go vet (copylocks) reports "passes lock by value".
22. Concurrent map writes
Symptom: fatal error: concurrent map writes — the process dies; recover can't catch it.
var rateCache = map[string]float64{}
func handler(w http.ResponseWriter, r *http.Request) {
rateCache[r.URL.Query().Get("pair")] = fetchRate() // many goroutines write
}
// Fix: guard with a mutex (or sync.Map for write-once/read-many), or shard.
type RateCache struct {
mu sync.RWMutex
m map[string]Rate
}
23. WaitGroup.Add inside the goroutine
Symptom: Wait returns early; some results are missing; occasional panics from Done after reuse.
for _, m := range merchants {
go func() {
wg.Add(1) // BUG: may run after wg.Wait() already returned
defer wg.Done()
settle(m)
}()
}
wg.Wait()
// Fix: Add before go — or, since Go 1.25, wg.Go(func() { settle(m) }).
Go 1.25's vet waitgroup analyzer flags Add inside the goroutine.
Context, HTTP and databases
24. Ignoring or replacing the context
Symptom: work continues after clients time out; retries pile up; deploys hang on shutdown.
func (h *Handler) refund(w http.ResponseWriter, r *http.Request) {
ctx := context.Background() // BUG: drops cancellation and deadline
err := h.svc.Refund(ctx, r.PathValue("id")) // keeps running if the client is gone
// ...
}
// Fix: thread r.Context() (plus a budget) everywhere; use context-aware APIs
// (QueryContext, NewRequestWithContext, pgx methods taking ctx).
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
25. HTTP client without a timeout
Symptom: goroutines pile up behind a hung upstream; the service stops responding although CPU is idle.
resp, err := http.Get(pspURL) // http.DefaultClient: no timeout at all
// Fix: a configured client, shared and reused.
var pspClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
MaxIdleConnsPerHost: 50, // default 2 is too low for one busy upstream
ResponseHeaderTimeout: 5 * time.Second,
IdleConnTimeout: 90 * time.Second,
},
}
Create clients once; a new http.Client/Transport per request defeats connection reuse.
26. Not closing (or draining) response bodies
Symptom: connection count and file descriptors climb; "too many open files"; TLS handshakes on every call.
resp, err := pspClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close() // always, even when you ignore the body
if resp.StatusCode != http.StatusOK {
// Drain (bounded) so the connection can return to the pool.
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
return fmt.Errorf("psp: unexpected status %d", resp.StatusCode)
}
The bodyclose linter catches missing Close calls. The database/sql equivalent: always defer rows.Close(), and set SetMaxOpenConns — the default pool size is unlimited.
Detection at a glance
Trade-offs
| Pitfall class | Caught by | Not caught by | Residual risk handled by |
|---|---|---|---|
| Lock copies, lost cancels, printf misuse | go vet (a subset also runs automatically in go test) | — | — |
| Unchecked errors, unclosed bodies/rows | errcheck, bodyclose, rowserrcheck, sqlclosecheck | Compiler | Code review |
| Missing context on HTTP calls | noctx, contextcheck | Compiler | Review, tracing gaps |
| Data races | -race (only executed paths) | Static tools | Concurrency tests, -count |
| Goroutine leaks | goleak in tests; goroutine metrics | Compiler, -race | Profiles in production |
| Float money, overflow | Review, custom linters (forbidigo on float64 in money packages) | Most tools | Property tests, reconciliation |
| Time zone / cut-off bugs | Tests with injected clocks | Static tools | Business-calendar test cases |
| Map order assumptions | -shuffle=on, randomized iteration surfaces flakes | Static tools | Deterministic output tests |
In practice
A CI configuration that catches most of this list:
# .golangci.yml (excerpt)
linters:
enable:
- govet
- staticcheck
- errcheck
- bodyclose
- noctx
- rowserrcheck
- sqlclosecheck
- contextcheck
- gosec
- errorlint # %w usage, errors.Is/As instead of ==
- exhaustive # missing cases in switches over enums
go vet ./...
golangci-lint run ./...
go test -race -shuffle=on -count=1 ./...
Plus: goleak.VerifyTestMain in packages that start goroutines; go 1.22+ (ideally current) in every go.mod so loop-variable and timer fixes apply; code review checklists for money types, time zones and timeouts (see Code Review & Engineering Standards).
Common pitfalls
Meta-pitfalls — mistakes made while fixing the ones above:
- Bumping the
goline without testing — 1.22 loop semantics and 1.23 timer semantics change behaviour; tests that relied on the old behaviour (rarely intentionally) can change. - Silencing linters globally instead of fixing or justifying with a targeted
//nolint:errcheck // reasoncomment. - Fixing leaks with bigger buffers — a buffer of 1,000 delays the leak instead of removing it.
- Wrapping everything in
recoverto stop crashes — hides concurrent-map-write bugs (which aren't even recoverable) and leaves corrupted state. - Replacing every map with
sync.Map"for safety" — slower and untyped for most workloads.
Interview angle
Most Go interviews include a "what does this print / what's wrong" round drawn from this list: append aliasing, range copies, typed nil errors, defer argument evaluation, loop-variable capture (and which version fixed it), unbuffered channel deadlocks, leaks on timeout paths, copied mutexes, concurrent map writes, missing HTTP timeouts.
A strong answer names the mechanism (shared backing array; interface (type, value) pair; defer evaluates arguments eagerly; goroutines must be able to exit), the symptom in production, the fix, and how you'd catch it automatically (vet, linter, -race, goleak). For bank and e-commerce roles, connect money pitfalls to reconciliation and time-zone pitfalls to settlement cut-offs.
Follow-ups: "Which of these does go vet catch?", "Why can't recover handle concurrent map writes?", "What changed in Go 1.22 and 1.23, and what does go.mod have to say?"
Red flags: not knowing the loop-variable change, believing time.After in loops is always a leak (or never), using floats for amounts "with rounding".
Self-check
1. Why does defer observeLatency(time.Since(start)) record ≈0, and what's the fix?
Arguments to a deferred call are evaluated when the defer statement executes, not when the deferred call runs. time.Since(start) is computed immediately after start. Defer a closure — defer func() { observeLatency(time.Since(start)) }() — so the expression runs at function exit.
2. A module with go 1.21 in go.mod is compiled with Go 1.26. Do goroutines started in a loop see per-iteration variables?
No. Loop-variable semantics follow the language version in go.mod, not the toolchain version; per-iteration variables need go 1.22 or later. Until the line is bumped, the old shared-variable behaviour applies.
3. Why is a 3 billion VND transfer a problem for int32, and how should the amount flow through your system?
int32 max is 2,147,483,647, so 3,000,000,000 wraps to a negative number on conversion — silently. Amounts should be int64 minor units end to end (Go structs, protobuf int64, SQL BIGINT/NUMERIC), with explicit range checks wherever a narrower type is unavoidable.
4. Name four errors in Go code that must never be ignored in a payments service, and why.
tx.Commit (otherwise you report success for unsaved data), rows.Err() after iteration (mid-stream failures look like end of results), Close/Flush on files and buffered writers you wrote (delayed write errors truncate settlement files), and errors from publishing events or outbox inserts (lost notifications and reconciliation breaks).
5. What changed for time.After in loops in Go 1.23, and is the rewrite with NewTimer still worthwhile?
Since Go 1.23 (with go 1.23+ in go.mod), unreferenced timers can be garbage-collected even if never stopped or fired, so time.After in a loop no longer accumulates memory until each timer fires; timer channels are also unbuffered, making Reset/Stop straightforward. A single reused timer is still clearer and avoids allocating a timer per iteration in hot loops.
6. Scenario: after a deploy, a service's file descriptors climb steadily and it starts failing with "too many open files". List the likely Go causes.
HTTP response bodies not closed (or not drained, preventing reuse), creating a new http.Client/Transport per request, defer f.Close() inside a long loop, sql.Rows not closed, or leaked goroutines each holding a connection. Check the goroutine profile and lsof counts by type; bodyclose/sqlclosecheck linters would have caught several of these.
7. Why does t1 == t2 fail for the same instant, and what should you use as a map key for times?
== compares the time.Time struct: wall clock, monotonic reading and *Location. The same instant in different locations, or with/without a monotonic reading, compares unequal. Use Equal for comparison and a normalised form (e.g. t.UTC() after Round(0)/Truncate, or UnixNano()) as a map key.
Exercise
Run a "bug bash" on your own code or a sample service:
- Enable the
.golangci.ymlabove plusgo vetand fix or justify every finding. - Write a failing test for at least eight pitfalls from this page (aliasing, typed nil, float money, defer argument evaluation, shadowed err, copied mutex, leak on timeout with
goleak, missingrows.Err), then fix the code so they pass. - Grep for
http.Get,http.DefaultClient,context.Background()inside handlers,float64in money packages, andtime.Now().Hour(); fix each occurrence. - Bump
go.modto the current Go version, run the full suite with-race -shuffle=on -count=3, and note any behaviour changes.
Done when: CI runs the linters and race detector on every PR, and each fixed pitfall has a regression test. More practice in Hands-on Go Labs.
Further reading
- Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them (Manning) — the most complete catalogue; this page overlaps with many of its chapters.
- Effective Go and Go Code Review Comments (go.dev).
- Go blog: "Fixing For Loops in Go 1.22" (David Chase, Russ Cox).
timepackage documentation — the Go 1.23 timer changes andasynctimerchanGODEBUG setting.- Go FAQ: "Why is my nil error value not equal to nil?"
- Go documentation: "Data Race Detector".
- golangci-lint documentation — linter descriptions (errcheck, bodyclose, noctx, rowserrcheck, errorlint).
- Katherine Cox-Buday, Concurrency in Go — leaks and channel ownership.
Related
- Go Fundamentals — the mechanics behind the data-structure pitfalls.
- Error Handling — wrapping, typed nils and logging once.
- Goroutines & Channels — leaks, deadlocks and closing rules.
- sync, atomic & context — mutexes, WaitGroup and context rules.
- Building Production Services — timeouts, bodies and pools configured correctly.
- Code Review & Engineering Standards — turning this list into a review checklist.
- Hands-on Go Labs — practise finding and fixing these bugs.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).