{"data":{"slug":"discovered-522d1f8f7c45024cee339c57f669a94e996468db63c75c34","title":"Go Performance Review for Artifact Registry","summary":"Review Go code for performance issues in the Artifact Registry service, focusing on allocation, concurrency, GC, and hot-path packages. Identify and fix unnecessary heap allocations, preallocation gaps, and opportunities for optimization using patterns from goperf.dev.","url":"https:\/\/skillshunter.net\/skills\/discovered-522d1f8f7c45024cee339c57f669a94e996468db63c75c34","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-522d1f8f7c45024cee339c57f669a94e996468db63c75c34","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-522d1f8f7c45024cee339c57f669a94e996468db63c75c34.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-522d1f8f7c45024cee339c57f669a94e996468db63c75c34\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Before reviewing, ensure that profiling data exists or can be gathered. Run benchmarks with allocation reporting using `GOTOOLCHAIN=auto go test -bench=BenchmarkName -benchmem -count=3 .\/path\/to\/package\/...` and escape analysis with `GOTOOLCHAIN=auto go build -gcflags=\"-m\" .\/path\/to\/package\/... 2>&1 | head -100`. Hot-path packages are defined in the `review-branch` setup step 3 table.","instructions":"---\nname: go-perf\ndescription: Go performance review for the Artifact Registry service. Covers allocation, concurrency, GC, networking, database, and HTTP patterns with patterns from goperf.dev, scoped to AR's hot-path packages as `review-branch` defines them. Use before merging changes to hot-path packages or when investigating latency, throughput, or memory regressions.\n---\n\n# Go Performance Review (Artifact Registry)\n\nReview Go code for performance issues using patterns from\n[goperf.dev](https:\/\/goperf.dev\/), scoped to the Artifact Registry service.\nThe standard is production-grade: this is a high-throughput service backing\ncontainer, Maven, and npm artifact distribution, where allocation churn,\nlock contention, and unbounded I\/O all surface at production traffic.\n\n## When to use\n\n1. Reviewing a change that touches a hot-path package.\n1. Investigating a measured regression (latency, throughput, allocation rate).\n1. Designing a new feature on a hot path and wanting to spot allocation or\n   contention issues before they ship.\n\nHot-path packages are the ones the `hot-path` row of the Setup step 3\ntable in `~\/.claude\/skills\/review-branch\/SKILL.md` names. Phase 6 of\n`review-branch` and this skill share that one definition, so it is not\nrepeated here.\n\nThe CLI in `cmd\/` is not a hot path. Treat findings there as low priority\nunless the user asks for a comprehensive review.\n\n## Profile first\n\nBefore recommending changes, check whether profiling data exists or can\nbe gathered.\n\n1. Look for benchmarks in `*_test.go` files near the target code (`Benchmark*`\n   functions).\n1. If benchmarks exist, run them with allocation reporting:\n\n   ```bash\n   GOTOOLCHAIN=auto go test -bench=BenchmarkName -benchmem -count=3 .\/path\/to\/package\/...\n   ```\n\n1. Run escape analysis on the target package:\n\n   ```bash\n   GOTOOLCHAIN=auto go build -gcflags=\"-m\" .\/path\/to\/package\/... 2>&1 | head -100\n   ```\n\n1. Record the baseline. All recommendations should reference this data\n   where available.\n\nIf no benchmarks exist and the target is a hot path, note it as a finding:\n\"No benchmarks cover this path. Write benchmarks before optimizing.\"\n\n## Read and understand\n\nRead the target code thoroughly. Identify:\n\n1. What the code does (request handler, blob upload path, GC worker, etc.).\n1. Whether it runs per-request, per-connection, periodically, or once.\n1. What the hot path is \u2014 the code that runs most frequently or with the\n   tightest latency requirements.\n\nDo not make recommendations about code you have not read.\n\n## Analysis categories\n\nWork through each category below. Skip categories that do not apply. For\neach finding, cite the file and line, explain the issue, and show a concrete\nfix.\n\n### 1. Allocation and GC pressure\n\nLook for patterns that create unnecessary heap allocations or GC load.\n\n**Check for:**\n\n1. **Escape analysis failures.** Variables that escape to heap unnecessarily.\n   Returning pointers to local variables, capturing variables in closures,\n   converting to `interface{}`, assigning to global variables. Cross-reference\n   with `-gcflags=\"-m\"` output.\n1. **Missing preallocation.** Slices and maps grown incrementally in loops\n   instead of preallocated with known or estimable capacity.\n1. **`sync.Pool` opportunities.** Short-lived, reusable objects (buffers,\n   scratch memory, request state) allocated repeatedly in hot paths. Pool\n   candidates must be safely resettable. Pattern:\n\n   ```go\n   buf := pool.Get().(*bytes.Buffer)\n   buf.Reset()\n   defer pool.Put(buf)\n   ```\n\n   `sync.Pool` gives ~20x throughput improvement for buffer reuse\n   (864 ns\/op \u2192 42 ns\/op in goperf.dev benchmarks).\n1. **Unnecessary copies.** Passing large structs by value, copying byte\n   slices when a slice view suffices, string-to-byte conversions in loops.\n   Sub-slicing is zero-copy since slices reference the underlying array.\n1. **String concatenation in loops.** Use `strings.Builder` or `bytes.Buffer`\n   instead of `+` or `fmt.Sprintf` in loops.\n1. **`fmt.Sprintf` in hot paths.** `fmt.Sprintf` allocates. For simple\n   int-to-string, use `strconv.Itoa`. For error formatting in hot paths,\n   consider pre-allocated error values.\n\n**Do NOT recommend:**\n\n1. Pooling objects with complex teardown or low reuse rates.\n1. Forcing stack allocation when it compromises readability for negligible gain.\n1. Preallocating when the size is genuinely unknown and the slice is small.\n\n### 2. Struct layout and data access\n\n**Check for:**\n\n1. **Field alignment waste.** Struct fields ordered so padding bytes are\n   inserted between fields. Reorder fields from largest to smallest alignment\n   requirement.\n1. **Hot\/cold field separation.** Frequently accessed fields scattered across\n   cache lines when they could be grouped.\n1. **False sharing in concurrent access.** Multiple goroutines writing to\n   fields in the same cache line without padding.\n\n**Only flag alignment issues when:**\n\n1. The struct is allocated in volume (thousands+ instances), or\n1. The struct appears in a hot path confirmed by profiling.\n\n### 3. Concurrency patterns\n\n**Check for:**\n\n1. **Unbounded goroutine spawning.** `go func()` in a loop without\n   backpressure. Recommend worker pools with channel-based task queues or\n   a semaphore (buffered channel of `struct{}`).\n1. **Missing context propagation.** Long-running operations without\n   `context.Context` for cancellation. AR's convention is `context.Context`\n   as the first parameter on blocking functions.\n1. **Lock contention.** `sync.Mutex` protecting hot paths where\n   `sync.RWMutex`, `sync\/atomic`, or lock-free structures would reduce\n   contention. Read-heavy workloads benefit from `RWMutex`.\n1. **Lazy initialization without `sync.Once`.** Double-checked locking or\n   init-on-first-use patterns that should use `sync.Once`.\n1. **Channel misuse.** Unbuffered channels causing unnecessary goroutine\n   blocking. Oversized buffered channels wasting memory.\n1. **Atomic versus mutex.** For simple counters or flags, `atomic.Int64`\n   or `atomic.Bool` avoids mutex overhead entirely.\n\n**Worker pool sizing guidance:**\n\n1. CPU-bound: `runtime.NumCPU()` or `runtime.GOMAXPROCS(0)`.\n1. I\/O-bound: can exceed core count since workers block on I\/O.\n1. Oversizing causes scheduler contention, context switching, cache thrashing.\n\n### 4. I\/O and buffering\n\n**Check for:**\n\n1. **Unbuffered I\/O.** Reading or writing to `net.Conn`, files, or HTTP\n   bodies without `bufio.Reader` or `bufio.Writer`. Buffered writes yield up\n   to 50x throughput gains on network connections (goperf.dev: 33.8 MiB \u2192\n   1661 MiB on 10K connections).\n1. **Missing batching.** Many small writes where batching would reduce\n   syscall overhead. Many small DB inserts where a single batch insert would\n   reduce round trips.\n1. **Large reads into memory.** Reading entire files or responses into\n   `[]byte` when streaming with `io.Reader` or `io.Writer` would avoid the\n   allocation. Critical for blob upload and download paths.\n1. **Zero-copy missed opportunities.** Copying data between `io.Reader` and\n   `io.Writer` instead of using `io.Copy` (which can use `sendfile` or\n   `splice` under the hood). Copying byte slices when sub-slicing the same\n   backing array suffices.\n\n### 5. HTTP server and handler patterns\n\n**Check for:**\n\n1. **Per-request allocations in middleware.** Middleware that allocates\n   buffers, maps, or structs on every request. Move to `sync.Pool` or\n   pre-allocate at server startup.\n1. **Response body buffering.** Writing response bodies incrementally\n   versus buffering then writing. For known-size responses, set\n   `Content-Length` to avoid chunked encoding overhead.\n1. **JSON encoding allocations.** `json.Marshal` allocates a new `[]byte`\n   each call. For high-throughput endpoints, use `json.NewEncoder(w)` to\n   write directly to the response writer, or pool `bytes.Buffer` for cases\n   where you need the bytes.\n1. **Request body not closed or drained.** Not draining `r.Body` before\n   closing prevents HTTP connection reuse. Use\n   `io.Copy(io.Discard, r.Body)` when the body is not fully read.\n1. **`http.Error` in hot paths.** `http.Error` calls `fmt.Fprintln`\n   internally. For high-throughput error responses, pre-format error bodies.\n1. **Handler struct allocations.** If handler structs are allocated\n   per-request in dispatchers, check whether they can be reused or simplified.\n1. **Blob streaming.** OCI blob upload and download must stream \u2014 never\n   buffer a whole blob in memory. A single blob can be hundreds of MiB or\n   more. Use `io.Copy` with bounded buffers and check for premature\n   `ReadAll`.\n\n### 6. Database patterns\n\nAR uses PostgreSQL exclusively (`internal\/datastore\/`). The service is\ndatabase-only by design \u2014 there is no filesystem dual-path.\n\n**Check for:**\n\n1. **N+1 queries.** Fetching a list then querying per-item in a loop. Batch\n   into a single query with `WHERE x IN (...)` or use joins.\n1. **Missing connection pool tuning.** Default `sql.DB` pool settings may\n   be wrong for the workload. Check `SetMaxOpenConns`, `SetMaxIdleConns`,\n   `SetConnMaxLifetime`.\n1. **Scanning into `interface{}`.** Using `sql.Rows.Scan` with interface\n   targets instead of typed destinations adds allocation and type assertion\n   overhead.\n1. **Prepared statement reuse.** Queries executed repeatedly without\n   `sql.Stmt` preparation. `database\/sql` caches prepared statements\n   per-connection, so this matters most for connection-pool-heavy workloads.\n1. **Transaction scope too wide.** Transactions held open across I\/O\n   operations (HTTP calls, file reads) instead of scoped to the minimal DB\n   operations.\n1. **Large result sets without `LIMIT`.** Queries that could return unbounded\n   rows without pagination.\n1. **Missing context on queries.** `db.Query()` without context prevents\n   cancellation. Always use `db.QueryContext(ctx, ...)`.\n\n### 7. Networking\n\n**Check for:**\n\n1. **Missing connection deadlines.** No `SetReadDeadline` or\n   `SetWriteDeadline` on long-lived connections, risking goroutine leaks\n   from stalled peers.\n1. **Missing TCP tuning.** `TCP_NODELAY` not set for latency-sensitive\n   paths. Connection reuse not configured.\n1. **Goroutine leaks.** Connections without proper lifecycle management\n   (heartbeats, idle timeouts, cleanup on context cancellation).\n1. **HTTP client reuse.** Creating new `http.Client` or `http.Transport`\n   per request instead of reusing with connection pooling.\n1. **TLS overhead.** TLS session resumption not enabled. Certificate\n   verification happening per-connection in high-throughput paths.\n1. **OS-level limits.** For high-connection-count services, check guidance\n   on file descriptor limits, `net.core.somaxconn`, and TCP stack tuning.\n\n### 8. GC tuning\n\n**Check for:**\n\n1. **Default `GOGC` without measurement.** If GC is confirmed as a\n   bottleneck via pprof, suggest tuning `GOGC`. Higher values trade memory\n   for less frequent collection. Default 100 is correct for most workloads.\n1. **Missing `GOMEMLIMIT` in containers.** AR runs on GKE via Runway.\n   Containerized services without `GOMEMLIMIT` risk OOM kills. Set to\n   ~80% of container memory limit.\n1. **`GOGC=off` without `GOMEMLIMIT`.** Disabling GC pacing without a\n   memory ceiling is dangerous.\n1. **Weak references (Go 1.24+).** For caches and deduplication maps,\n   `weak.Make` allows entries to be collected when no strong references\n   remain.\n\n**Do NOT recommend GC tuning unless:**\n\n1. pprof or runtime metrics confirm GC is the bottleneck, or\n1. the user has specifically asked about GC behavior.\n\n### 9. Compiler hints\n\n**Check for:**\n\n1. **Inline candidates.** Small, hot functions that the compiler might not\n   inline due to complexity budget. Check with `go build -gcflags=\"-m\"` for\n   \"cannot inline\" messages.\n1. **Bounds check elimination.** Patterns where adding an explicit length\n   check before a loop would let the compiler eliminate per-iteration bounds\n   checks.\n1. **Build tags for architecture-specific paths.** Performance-critical code\n   that could benefit from architecture-specific implementations.\n\n## Propose benchmarks\n\nFor each high-severity finding, write a benchmark that would demonstrate the\nimprovement. Use table-driven benchmark style:\n\n```go\nfunc BenchmarkXxx(b *testing.B) {\n    b.ReportAllocs()\n    for i := 0; i < b.N; i++ {\n        \/\/ code under test\n    }\n}\n```\n\n## Output format\n\nPresent findings grouped by category:\n\n```plaintext\n## Go Performance Review: <target>\n\n### Baseline\n- Existing benchmarks: <list or \"none found\">\n- Escape analysis: <N heap escapes in target package>\n- Hot path: <description>\n\n### Allocation & GC Pressure (N findings)\n- **file.go:42** \u2014 `bytes.NewBuffer` in request handler allocates per-call.\n  Use sync.Pool:\n  ```go\n  buf := bufPool.Get().(*bytes.Buffer)\n  buf.Reset()\n  defer bufPool.Put(buf)\n  ```\n\n### Concurrency (N findings)\n- **server.go:118** \u2014 Unbounded `go handle(conn)` in accept loop.\n  Add worker pool with semaphore channel.\n\n### Proposed Benchmarks\n- `BenchmarkBlobUpload` \u2014 measures allocation reduction from sync.Pool change\n\n### Summary\nN total findings across M categories.\nTop priority: <the single most impactful change and why>\n```\n\n**Severity ranking:**\n\n1. **High:** Unbounded allocations in hot paths, N+1 queries, goroutine\n   leaks, missing connection deadlines, unbuffered network I\/O on blob paths.\n1. **Medium:** Suboptimal pool usage, struct alignment in volume types,\n   missing preallocation, wide transaction scope, missing connection pool\n   tuning.\n1. **Low:** Compiler hints, cold-path allocations, style-level improvements.\n\n## Rules\n\n1. Every recommendation must be backed by a specific code pattern from the\n   review, not a general best practice.\n1. Do not recommend optimizations for code that is not in a hot path unless\n   the user asked for a comprehensive review.\n1. Do not recommend `unsafe` package usage.\n1. State when profiling is needed to confirm an issue rather than asserting\n   impact without evidence. \"This looks like it allocates per-request, but\n   run `go test -bench -benchmem` to confirm\" is better than \"this allocates\n   per-request.\"\n1. Reference [goperf.dev](https:\/\/goperf.dev\/) sections for further reading\n   when relevant (e.g., \"See goperf.dev\/01-common-patterns\/object-pooling\/\n   for sync.Pool benchmarks\").\n1. Respect the conventions in `docs\/dev\/go-style.md` and AGENTS.md. Do not\n   suggest changes that conflict with established project patterns (for\n   example, do not suggest changing the error handling pattern in code that\n   uses error accumulators).\n","use_cases":["Reviewing changes to hot-path packages for performance improvements","Investigating latency or throughput regressions in production","Designing new features on hot paths to preempt performance issues"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/gitlab.com\/radbatnag\/claude-skills\/-\/blob\/05b55872e4e98b79bc052be748b3abd6dccbabe6\/skills\/go-perf\/SKILL.md","source_commit":"05b55872e4e98b79bc052be748b3abd6dccbabe6","license":null,"version":null,"listing_approved_at":"2026-11-28","created_at":"2026-11-28T08:00:04.000000Z","updated_at":"2026-11-28T18:37:52.000000Z","seo_title":"Go Performance Review for Artifact Registry","seo_description":"Optimize Go code for the Artifact Registry service by identifying allocation, concurrency, and GC issues. Use patterns from goperf.dev to improve performance in hot-path,","seo_keywords":["Go performance review","Artifact Registry optimization","Go allocation analysis","sync.Pool usage","Go escape analysis","hot-path code review"]}}