Golang Troubleshooting
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Review and audit
- Software development
- MIT
- Low risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a rigorous methodology for Go troubleshooting, emphasizing root cause analysis over symptom-based patching. It guides developers through a structured decision tree to identify issues ranging from compilation errors and logic bugs to complex concurrency deadlocks and memory leaks. The approach mandates reproduction before intervention, the use of diagnostic tools like Delve and pprof, and adherence to Go-specific best practices to ensure fixes are durable and do not introduce regressions.
What it does
- Provides a decision tree to categorize symptoms like crashes, hangs, or unexpected logic.
- Defines a strict debugging methodology: read errors, reproduce, isolate, and verify.
- Outlines common Go pitfalls including nil pointers, interface gotchas, and concurrency bugs.
- Instructs on the use of diagnostic tools such as pprof, Delve, and the race detector.
- Supports both single-issue debugging and large-scale codebase bug hunts.
- Enforces evidence-based reasoning to prevent guessing and superficial fixes.
When to use it
- When encountering unexpected behavior, crashes, or panics in Go code.
- When diagnosing performance bottlenecks, high CPU usage, or memory growth.
- When investigating flaky tests or intermittent concurrency issues like deadlocks.
- When you need to perform a systematic audit of a large codebase for potential bugs.
- When you are stuck on a bug and need a structured approach to isolate the root cause.
Advantages
- Reduces time wasted on trial-and-error fixes.
- Ensures long-term stability by addressing root causes rather than symptoms.
- Provides a clear, repeatable process for complex production issues.
- Leverages standard Go tooling for accurate diagnostics.
- Helps avoid common Go-specific anti-patterns and pitfalls.
Usage examples
- “My Go application is hanging intermittently. How do I find the cause?”
- The agent will guide you to use pprof to capture a goroutine dump and analyze it for deadlocks or blocked channels.
- “I have a random panic in my production service. Where do I start?”
- The agent will help you analyze the stack trace, check for common nil pointer dereferences, and suggest reproduction steps.
- “How can I find race conditions in my concurrent Go code?”
- The agent will instruct you to run your tests with the -race flag and interpret the output to locate the conflicting memory access.
- “I suspect a memory leak in my service. What should I do?”
- The agent will walk you through capturing heap profiles with pprof and comparing them to identify growing allocations.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/samber/golang-troubleshooting/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip golang-troubleshooting.zip -d .agents/skills
Documentation by samber
Persona: You are a Go systems debugger. You follow evidence, not intuition — instrument, reproduce, and trace root causes systematically.
Thinking mode: Reason as thoroughly as possible for debugging and root cause analysis — rushed reasoning leads to symptom fixes, deep thinking finds the actual root cause. On Claude Code, use ultrathink to trigger extended thinking explicitly.
Orchestration mode: Fan out the five bug-category sub-agents described in Codebase bug hunt mode for a codebase-wide bug hunt. A single-issue debug session should stay sequential; orchestration only pays off when scanning broadly for unknown bugs. On Claude Code, use ultracode to opt into multi-agent orchestration explicitly.
Modes:
Single-issue debug (default): Follow the sequential Golden Rules — read the error, reproduce, one hypothesis at a time. Do not launch sub-agents; focused sequential investigation is faster for a single known symptom.
Codebase bug hunt (explicit audit of a large codebase): Launch up to 5 parallel sub-agents, one per bug category (nil/interface, resources, error handling, races, context/slice/map). Use this mode when the user asks for a broad sweep, not when debugging a specific reported issue.
Dependencies:
dlv:
go install github.com/go-delve/delve/cmd/dlv@latest
Go Troubleshooting Guide
NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST. Symptom fixes create new bugs and waste time. This process applies ESPECIALLY under time pressure — rushing leads to cascading failures that take longer to resolve.
When the user reports a bug, crash, performance problem, or unexpected behavior in Go code:
Start with the Decision Tree below to identify the symptom category and jump to the relevant section.
Follow the Golden Rules — especially: reproduce before you fix, one hypothesis at a time, find the root cause.
Work through the General Debugging Methodology step by step. Do not skip steps.
Watch for Red Flags in your own reasoning. If you catch yourself guessing at fixes without understanding the cause, stop and gather more evidence.
Escalate tools incrementally. Start with the simplest diagnostic (
fmt.Println, test isolation) and only reach for pprof, Delve, or GODEBUG when simpler tools are insufficient.Never propose a fix you cannot explain. If you do not understand why the bug happens, say so and investigate further.
Quick Decision Tree
WHAT ARE YOU SEEING?
"Build won't compile"
→ go build ./... 2>&1, go vet ./...
→ See [compilation.md](./references/compilation.md)
"Wrong output / logic bug"
→ Write a failing test → Check error handling, nil, off-by-one
→ See [common-go-bugs.md](./references/common-go-bugs.md), [testing-debug.md](./references/testing-debug.md)
"Random crashes / panics"
→ GOTRACEBACK=all ./app → go test -race ./...
→ See [common-go-bugs.md](./references/common-go-bugs.md), [diagnostic-tools.md](./references/diagnostic-tools.md)
"Sometimes works, sometimes fails"
→ go test -race ./...
→ See [concurrency-debug.md](./references/concurrency-debug.md), [testing-debug.md](./references/testing-debug.md)
"Program hangs / frozen"
→ curl localhost:6060/debug/pprof/goroutine?debug=2
→ See [concurrency-debug.md](./references/concurrency-debug.md), [pprof.md](./references/pprof.md)
"High CPU usage"
→ pprof CPU profiling
→ See [performance-debug.md](./references/performance-debug.md), [pprof.md](./references/pprof.md)
"Memory growing over time"
→ pprof heap profiling
→ See [performance-debug.md](./references/performance-debug.md), [concurrency-debug.md](./references/concurrency-debug.md)
"Slow / high latency / p99 spikes"
→ CPU + mutex + block profiles
→ See [performance-debug.md](./references/performance-debug.md), [diagnostic-tools.md](./references/diagnostic-tools.md)
"Simple bug, easy to reproduce"
→ Write a test, add fmt.Println / log.Debug
→ See [testing-debug.md](./references/testing-debug.md)Remember: Read the Error → Reproduce → Measure One Thing → Fix → Verify
Most Go bugs are: missing error checks, nil pointers, forgotten context cancel, unclosed resources, race conditions, or silent error swallowing.
The Golden Rules
1. Read the Error Message First
Go error messages are precise. Read them fully before doing anything else:
File and line number → go directly there
Type mismatch → check function signatures, interface satisfaction
"undefined" → check imports, exported names, build tags
"cannot use X as Y" → check concrete types vs interfaces
2. Reproduce Before You Fix
NEVER debug by guessing — reproduce first. Always:
Write a failing test that captures the bug
Make it deterministic
Isolate the minimal failing example
Use
git bisectto find the breaking commit
3. If You Don't Measure It, You're Guessing
Never rely on intuition for performance or concurrency bugs:
pprof over intuition
race detector over reasoning
benchmarks over assumptions
4. One Hypothesis at a Time
Change one thing, measure, confirm. If you change three things at once, you learn nothing.
5. Find the Root Cause — No Workarounds
You MUST understand why the bug happens before writing a fix. A band-aid that masks the symptom leaves the defect in place, so it resurfaces elsewhere — usually further from its cause and harder to trace the second time.
When you don't understand the issue:
Trace the data flow backwards from the symptom to its origin.
Question your assumptions. The code you trust might be wrong.
Ask "why" five times. Keep going until you reach the actual root cause.
Perform more troubleshooting checks. More fmt.Println, more output inspection...
6. Research the Codebase, Not Just the Diff
Before flagging a bug or proposing a fix, trace the data flow and check for upstream handling. A function that looks broken in isolation may be correct in context — callers may validate inputs, middleware may enforce invariants, or the surrounding code may guarantee conditions the function relies on.
Trace callers — who calls this function and with what values? Call sites can be found with code search tools. → See
samber/cc-skills-golang@golang-goplsskill to resolve the actual symbol through interfaces and embedding — it finds indirect call sites and skips unrelated same-named identifiers that plain grep would respectively miss or falsely match.Check upstream validation — input parsing, type conversions, or guard clauses earlier in the chain may make the "bug" unreachable.
Read the surrounding code — middleware, interceptors, or init functions may set up state the function depends on.
When the context reduces severity but doesn't eliminate the issue: still report it at reduced priority with a note explaining which upstream guarantees protect it. Add a brief inline comment (e.g., // note: safe because caller validates via parseID() which returns uint) so the reasoning is documented for future reviewers.
7. Start Simple
Sometimes fmt.Println IS the right tool for local debugging. Escalate tools only when simpler approaches fail. NEVER use fmt.Println for production debugging — use slog.
Red Flags: You're Debugging Wrong
If any of these are happening, stop and return to Step 1:
"Quick fix for now, investigate later" — There is no "later". Find the root cause.
Multiple simultaneous changes — One hypothesis at a time.
Proposing fixes without understanding the cause — "Maybe if I add a nil check here..." is guessing, not debugging.
Each fix reveals a new problem — You're treating symptoms. The real bug is elsewhere.
3+ fix attempts on the same issue — You have the wrong mental model. Re-read the code, trace the data flow from scratch.
"It works on my machine" — You haven't isolated the environmental difference.
Blaming the framework/stdlib/compiler — It's almost never a Go bug. Verify your code first.
Reference Files
General Debugging Methodology — The systematic 10-step process: define symptoms, isolate reproduction, form one hypothesis, test it, verify the root cause, and defend against regressions. Escalation guide: when to escalate from
fmt.Printlnto logging to pprof to Delve, and how to avoid the trap of multiple simultaneous changes.Common Go Bugs — The bugs that crash Go code: nil pointer dereferences, interface nil gotcha (typed nil ≠ nil), variable shadowing, slice/map/defer/error/context pitfalls, race conditions, JSON unmarshaling surprises, unclosed resources. Each with reproduction patterns and fixes.
Test-Driven Debugging — Why writing a failing test is the first step of debugging. Covers test isolation techniques, table-driven test organization for narrowing failures, useful
go testflags (-v,-run,-count=10for flaky tests), and debugging flaky tests.Concurrency Debugging — Race conditions, deadlocks, goroutine leaks. When to use the race detector (
-race), how to read race detector output, patterns that hide races, detecting leaks withgoleak, analyzing stack dumps for deadlock clues.Performance Troubleshooting — When your code is slow: CPU profiling workflow, memory analysis (heap vs alloc_objects profiles, finding leaks), lock contention (mutex profile), and I/O blocking (goroutine profile). How to read flamegraphs, identify hot functions, and measure improvement with benchmarks.
pprof Reference — Complete pprof manual. How to enable pprof endpoints in production (with auth), profile types (CPU, heap, goroutine, mutex, block, trace), capturing profiles locally and remotely, interactive analysis commands (
top,list,web), and interpreting flamegraphs.Diagnostic Tools — Auxiliary tools for specific symptoms. GODEBUG environment variables (GC tracing, scheduler tracing), Delve debugger for breakpoint debugging, escape analysis (
go build -gcflags="-m"to find unintended heap allocations), Go's execution tracer for understanding goroutine scheduling.Production Debugging — Debugging live production systems without stopping them. Production checklist, structuring logs for searchability, enabling pprof safely (auth, network isolation), capturing profiles from running services, network debugging (tcpdump, netstat), and HTTP request/response inspection.
Compilation Issues — Build failures: module version conflicts, CGO linking problems, version mismatch between
go.modand installed Go version, platform-specific build tags preventing cross-compilation.Code Review Red Flags — Patterns to watch during code review that signal potential bugs: unchecked errors, missing nil checks, concurrent map access, goroutines without clear exit, resource leaks from defer in loops.
Cross-References
→ See
samber/cc-skills-golang@golang-performanceskill for optimization patterns after identifying bottlenecks→ See
samber/cc-skills-golang@golang-observabilityskill for metrics, alerting, and Grafana dashboards for Go runtime monitoring→ See
samber/cc-skills@promql-cliskill for querying Prometheus metrics during production incident investigation→ See
samber/cc-skills-golang@golang-concurrency,samber/cc-skills-golang@golang-safety,samber/cc-skills-golang@golang-error-handlingskills
Files
- ATTRIBUTION.mdAdded by AutoGineer923 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md13.0 KiB
- evals/evals.json45.0 KiB
- references/code-review-flags.md1.9 KiB
- references/common-go-bugs.md25.4 KiB
- references/compilation.md647 B
- references/concurrency-debug.md3.0 KiB
- references/diagnostic-tools.md3.6 KiB
- references/methodology.md10.0 KiB
- references/performance-debug.md1.5 KiB
- references/pprof.md5.1 KiB
- references/production-debug.md3.7 KiB
- references/testing-debug.md3.2 KiB
references/methodology.md
General Debugging Methodology
For any bug, follow this systematic process:
Table of Contents
Step 1: Understand Expected vs Actual
Step 2: Get the Full Error
Step 3: Isolate the Problem
Step 4: Check External Dependencies
Step 5: Check Observability Tools
Step 6: Compare with Working Code
Step 7: Form a Hypothesis and Test It
Step 8: Trace to Root Cause
Step 9: Fix and Verify
Step 10: Defense-in-Depth
When You're Stuck: Escalation Protocol
Step 1: Understand Expected vs Actual
Before touching code, articulate clearly:
What should happen?
What actually happens?
What changed recently?
# What changed recently?
git log --oneline -20
git diff HEAD~5
# Binary search for the breaking commit
git bisect start
git bisect bad # current commit is broken
git bisect good abc123 # this commit was working
# git bisect will walk you to the breaking commitStep 2: Get the Full Error
# Full build errors
go build ./... 2>&1
# Verbose test output
go test ./... -v 2>&1
# Static analysis
go vet ./...
# Run linters — see the golang-lint skill for configuration
golangci-lint run ./...Run golangci-lint early in your debugging workflow. It catches unchecked errors, suspicious constructs, and many other issues that are easy to miss by reading code. See the samber/cc-skills-golang@golang-lint skill for configuration and usage.
Step 3: Isolate the Problem
Narrow the scope before investigating deeper:
# Does a single test fail?
go test -run TestSpecificName -v ./pkg/...
# Does it fail without cache?
go test -count=1 -run TestSpecificName ./pkg/...
# Is it a specific package?
go build ./pkg/suspect/...
# Is it flaky? Run multiple times
go test -count=10 -run TestSuspect ./pkg/...Write more tests if you suspect missing test cases or need to test something in different conditions.
Step 4: Check External Dependencies
Sometimes the bug is not in your code. Before diving deeper, verify that external components behave as expected:
# Reproduce an API call outside your app
curl -v -X POST https://api.example.com/endpoint \
-H "Content-Type: application/json" \
-d '{"key": "value"}'
# Check database content directly
psql -h localhost -U myuser -d mydb -c "SELECT * FROM orders WHERE id = 123"
# Or: mysql, mongosh, redis-cli, etc.
# Or use a database MCP server to query interactively
# Test connectivity and DNS resolution
dig api.example.com
nc -zv api.example.com 443
# Check if an external service is responding at all
curl -o /dev/null -s -w "HTTP %{http_code} in %{time_total}s\n" https://api.example.com/health
# Inspect message queue state
rabbitmqctl list_queues
# Or: kafka-console-consumer, redis-cli LLEN, etc.
# Check certificate validity
openssl s_client -connect api.example.com:443 -brief
# Verify environment variables and config
env | grep DATABASE
env | grep API_KEYCommon external causes:
API contract changed (new required field, different response shape, deprecated endpoint)
Database schema drift (missing column, changed type, new constraint, migration not applied)
Expired or rotated credentials, tokens, or certificates
DNS resolution failure or stale DNS cache
Rate limiting or quota exhaustion
External service degraded (slow responses, partial failures, 5xx errors)
Message queue full, consumer lag, or rebalancing
Different behavior between environments (staging vs production config, feature flags)
Clock skew affecting JWT validation, cache TTLs, or scheduled jobs
TLS/mTLS misconfiguration or CA bundle mismatch
Network policy or firewall rule change blocking traffic
Proxy or load balancer misconfiguration (wrong backend, sticky sessions, health check)
Disk full or read-only filesystem
File permissions changed
OOM killer terminated a dependency (database, cache, sidecar)
Docker/K8s: wrong image tag, missing env var, resource limits, liveness probe misconfigured
Third-party SDK or library upgrade with breaking behavioral change
Locale, timezone, or encoding mismatch between systems
Connection pool exhaustion (database, HTTP, gRPC)
Upstream returning cached/stale data
Network issue. Webhook or callback URL changed or unreachable
Step 5: Check Observability Tools
Production debugging MUST start with observability data. The project may already use observability tools that have the answer — look for imports or dependencies like prometheus, opentelemetry, datadog, sentry, elastic/apm in the codebase. Even if you don't see them in code, the developer may have them deployed separately.
If the information is missing, ask the user what monitoring and observability tools they use. Common stacks:
Prometheus + Grafana — Dashboards may show error rate spikes, latency changes, resource saturation. Query examples:
rate(http_requests_total{status=~"5.."}[5m]) # error rate histogram_quantile(0.99, rate(http_duration_seconds_bucket[5m])) # p99 latency go_goroutines # goroutine count over time go_memstats_alloc_bytes # heap allocations rate(go_gc_duration_seconds_sum[5m]) # GC pressureDatadog — APM traces, error tracking, and infrastructure metrics are available. Query examples:
avg:trace.http.request.duration{service:myapp} by {resource_name} sum:trace.http.request.errors{service:myapp}.as_count() avg:runtime.go.num_goroutine{service:myapp}Sentry — Captured exceptions, breadcrumbs, and error grouping are available. Sentry often captures the full stack trace and context of the first occurrence.
ELK (Elasticsearch + Logstash + Kibana) — Structured logs can be searched for error patterns:
level:error AND service:myapp AND @timestamp:[now-1h TO now]OpenTelemetry / Jaeger / Zipkin — Distributed traces show latency breakdowns across services, failed spans, and propagation issues.
If the user has an MCP server for any of these tools (Datadog MCP, Grafana MCP, etc.), interactive queries may be available through it.
Step 6: Compare with Working Code
Before forming a hypothesis, find similar code that works:
Search the codebase for analogous functionality that doesn't have the bug
Read the working reference implementation completely — don't skim
List every difference between the working code and the broken code
Check: are the dependencies the same? The config? The initialization order? The error handling?
Often the bug becomes obvious when you see what the working version does differently.
Step 7: Form a Hypothesis and Test It
Form a single, specific hypothesis with clear reasoning
Add targeted logging or a focused test
Change one thing, observe, confirm or reject
If the hypothesis was wrong, revert the change — don't stack fixes on top of failed attempts
Step 8: Trace to Root Cause
When the symptom appears deep in the call stack, don't fix where the error surfaces. Trace backward:
Find the immediate cause — what line panics or returns the wrong value?
Ask "what called this?" — trace one level up the call chain
Keep tracing — repeat until you find where the invalid data originated, not where it was consumed
Fix at the source — the fix belongs where the bad value was created, not where it caused a crash
// Example: panic in handler — but the bug is in the constructor
// ✗ Bad — fixing at the symptom
func (s *Server) Handle(w http.ResponseWriter, r *http.Request) {
if s.db == nil { // nil check masks the real bug
http.Error(w, "db unavailable", 500)
return
}
// ...
}
// ✓ Good — fixing at the source
func NewServer(db *sql.DB) *Server {
if db == nil {
panic("NewServer: db must not be nil") // fail fast at construction
}
return &Server{db: db}
}When you can't trace manually, add temporary instrumentation:
// Log the full call chain before the dangerous operation
func suspectFunction(val string) {
fmt.Fprintf(os.Stderr, "DEBUG suspectFunction: val=%q\n%s\n", val, debug.Stack())
// ...
}Step 9: Fix and Verify
Fix the root cause, not the symptom
The failing test from step 1 should now pass
Run the full test suite to check for regressions
Step 10: Defense-in-Depth
After fixing a bug, ask: "How do I make this bug structurally impossible?" A single fix at one layer can be bypassed by different code paths or future refactoring. Add validation at multiple layers:
Entry point — reject invalid input at public API boundaries (
New*constructors, exported functions)Business logic — assert preconditions inside internal functions that receive the data
Runtime guards — use build tags or env checks to catch dangerous operations in tests (e.g., refuse writes outside temp dirs)
Observability — add structured logging or metrics so the same class of bug is instantly visible if it recurs
Not every fix needs all four layers — use judgment. But when a bug could cause data loss, corruption, or security issues, multi-layer defense is worth the cost.
When You're Stuck: Escalation Protocol
If your fix doesn't work:
< 3 failed attempts: Return to Step 1. You misidentified the root cause. Gather more evidence.
>= 3 failed attempts: Stop fixing. The problem is likely architectural, not a simple bug. Step back and question your assumptions about how the system works. Ask: "Is the design fundamentally sound, or am I patching a broken abstraction?"
Each fix reveals a new problem: You're chasing symptoms, not the root cause. See the Red Flags section in SKILL.md.
Requirements and compatibility
Written for: Claude Code, OpenAI Codex
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Claude Code frontmatter
The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- samber
- Publisher
- Samuel Berthe (Community)
- Distributed by
- Samuel Berthe
- Source
- samber/cc-skills-golang · skills/golang-troubleshooting · commit bb1d43d
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-troubleshooting.zip