go

Consistent JSON responses (content-type + error envelopes)

One of the easiest ways to reduce frontend complexity is to be consistent about API responses. I keep a small helper that always sets Content-Type: application/json; charset=utf-8, uses a stable error envelope (error + optional details), and returns c

Track in-flight requests with atomic counters

In-flight request count is a simple but powerful saturation signal. I keep an atomic.Int64 gauge that increments at the start of a request and decrements in a defer, which makes it robust even on early returns. This gauge can be exported via expvar, P

db/sql prepared statements with context and explicit Close

Prepared statements are useful when the same query runs in hot loops, but they come with lifecycle responsibilities. I prepare once (usually at startup), store the *sql.Stmt, and always close it on shutdown. The important detail is still using QueryRo

Request-scoped slog logger with JSON output (Go 1.21+)

I’ve started using log/slog for services that want structured logs without a heavy dependency. The key is treating the request logger as data: create a base logger with JSON output, then derive a request logger with fields like request_id and path. I

Exponential backoff with jitter for retries

Retries are dangerous when they synchronize; that’s how you turn a minor outage into a stampede. I implement exponential backoff with jitter so clients spread out naturally. The Retry helper takes a shouldRetry predicate and always checks ctx.Done() b

Safe YAML decoding (KnownFields) for config files

YAML configuration is convenient, but it’s also a footgun when typos silently get ignored. I enable KnownFields(true) so unknown keys cause an error, which turns “silent misconfig” into a fast failure. That is especially useful during refactors when f

JSON schema-ish validation with custom error details

I don’t try to re-implement full JSON Schema in Go, but I do like returning validation errors that are easy for clients to render. The pattern is: decode into a struct, validate required fields and invariants, and return a slice of {field, message} is

ETag handling for conditional GETs (cheap caching)

ETags are a low-effort way to cut bandwidth and CPU when clients poll for resources that rarely change. The server computes an ETag for the representation (often a version, content hash, or updated_at value) and compares it to If-None-Match. If they m

CORS allowlist middleware (no wildcard surprises)

CORS is one of those features that becomes security-sensitive by accident. Instead of Access-Control-Allow-Origin: *, I keep a strict allowlist and echo back the exact origin only when it’s approved. I also handle OPTIONS preflight requests explicitly

Robust environment parsing for bool/int with explicit defaults

I like config that fails loudly when it’s wrong. The helpers below parse environment variables with explicit defaults and good error messages, which prevents subtle “zero value” behavior in production. This is especially important for flags like ENABL

Sampling logs to reduce noise during high-QPS incidents

Structured logs are great, but at high QPS they can become their own outage: too much IO, too much storage, and noisy dashboards. zap includes a sampler that allows you to keep early logs and then sample at a fixed rate. I like this for “successful re

Password hashing with bcrypt and a calibrated cost

Never store passwords as raw strings, and don’t invent your own hashing scheme. I use bcrypt with a cost that’s calibrated for the environment (fast enough for login throughput, slow enough to resist offline cracking). The trick is to treat the cost a