# Go Performance Review for Artifact Registry

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.

**Canonical 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

**Instructions download URL:** https://skillshunter.net/skills/discovered-522d1f8f7c45024cee339c57f669a94e996468db63c75c34/download

**Category:** Software & Development

**Source URL:** https://gitlab.com/radbatnag/claude-skills/-/blob/05b55872e4e98b79bc052be748b3abd6dccbabe6/skills/go-perf/SKILL.md

**Source commit:** 05b55872e4e98b79bc052be748b3abd6dccbabe6

**Listing approved at:** 2026-11-28

**Created at:** 2026-11-28T08:00:04.000000Z

**Updated at:** 2026-11-28T18:37:52.000000Z

## Catalog information

The following descriptions are catalog information. Listing approval does not mean the skill has been tested or is safe for every environment.

### Editor's 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.

### When to use it

- 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

## Skill instructions

---
name: go-perf
description: 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.
---

# Go Performance Review (Artifact Registry)

Review Go code for performance issues using patterns from
[goperf.dev](https://goperf.dev/), scoped to the Artifact Registry service.
The standard is production-grade: this is a high-throughput service backing
container, Maven, and npm artifact distribution, where allocation churn,
lock contention, and unbounded I/O all surface at production traffic.

## When to use

1. Reviewing a change that touches a hot-path package.
1. Investigating a measured regression (latency, throughput, allocation rate).
1. Designing a new feature on a hot path and wanting to spot allocation or
   contention issues before they ship.

Hot-path packages are the ones the `hot-path` row of the Setup step 3
table in `~/.claude/skills/review-branch/SKILL.md` names. Phase 6 of
`review-branch` and this skill share that one definition, so it is not
repeated here.

The CLI in `cmd/` is not a hot path. Treat findings there as low priority
unless the user asks for a comprehensive review.

## Profile first

Before recommending changes, check whether profiling data exists or can
be gathered.

1. Look for benchmarks in `*_test.go` files near the target code (`Benchmark*`
   functions).
1. If benchmarks exist, run them with allocation reporting:

   ```bash
   GOTOOLCHAIN=auto go test -bench=BenchmarkName -benchmem -count=3 ./path/to/package/...
   ```

1. Run escape analysis on the target package:

   ```bash
   GOTOOLCHAIN=auto go build -gcflags="-m" ./path/to/package/... 2>&1 | head -100
   ```

1. Record the baseline. All recommendations should reference this data
   where available.

If no benchmarks exist and the target is a hot path, note it as a finding:
"No benchmarks cover this path. Write benchmarks before optimizing."

## Read and understand

Read the target code thoroughly. Identify:

1. What the code does (request handler, blob upload path, GC worker, etc.).
1. Whether it runs per-request, per-connection, periodically, or once.
1. What the hot path is — the code that runs most frequently or with the
   tightest latency requirements.

Do not make recommendations about code you have not read.

## Analysis categories

Work through each category below. Skip categories that do not apply. For
each finding, cite the file and line, explain the issue, and show a concrete
fix.

### 1. Allocation and GC pressure

Look for patterns that create unnecessary heap allocations or GC load.

**Check for:**

1. **Escape analysis failures.** Variables that escape to heap unnecessarily.
   Returning pointers to local variables, capturing variables in closures,
   converting to `interface{}`, assigning to global variables. Cross-reference
   with `-gcflags="-m"` output.
1. **Missing preallocation.** Slices and maps grown incrementally in loops
   instead of preallocated with known or estimable capacity.
1. **`sync.Pool` opportunities.** Short-lived, reusable objects (buffers,
   scratch memory, request state) allocated repeatedly in hot paths. Pool
   candidates must be safely resettable. Pattern:

   ```go
   buf := pool.Get().(*bytes.Buffer)
   buf.Reset()
   defer pool.Put(buf)
   ```

   `sync.Pool` gives ~20x throughput improvement for buffer reuse
   (864 ns/op → 42 ns/op in goperf.dev benchmarks).
1. **Unnecessary copies.** Passing large structs by value, copying byte
   slices when a slice view suffices, string-to-byte conversions in loops.
   Sub-slicing is zero-copy since slices reference the underlying array.
1. **String concatenation in loops.** Use `strings.Builder` or `bytes.Buffer`
   instead of `+` or `fmt.Sprintf` in loops.
1. **`fmt.Sprintf` in hot paths.** `fmt.Sprintf` allocates. For simple
   int-to-string, use `strconv.Itoa`. For error formatting in hot paths,
   consider pre-allocated error values.

**Do NOT recommend:**

1. Pooling objects with complex teardown or low reuse rates.
1. Forcing stack allocation when it compromises readability for negligible gain.
1. Preallocating when the size is genuinely unknown and the slice is small.

### 2. Struct layout and data access

**Check for:**

1. **Field alignment waste.** Struct fields ordered so padding bytes are
   inserted between fields. Reorder fields from largest to smallest alignment
   requirement.
1. **Hot/cold field separation.** Frequently accessed fields scattered across
   cache lines when they could be grouped.
1. **False sharing in concurrent access.** Multiple goroutines writing to
   fields in the same cache line without padding.

**Only flag alignment issues when:**

1. The struct is allocated in volume (thousands+ instances), or
1. The struct appears in a hot path confirmed by profiling.

### 3. Concurrency patterns

**Check for:**

1. **Unbounded goroutine spawning.** `go func()` in a loop without
   backpressure. Recommend worker pools with channel-based task queues or
   a semaphore (buffered channel of `struct{}`).
1. **Missing context propagation.** Long-running operations without
   `context.Context` for cancellation. AR's convention is `context.Context`
   as the first parameter on blocking functions.
1. **Lock contention.** `sync.Mutex` protecting hot paths where
   `sync.RWMutex`, `sync/atomic`, or lock-free structures would reduce
   contention. Read-heavy workloads benefit from `RWMutex`.
1. **Lazy initialization without `sync.Once`.** Double-checked locking or
   init-on-first-use patterns that should use `sync.Once`.
1. **Channel misuse.** Unbuffered channels causing unnecessary goroutine
   blocking. Oversized buffered channels wasting memory.
1. **Atomic versus mutex.** For simple counters or flags, `atomic.Int64`
   or `atomic.Bool` avoids mutex overhead entirely.

**Worker pool sizing guidance:**

1. CPU-bound: `runtime.NumCPU()` or `runtime.GOMAXPROCS(0)`.
1. I/O-bound: can exceed core count since workers block on I/O.
1. Oversizing causes scheduler contention, context switching, cache thrashing.

### 4. I/O and buffering

**Check for:**

1. **Unbuffered I/O.** Reading or writing to `net.Conn`, files, or HTTP
   bodies without `bufio.Reader` or `bufio.Writer`. Buffered writes yield up
   to 50x throughput gains on network connections (goperf.dev: 33.8 MiB →
   1661 MiB on 10K connections).
1. **Missing batching.** Many small writes where batching would reduce
   syscall overhead. Many small DB inserts where a single batch insert would
   reduce round trips.
1. **Large reads into memory.** Reading entire files or responses into
   `[]byte` when streaming with `io.Reader` or `io.Writer` would avoid the
   allocation. Critical for blob upload and download paths.
1. **Zero-copy missed opportunities.** Copying data between `io.Reader` and
   `io.Writer` instead of using `io.Copy` (which can use `sendfile` or
   `splice` under the hood). Copying byte slices when sub-slicing the same
   backing array suffices.

### 5. HTTP server and handler patterns

**Check for:**

1. **Per-request allocations in middleware.** Middleware that allocates
   buffers, maps, or structs on every request. Move to `sync.Pool` or
   pre-allocate at server startup.
1. **Response body buffering.** Writing response bodies incrementally
   versus buffering then writing. For known-size responses, set
   `Content-Length` to avoid chunked encoding overhead.
1. **JSON encoding allocations.** `json.Marshal` allocates a new `[]byte`
   each call. For high-throughput endpoints, use `json.NewEncoder(w)` to
   write directly to the response writer, or pool `bytes.Buffer` for cases
   where you need the bytes.
1. **Request body not closed or drained.** Not draining `r.Body` before
   closing prevents HTTP connection reuse. Use
   `io.Copy(io.Discard, r.Body)` when the body is not fully read.
1. **`http.Error` in hot paths.** `http.Error` calls `fmt.Fprintln`
   internally. For high-throughput error responses, pre-format error bodies.
1. **Handler struct allocations.** If handler structs are allocated
   per-request in dispatchers, check whether they can be reused or simplified.
1. **Blob streaming.** OCI blob upload and download must stream — never
   buffer a whole blob in memory. A single blob can be hundreds of MiB or
   more. Use `io.Copy` with bounded buffers and check for premature
   `ReadAll`.

### 6. Database patterns

AR uses PostgreSQL exclusively (`internal/datastore/`). The service is
database-only by design — there is no filesystem dual-path.

**Check for:**

1. **N+1 queries.** Fetching a list then querying per-item in a loop. Batch
   into a single query with `WHERE x IN (...)` or use joins.
1. **Missing connection pool tuning.** Default `sql.DB` pool settings may
   be wrong for the workload. Check `SetMaxOpenConns`, `SetMaxIdleConns`,
   `SetConnMaxLifetime`.
1. **Scanning into `interface{}`.** Using `sql.Rows.Scan` with interface
   targets instead of typed destinations adds allocation and type assertion
   overhead.
1. **Prepared statement reuse.** Queries executed repeatedly without
   `sql.Stmt` preparation. `database/sql` caches prepared statements
   per-connection, so this matters most for connection-pool-heavy workloads.
1. **Transaction scope too wide.** Transactions held open across I/O
   operations (HTTP calls, file reads) instead of scoped to the minimal DB
   operations.
1. **Large result sets without `LIMIT`.** Queries that could return unbounded
   rows without pagination.
1. **Missing context on queries.** `db.Query()` without context prevents
   cancellation. Always use `db.QueryContext(ctx, ...)`.

### 7. Networking

**Check for:**

1. **Missing connection deadlines.** No `SetReadDeadline` or
   `SetWriteDeadline` on long-lived connections, risking goroutine leaks
   from stalled peers.
1. **Missing TCP tuning.** `TCP_NODELAY` not set for latency-sensitive
   paths. Connection reuse not configured.
1. **Goroutine leaks.** Connections without proper lifecycle management
   (heartbeats, idle timeouts, cleanup on context cancellation).
1. **HTTP client reuse.** Creating new `http.Client` or `http.Transport`
   per request instead of reusing with connection pooling.
1. **TLS overhead.** TLS session resumption not enabled. Certificate
   verification happening per-connection in high-throughput paths.
1. **OS-level limits.** For high-connection-count services, check guidance
   on file descriptor limits, `net.core.somaxconn`, and TCP stack tuning.

### 8. GC tuning

**Check for:**

1. **Default `GOGC` without measurement.** If GC is confirmed as a
   bottleneck via pprof, suggest tuning `GOGC`. Higher values trade memory
   for less frequent collection. Default 100 is correct for most workloads.
1. **Missing `GOMEMLIMIT` in containers.** AR runs on GKE via Runway.
   Containerized services without `GOMEMLIMIT` risk OOM kills. Set to
   ~80% of container memory limit.
1. **`GOGC=off` without `GOMEMLIMIT`.** Disabling GC pacing without a
   memory ceiling is dangerous.
1. **Weak references (Go 1.24+).** For caches and deduplication maps,
   `weak.Make` allows entries to be collected when no strong references
   remain.

**Do NOT recommend GC tuning unless:**

1. pprof or runtime metrics confirm GC is the bottleneck, or
1. the user has specifically asked about GC behavior.

### 9. Compiler hints

**Check for:**

1. **Inline candidates.** Small, hot functions that the compiler might not
   inline due to complexity budget. Check with `go build -gcflags="-m"` for
   "cannot inline" messages.
1. **Bounds check elimination.** Patterns where adding an explicit length
   check before a loop would let the compiler eliminate per-iteration bounds
   checks.
1. **Build tags for architecture-specific paths.** Performance-critical code
   that could benefit from architecture-specific implementations.

## Propose benchmarks

For each high-severity finding, write a benchmark that would demonstrate the
improvement. Use table-driven benchmark style:

```go
func BenchmarkXxx(b *testing.B) {
    b.ReportAllocs()
    for i := 0; i < b.N; i++ {
        // code under test
    }
}
```

## Output format

Present findings grouped by category:

```plaintext
## Go Performance Review: <target>

### Baseline
- Existing benchmarks: <list or "none found">
- Escape analysis: <N heap escapes in target package>
- Hot path: <description>

### Allocation & GC Pressure (N findings)
- **file.go:42** — `bytes.NewBuffer` in request handler allocates per-call.
  Use sync.Pool:
  ```go
  buf := bufPool.Get().(*bytes.Buffer)
  buf.Reset()
  defer bufPool.Put(buf)
  ```

### Concurrency (N findings)
- **server.go:118** — Unbounded `go handle(conn)` in accept loop.
  Add worker pool with semaphore channel.

### Proposed Benchmarks
- `BenchmarkBlobUpload` — measures allocation reduction from sync.Pool change

### Summary
N total findings across M categories.
Top priority: <the single most impactful change and why>
```

**Severity ranking:**

1. **High:** Unbounded allocations in hot paths, N+1 queries, goroutine
   leaks, missing connection deadlines, unbuffered network I/O on blob paths.
1. **Medium:** Suboptimal pool usage, struct alignment in volume types,
   missing preallocation, wide transaction scope, missing connection pool
   tuning.
1. **Low:** Compiler hints, cold-path allocations, style-level improvements.

## Rules

1. Every recommendation must be backed by a specific code pattern from the
   review, not a general best practice.
1. Do not recommend optimizations for code that is not in a hot path unless
   the user asked for a comprehensive review.
1. Do not recommend `unsafe` package usage.
1. State when profiling is needed to confirm an issue rather than asserting
   impact without evidence. "This looks like it allocates per-request, but
   run `go test -bench -benchmem` to confirm" is better than "this allocates
   per-request."
1. Reference [goperf.dev](https://goperf.dev/) sections for further reading
   when relevant (e.g., "See goperf.dev/01-common-patterns/object-pooling/
   for sync.Pool benchmarks").
1. Respect the conventions in `docs/dev/go-style.md` and AGENTS.md. Do not
   suggest changes that conflict with established project patterns (for
   example, do not suggest changing the error handling pattern in code that
   uses error accumulators).

