Recipes

Step-by-step solutions for real development tasks.

699 published

Page 5 of 7

Gate Deployment on a Smoke Test Suite

Run a fast post-deploy smoke suite that exercises critical paths and blocks promotion when any check fails.

~35 min
testing · deployment · ops

Generate Realistic Test Data with Faker

Produce a million-row dataset with believable distributions, seeded reproducibility, and referential integrity, then load it with COPY.

~30 min
database · testing · tooling

Handle SIGINT Cleanup in a CLI

Trap interrupt signals to remove temporary files and flush progress so Ctrl-C does not leave a broken state.

~25 min
cli · nodejs · reliability

Audit and Harden sshd Configuration

Disable password and root login, restrict algorithms to current best practice, verify with ssh -Q and a controlled restart, and keep an escape session open.

~20 min
security · ssh · operations

Harden TLS Cipher Suites

Restrict a server to modern TLS versions and strong ciphers, then verify with a scanner and client handshake tests.

~30 min
tls · security · hardening

Harden a Base Image with Non-Root User and Read-Only Rootfs

Run containers as a dedicated UID with a read-only root filesystem, writable tmpfs mounts, and dropped capabilities verified by a breakout attempt.

~25 min
deploy · docker · security

Hunt Down idle in transaction Sessions in PostgreSQL

Find sessions holding a transaction open while doing nothing, measure their age and lock footprint, and close the leak at the application layer.

~30 min
database · postgresql · debugging

Hydrate Islands Progressively

Hydrate interactive components on idle or on visibility so static content is interactive without blocking the main thread.

~30 min
frontend · performance · hydration

Implement CLI Config Precedence

Define a clear precedence of flags over environment over config file over defaults so behaviour is predictable.

~30 min
cli · configuration · javascript

Implement Progressive Delivery Steps

Roll out a change in controlled increments with automated analysis between steps so a bad release is caught early.

~40 min
deployment · ops · reliability

Implement Webhook Signature Verification That Handles Time

Verify HMAC signatures with constant-time comparison, reject timestamps outside a tolerance window, and block replayed delivery ids.

~30 min
security · webhooks · api

Build an Incremental ETL Load with a Watermark Column

Track a monotonically increasing watermark, copy only rows past it, and make the job restartable by advancing the mark transactionally.

~40 min
data · etl · incremental

Inspect and Defragment etcd Safely

Check etcd database size and fragmentation, then defragment one member at a time with a backup first.

~40 min
etcd · kubernetes · maintenance

Inspect HTTP Cache Vary Header Mismatch

Detect a missing or wrong Vary header that serves one user language or encoding to another through a shared cache.

~30 min
http · caching · debugging

Inspect HTTP Keep-Alive Timeout Resets

Use packet capture to prove whether intermittent connection resets come from idle keep-alive timeouts on a proxy or the origin server.

~35 min
http · networking · debugging

Inspect WebSocket Frames with websocat

Connect to a live WebSocket endpoint with websocat, send handcrafted frames, watch server pushes arrive, and diagnose protocol issues the browser hides.

~20 min
api · websocket · debugging

Instrument Unit Tests with a Coverage Threshold

Enable coverage instrumentation and set an enforceable threshold so new code cannot merge below the agreed bar.

~25 min
testing · ci · coverage

Isolate HTTP 502 Upstream Reset

Correlate gateway access logs with upstream connection resets to prove which backend instance is closing connections early.

~30 min
http · debugging · reliability

Lazy-Load Route Chunks in Vite

Split routes into dynamic imports so the initial bundle stays small and heavy views load on demand.

~30 min
frontend · performance · vite

Diagnose Container CPU Throttling

Read cgroup throttling counters to prove whether a container's latency comes from CPU limits rather than slow code.

~30 min
container · performance · kubernetes

Manage Focus After SPA Navigation

Move focus to the new view heading on client-side navigation so keyboard and screen-reader users are not stranded.

~25 min
frontend · accessibility · spa

Measure PostgreSQL Index Bloat

Use pgstattuple and statistics to estimate index bloat and decide whether a REINDEX is worth the lock cost.

~30 min
postgresql · database · maintenance

Measure TLS Handshake Overhead and Session Reuse

Time full versus resumed TLS handshakes with curl and openssl, quantify the certificate chain cost, and decide where connection reuse pays off.

~20 min
api · performance · tls

Merge Multiple Parquet Files Safely

Consolidate many small Parquet files into fewer larger ones to cut metadata overhead and improve scan efficiency.

~30 min
data · parquet · storage

Migrate a Runtime Image to Distroless Safely

Shrink the attack surface by moving from a full base image to distroless, keeping debug shells reachable via a separate debug tag, and verify in CI.

~30 min
deploy · docker · security

Mine Access Logs for Status and Latency Anomalies

Turn nginx or app access logs into ranked tables of error rates, slow paths, and suspicious clients using only jq, awk, and sort.

~20 min
api · observability · shell

Mock Time with Sinon Fake Timers

Control time in tests with fake timers so debounce, retry, and timeout logic is deterministic instead of flaky.

~25 min
testing · javascript · timers

Measure Node Event Loop Delay Before Blaming the CPU

Track lag between scheduled and actual timer execution, correlate spikes with request logs, and find the synchronous code responsible.

~30 min
performance · nodejs · observability

Build Multi-Architecture Images with buildx

Build and push amd64 and arm64 variants in one command so the same tag runs on mixed clusters.

~35 min
container · docker · ops

Turn a Full Table Scan into a Covered Query in MySQL

Confirm the scan with EXPLAIN, design a composite covering index, and verify Extra shows Using index so the query never touches the row.

~30 min
database · mysql · performance

Reload nginx Without Dropping Connections

Use nginx -s reload with correct worker shutdown settings, verify old workers drain, and confirm zero 502s during configuration changes.

~20 min
deploy · nginx · operations

Optimize Array Deduplication with a Set

Replace O(n squared) deduplication loops with a hash set so large arrays dedupe in linear time.

~20 min
performance · algorithms · javascript

Reduce Go Allocations with sync.Pool

Reuse hot short-lived buffers through sync.Pool to cut garbage collection pressure on high-throughput paths.

~30 min
performance · go · memory

Serve Responsive Images with srcset

Provide width descriptors and modern formats so devices download the smallest adequate image.

~30 min
frontend · performance · images

Lazy-Load Below-the-Fold Images and Widgets Correctly

Audit what actually ships in the initial payload, apply native lazy-loading plus fetchpriority hints, and verify with a network waterfall.

~25 min
performance · frontend · web-vitals

Package a Node CLI with a bin Entry

Publish a Node CLI with a bin mapping and executable shebang so it installs as a global command with the right name.

~25 min
cli · nodejs · packaging

Parallelize Playwright E2E with Shards and Workers

Split E2E specs across CI machines and in-process workers, isolate each workers browser context, and keep total runtime under a budget.

~30 min
testing · e2e · playwright

Parallelize Shell Jobs with xargs -P and Preserve Ordering

Fan out independent commands across CPU cores with xargs -P, keep outputs attributable, and recombine results in input order.

~20 min
cli · shell · parallelism

Parallelize Vitest Across Threads

Tune the Vitest pool and per-file isolation so a large suite finishes faster without flaky shared-state failures.

~30 min
testing · performance · ci

Parametrize JUnit 5 Tests with a Method Source

Drive JUnit 5 parameterised tests from a method source or CSV so edge cases stay explicit and addable without new methods.

~30 min
testing · java · junit

Parse CLI Flags Correctly in POSIX Shell with getopts

Handle short flags with arguments, distinguish missing from empty values, and produce actionable errors instead of silent defaults.

~25 min
cli · shell · argument-parsing

Parse a YAML Config in a CLI

Load a YAML config with schema validation and helpful error messages so a malformed file fails clearly rather than silently.

~30 min
cli · configuration · yaml

Write Partitioned Parquet Datasets

Write Parquet partitioned by a low-cardinality column so downstream queries prune partitions and scan far less data.

~30 min
data · parquet · analytics

Pin Docker Base Images by Digest, Not by Tag

Resolve mutable tags to immutable digests, record them in the Dockerfile, and verify every rebuild starts from the exact same bytes.

~20 min
deploy · docker · supply-chain

Diagnose and Break a Postgres Lock Wait Chain

Query pg_locks and pg_stat_activity to expose the blocking session and its waiting victims, then decide to terminate, wait, or fix the transaction scope.

~25 min
database · postgres · operations

Prefetch Critical Resources with Resource Hints

Use preconnect and prefetch hints for the next likely navigation so critical resources arrive before they are requested.

~25 min
performance · frontend · web

Preflight Check Cluster Capacity

Compare requested resources against allocatable capacity so a deployment does not land pods in a permanently pending state.

~25 min
kubernetes · ops · capacity

Profile Column Cardinality Before Designing Storage

Measure distinct counts, null rates, and frequency skew per column, then let the data choose between enum, index, and partition designs.

~30 min
data · schema-design · profiling

Profile MongoDB Slow Queries and Read the Plan

Enable the profiler at slowms, read explain output for scanStage and index use, and add the compound index the plan says is missing.

~30 min
database · mongodb · performance

Profile a Python Hot Function with cProfile

Use cProfile and pstats to rank functions by cumulative time and fix the real hot path instead of guessing.

~30 min
performance · python · profiling

Profile the Slowest Tests with Reporters

Rank tests by duration with a reporter so optimising the few slowest cases shortens the whole suite the most.

~30 min
testing · performance · ci

Protect Against CSRF with Double Submit

Use a same-site cookie plus a double-submit token so state-changing requests cannot be forged from another origin.

~30 min
security · web · csrf

Protect a Redis Cache Against Stampede and Penetration

Guard a hot key with a mutex lock and stale-while-revalidate, and neutralize cache penetration for missing keys with short negative TTLs.

~35 min
database · redis · resilience

Prove SQL Injection Safeguards with Attack Tests

Inventory every query construction site, attack each with canonical payloads, and add regression tests that keep parameterization honest.

~35 min
security · database · testing

Quarantine Flaky Tests and Fix Them for Real

Detect flaky tests with repeat runs, move them to a quarantine suite that does not gate, diagnose the root cause, and graduate them back.

~35 min
testing · ci · flakiness

Unmask Flaky Tests by Rerunning the Suite

Run the suite repeatedly with shuffled order and fixed seeds, rank tests by failure variance, and quarantine only the proven offenders.

~40 min
testing · ci · flaky-tests

Read a Postgres Execution Plan and Fix the Slow Node

Run EXPLAIN ANALYZE, walk the plan tree node by node, compare estimated versus actual rows, and act on the node where the cost concentrates.

~30 min
database · postgres · performance

Rebuild a MongoDB Index Online

Rebuild a fragmented MongoDB index without blocking writes by leveraging rolling index builds on a replica set.

~45 min
mongodb · database · maintenance

Redact PII in Application Logs

Add structured log redaction for emails, tokens, and card numbers so sensitive data never lands in log storage.

~30 min
security · logging · privacy

Reduce CLS by Measuring Shifts Before Fixing Them

Record layout-shift entries with sources, rank which elements move and when, then reserve exact space instead of guessing at CSS.

~30 min
performance · frontend · web-vitals

Reduce N+1 Queries with a DataLoader

Batch and cache per-request lookups with a DataLoader so list endpoints stop issuing one query per item.

~35 min
performance · database · graphql

Reduce Render-Blocking CSS

Inline critical CSS, defer the rest, and split stylesheets so the first paint is not blocked by a large global stylesheet.

~30 min
performance · frontend · css

Record and Replay HTTP Traffic with mitmproxy

Capture real client traffic into a flow file with mitmproxy, edit selected requests, and replay them deterministically against staging to reproduce bugs.

~35 min
api · debugging · testing

Reproduce an API Timeout with curl Trace

Break a slow API call into DNS, connect, TLS, and first-byte timings so you can prove which phase consumes the latency budget.

~25 min
http · performance · debugging

Restore a Single Table from a Full Database Dump

Extract one table from a pg_dump archive with pg_restore, land it in staging, verify counts and checksums, then move only the needed rows.

~40 min
database · postgres · operations

Restrict CORS to an Origin Allowlist

Replace wildcard CORS with a strict origin allowlist that also handles credentials and preflight safely.

~25 min
security · cors · api

Enforce Pod Security Admission

Apply the restricted Pod Security Standard namespace by namespace so privileged pods are rejected at admission.

~35 min
kubernetes · security · hardening

Review and Slim an Overgrown Snapshot Suite

Audit snapshot sizes and update frequency, convert intent-bearing cases to explicit assertions, and keep snapshots only where structure is the contract.

~30 min
testing · snapshots · vitest

Review sudoers for Privilege Escalation Paths

Dump effective sudo rules per user, hunt wildcard and NOPASSWD grants that escape their intent, and tighten them with command argument pinning.

~30 min
security · linux · hardening

Roll Forward a Failed DB Migration

Prefer a corrective forward migration over a rollback when a schema change has already run, to avoid data-loss surprises.

~35 min
database · migration · ops

Roll Back a Bad Deployment with kubectl rollout undo

Inspect revision history, undo to the last good revision by number, and verify the rollback actually landed by comparing live pod specs.

~15 min
deploy · kubernetes · rollback

Roll Out a Content Security Policy via Report-Only

Deploy a strict CSP in report-only mode first, collect violation reports from real users, fix the causes, then enforce once reports fall silent.

~30 min
security · web · headers

Rotate a Live API Key Without Downtime

Issue a second key, deploy dual-key acceptance, shift traffic to the new key, then revoke the old one after a quiet observation window.

~30 min
security · secrets · operations

Rotate SSH Authorized Keys Safely

Roll SSH authorized keys with an overlap window so each operator can verify their new key before the old one is removed.

~30 min
ssh · security · operations

Run E2E Tests Against docker compose

Spin up the full stack with docker compose in CI, wait for readiness, run E2E tests, and tear everything down deterministically.

~40 min
testing · docker · e2e

Run a Bulk Delete with a Checkpoint Table and Dry Run

Stage the doomed rows into a checkpoint table, review the dry-run count, delete in bounded batches, and keep an instant restore path.

~45 min
database · postgres · operations

Sanitize User-Submitted HTML with DOMPurify

Clean rich-text input on the server with a strict allow-list, keep hooks for URL schemes, and prove the result with XSS payload tests.

~30 min
security · web · xss

Scaffold Projects from Templates with Variable Substitution

Build a template directory with delimited placeholders, substitute values safely without regex injection, and verify the result compiles.

~35 min
cli · developer-experience · templates

Scan Dependencies with OSV-Scanner

Scan lockfiles and container images for known vulnerabilities with OSV-Scanner and fail CI only on actionable findings.

~30 min
security · supply-chain · testing

Schedule an ECS Task with EventBridge

Run a periodic containerised job on a schedule with EventBridge rules and verify retries and logging.

~40 min
aws · ops · scheduling

Scrub PII from a Dataset with pandas

Detect and pseudonymise direct identifiers in a dataframe before sharing it with analysts.

~35 min
data · privacy · pandas

Make Randomized Tests Reproducible with Seeds

Route all randomness through one seeded generator, print the seed on failure, and replay the exact failing sequence with one flag.

~30 min
testing · determinism · ci

Set Statement Timeout per Role

Apply a default statement_timeout to reporting roles so a runaway query cannot monopolise connections and starve the pool.

~25 min
postgresql · database · operations

Deploy from GitHub Actions Without Long-Lived Keys

Replace stored cloud credentials with OIDC federation, scope the trust policy to your repo and environment, and verify no secrets remain.

~30 min
deploy · ci · security

Shard Tests Across Parallel Databases for Speed

Give each test shard its own schema or database, run shards concurrently, and eliminate cross-test interference that serial runners hid.

~30 min
testing · ci · databases

Detect and Shrink a Bloated Postgres Table

Estimate dead tuple bloat with pgstattuple, reclaim space without exclusive locks using pg_repack, and verify the size actually dropped.

~50 min
database · postgres · operations

Shrink SQLite with Page Reclaim

Lower the page size and auto_vacuum settings to reclaim free pages and keep a local SQLite file compact between maintenance runs.

~25 min
sqlite · database · maintenance

Sign and Verify Release Artifacts

Sign release binaries and container images with a keyless signature and verify them at deploy time to block tampered artifacts.

~35 min
supply-chain · security · ops

Design Skeleton Loading That Tells the Truth

Match skeleton geometry to the real content layout, avoid fake progress bars, and measure perceived completion against actual readiness.

~30 min
frontend · ux · performance

Snapshot REST API Contracts

Capture normalised response snapshots for REST endpoints so unintended contract changes fail review instead of reaching clients.

~30 min
testing · api · contract

Speed Up Bulk Inserts with COPY Instead of Row-by-Row

Replace thousands of single INSERT round trips with one COPY stream, measure the difference, and keep the loader resumable and idempotent.

~30 min
database · postgres · performance

Tune SQLite WAL Mode for Concurrent Readers and a Writer

Enable WAL journaling, set busy_timeout and synchronous pragmas, and prove readers keep working while a write transaction commits.

~20 min
database · sqlite · concurrency

Standardize Timestamps and Timezones in a Dirty Dataset

Detect mixed formats and zone-less entries, normalize everything to UTC instants, and keep the original string alongside for audit.

~40 min
data · timestamps · data-quality

Transform Gigabyte Files with Constant Memory Streams

Replace readFileSync loops with pipeline streams, apply backpressure-aware transforms, and verify output equivalence on a sample.

~35 min
data · nodejs · streaming

Stub Third-Party API Failures to Prove Client Resilience

Spin up WireMock with fault scenarios for latency, 500s, and 429 throttling, point the client at it, and prove retries, timeouts, and fallbacks actually work.

~40 min
api · resilience · testing

Template an Idempotent Ansible Role

Write an Ansible role that converges to the same state on repeated runs, using declarative modules instead of shell tasks.

~35 min
ansible · ops · automation

Test Error Branches with Injected Failures

Inject dependency failures at call boundaries to exercise catch and fallback paths that normal runs never reach.

~30 min
testing · reliability · error-handling

Test Graceful Shutdown Signal Handling

Assert that a service stops accepting new work, drains in-flight requests, and exits within the shutdown deadline on SIGTERM.

~30 min
testing · reliability · nodejs

Trace API 429 Throttling Windows

Align 429 responses with rate-limit headers to reconstruct the client quota window and stop retries from extending the lockout.

~30 min
api · rate-limit · debugging

Trace One Request Across Services with a Correlation ID

Propagate a single x-request-id through gateway, service, and job tiers, then stitch per-service logs into one timeline to find the slow hop.

~25 min
api · observability · logging