Snippets
Things that don’t deserve a full post. A query I always have to look up, a bash trick I save for later, a Go helper I’ve written three times. If you see something useful, copy freely.
pushd/popd for scripts that cd into many directories
A directory stack so scripts do not leak working directories between steps.
Builder pattern in Rust with Default
Builder structs for configuration, without a macro crate, when the struct has 20 fields.
A PodDisruptionBudget that actually protects you
minAvailable as a percentage, matched to a workload that has more than one replica.
A generic atomic counter for typed IDs
sync/atomic plus Go generics, so counter.Add and counter.Load carry their type.
Fast row-count estimates without COUNT(*)
pg_class.reltuples for when you need an answer in milliseconds.
Parsing process.env with zod, once, at startup
A typed env object that crashes on boot if required variables are missing.
A good-enough email regex, with notes on what it ignores
The 90-percent regex I use, plus a list of the 10 percent it deliberately misses.
Graceful shutdown with signal.NotifyContext
Three lines that replace the old os/signal dance and are still the right pattern.
Bounded parallelism with asyncio.gather
A Semaphore wrapper that caps concurrent coroutines without losing gather ergonomics.
tokio::select with an explicit cancellation token
CancellationToken over ad-hoc shutdown channels, because it actually composes.
Multi-stage Dockerfile for a Go service on scratch
A tiny final image with certs, tzdata, a non-root user, and no surprises.
Parallel Go tests that share a per-test temp directory
t.TempDir plus t.Parallel: short, correct, and auto-cleaning.
Shell retry with exponential backoff and jitter
A copy-pasteable retry function for flaky network calls in CI and deploy scripts.
Find foreign-key violations before a migration
A query that tells you exactly which child rows will fail when you add the FK.
A Click stub for a multi-subcommand CLI
The pattern I copy when I am tired of argparse and need something useful in five minutes.
Portable sed -i across GNU and BSD
The one invocation that does not blow up on macOS or Linux.
A sync.Pool of bytes.Buffer done right
The Put-before-you-Get-back idiom, and the cap-guard that keeps the pool small.
Rust: ok_or_else over ok_or, and why
A tiny pattern that avoids allocating error strings on the happy path.
Parallel xargs with an actual progress indicator
xargs -P plus a named pipe to print 'M of N done' without buffering the output.
Gaps-and-islands SQL for compressing event streaks
A window-function pattern that collapses consecutive states into runs.
Kubernetes webhook: skip a namespace with one selector
The namespaceSelector pattern that saved me from an admission-webhook outage.
Caddy snippet for security headers in one place
A named snippet I import into every site so headers stay consistent.
HTTP middleware that recovers panics cleanly
Recover, log with a stack, return 500, and do not crash the whole server.
Cancel long-idle Postgres transactions
A query plus a loop to find idle-in-transaction sessions and kindly end them.
Bash trap for cleaning up a temp directory
The five-line top-of-script pattern I use in every non-trivial bash tool.
Detaching a context for background work
A context that keeps the values but drops the cancellation, for async follow-ups.
Streaming a large CSV in Python without loading it
The DictReader loop plus a progress tick, so I stop reaching for pandas on 20GB files.
Recursive CTE to walk a parent-child tree in SQLite
The WITH RECURSIVE pattern for a self-joining table, with depth and path.
A ticker with jitter, cancelled by context
A drop-in replacement for time.NewTicker that stops when your context does and does not synchronize all your replicas.
rsync invocation that is actually safe to resume
The flag combo I copy into every backup job so half-done transfers do not corrupt files.
Postgres advisory locks for cross-process deduplication
A cheap mutex across N service replicas that does not need Redis.
Deduplicating in-flight requests with singleflight
Ten lines that collapse a thundering herd into a single upstream call.
AWK script that sums a column with a header
The awk one-liner I keep forgetting, with the one option that made it robust.
A tiny Rust macro for safe env var parsing
A declarative macro that turns std::env::var into a typed, required-or-default lookup.
Nginx location block to serve one file under many names
A tiny block for robots.txt, favicon, humans.txt and all their cousins.
Postgres: find long-running queries and who is blocking whom
A view of pg_stat_activity that tells me the query and its blockers in one shot.
errgroup that cancels siblings on the first error
The 10-line pattern that replaces half the goroutine orchestration I used to write.
Find files modified today across multiple repos
A shell one-liner I run every morning to remember what I was touching yesterday.
Postgres query to find bloated indexes
A quick-and-dirty bloat estimate so I can decide which indexes to REINDEX tonight.
Deadline-wrapping an io.Reader
A small helper to cancel a slow read with a deadline, using context and a goroutine proxy.