Recipes

Step-by-step solutions for real development tasks.

699 published

Page 4 of 7

Implement a Sliding-Window Rate Limit

Use a sliding window or token bucket with shared state so limits are accurate across instances and fair at the boundaries of fixed windows.

~40 min
rate-limiting · reliability · security

Replace SSH Keys with a Short-Lived CA

Run an SSH certificate authority, issue short-lived user and host certificates, and have servers trust the CA so key rotation and revocation are manageable.

~50 min
ssh · security · pki

Implement Stale-While-Revalidate Caching

Serve a cached response immediately while refreshing it in the background, and cap staleness so users get fast reads without permanently stale data.

~35 min
caching · performance · reliability

Stream a Large CSV Export

Write rows to the response as they are read, flush periodically, and backpressure the database cursor so memory stays flat for large exports.

~40 min
streaming · data-export · performance

Add a Time-Series Retention Policy

Partition metrics by time, drop or roll up old partitions on a schedule, and keep queries bounded so storage and latency stay predictable.

~45 min
timeseries · postgresql · data-lifecycle

Chain Traefik Middlewares for Defense in Depth

Compose rate limiting, security headers, and a circuit breaker as labeled middlewares so every routed service inherits the same protections.

~40 min
traefik · reliability · security

Publish Events with a Transactional Outbox

Write the event to an outbox table in the same transaction as the state change, then relay it asynchronously with retries and idempotent consumers.

~45 min
messaging · reliability · transactions

Prevent DOM XSS with Trusted Types

Enable Trusted Types, route unsafe sinks through a policy that sanitizes input, and keep string assignment from injecting scripts.

~40 min
security · xss · frontend

Map Internal Errors to Typed API Errors

Define an error taxonomy, convert thrown domain errors to stable codes and HTTP statuses, and log the internal cause without exposing it to clients.

~30 min
api-design · error-handling · backend

Verify Partition Pruning Is Effective

Confirm that queries filter on the partition key and that the planner prunes unrelated partitions, using EXPLAIN and runtime statistics.

~30 min
postgresql · performance · databases

Add a Progress Bar for Streamed Work

Render progress to stderr so it does not pollute stdout, and suppress it when output is not a terminal.

~20 min
cli · ux · terminal

Stop Slow-Starting Containers from Being Killed

Give JVM or migration-heavy containers a startupProbe with a generous budget so liveness never executes during boot and restart loops end.

~20 min
deploy · kubernetes · operations

Add Namespace Resource Quotas to Stop Noisy Neighbors

Bound CPU, memory, and object counts per namespace with ResourceQuota, require requests on every pod, and verify enforcement with a stress test.

~25 min
deploy · kubernetes · operations

Add PKCE to an OAuth Public Client Flow

Generate a per-request code verifier, send its challenge in the authorization request, and redeem the code proving possession of the verifier.

~25 min
security · oauth · authentication

Add Bash Shell Completion

Ship a completion script that suggests subcommands and flags so users discover options without reading docs.

~25 min
cli · bash · ux

Add TOTP MFA Enrollment with Recovery Codes

Generate a provisioning QR code, verify a first code before enabling, store the secret encrypted, and issue single-use recovery codes.

~40 min
security · authentication · mfa

Add Visual Regression Checks with Playwright Screenshots

Screenshot stable viewports with deterministic content, compare against committed baselines with a tolerance, and review diffs in the pull request.

~30 min
testing · e2e · playwright

Automate Canary Analysis and Rollback with Argo Rollouts

Replace manual canary judgment with an AnalysisTemplate that queries error rate and latency metrics and promotes or rolls back automatically.

~45 min
deploy · kubernetes · observability

Find Duplicate Packages Inflating Your Frontend Bundle

List version-multiplicated packages in the dependency graph, trace which import paths pull each copy, and collapse them into one.

~35 min
performance · frontend · bundling

Analyze Tail Latency Outliers Beyond the Averages

Compute P50, P99, and P99.9 from raw latency samples, group outliers by instance and endpoint, and find the one slow replica dragging every hundredth request.

~30 min
api · performance · observability

Archive Cold Rows to a History Table

Move old rows into an archive table in bounded batches so the hot table stays small and query plans stay stable.

~40 min
postgresql · database · operations

Assert Structured Log Fields

Capture structured logs in tests and assert on fields rather than substrings so logging behaviour is regression-tested.

~25 min
testing · observability · logging

Audit API Error Response Shapes for Consistency

Collect real 4xx and 5xx responses across endpoints, normalize them into a report of shapes and fields, and converge everyone onto one error envelope.

~40 min
api · design · testing

Audit JWT Refresh Token Rotation and Revocation

Inspect access and refresh token lifetimes, verify refresh rotation invalidates the old token, and test revocation actually blocks reuse.

~30 min
security · authentication · jwt

Audit Missing Security Headers

Scan responses for missing HSTS, CSP, X-Content-Type-Options, and frame protections, then fix them with a middleware.

~30 min
security · http · hardening

Audit and Constrain npm Install Scripts in Your Supply Chain

Enumerate which dependencies declare lifecycle scripts, run installs with scripts disabled, and gate the exceptions you truly need.

~30 min
security · supply-chain · npm

Audit PostgreSQL Unused Indexes

Use pg_stat_user_indexes to find indexes that are never scanned, then drop them safely after confirming they are not unique constraints.

~35 min
postgresql · database · performance

Automate Blue-Green DNS Cutover

Switch traffic between blue and green stacks by updating DNS with a low TTL and verifying health before and after the cutover.

~35 min
dns · ops · deployment

Automate Certificate Renewal with a Deploy Hook

Configure certbot renewals with dry runs, a deploy hook that reloads the right service, and monitoring that alerts when renewal stops happening.

~20 min
deploy · tls · automation

Backfill a Warehouse Partition Safely

Backfill a single partition in place with an atomic swap so queries see either the old or the new data, never a partial mix.

~35 min
data · warehouse · operations

Batch Network Calls Without Losing Latency

Coalesce many small requests into fewer batched calls using a short scheduling window to cut round-trip overhead.

~35 min
performance · networking · javascript

Block SSH Brute Force with fail2ban

Match auth failures with a jail, ban repeat offenders with iptables or nftables, whitelist your own networks, and verify with a test ban.

~25 min
security · ssh · operations

Block Unnecessary Outbound Egress

Apply a default-deny egress policy so a compromised workload cannot reach arbitrary hosts on the internet.

~35 min
kubernetes · security · network

Blue-Green Switch with Cloudflare Workers

Route a portion of traffic between two origins using a Worker and shift weight programmatically to enable instant rollback.

~40 min
cloudflare · ops · deployment

Build argparse Subcommands

Structure a Python CLI with subparsers so each command has its own arguments and a shared top-level parser.

~30 min
cli · python · argparse

Build Interactive CLI Prompts with Validation and Safe Defaults

Ask questions only when arguments are absent, validate answers in the loop, and make non-interactive mode the escape hatch that always works.

~30 min
cli · developer-experience · nodejs

Bulk Upsert Thousands of Rows with ON CONFLICT in PostgreSQL

Stream rows through COPY or multi-row INSERT with ON CONFLICT DO UPDATE, avoiding per-row round trips and deadlocks from unordered writes.

~30 min
database · postgresql · bulk-operations

Cache API Responses in a Service Worker

Apply a stale-while-revalidate strategy in a service worker so repeat visits render instantly and refresh in the background.

~35 min
frontend · caching · service-worker

Cache Serialization with MessagePack

Swap JSON for MessagePack in a hot cache path to cut serialization CPU and payload size without changing semantics.

~30 min
performance · caching · serialization

Capture gRPC DEADLINE_EXCEEDED Traces

Instrument a gRPC client to surface deadline budgets and server spans so DEADLINE_EXCEEDED can be traced to the slow dependency.

~40 min
grpc · observability · debugging

Catch a Retry Storm by Capturing Packets with tcpdump

Capture retransmissions and connection churn at the NIC level, correlate them with application retry counters, and size backoff correctly before disabling retries.

~35 min
api · networking · reliability

Debug Webhook HMAC Signature Mismatch

Compare the raw request body bytes used for HMAC signing against the bytes received, catching re-serialisation and encoding drift.

~30 min
webhook · security · debugging

Catch Breaking OpenAPI Changes Before Release with oasdiff

Diff two OpenAPI documents with oasdiff in CI, fail the build on removed fields or narrowed types, and publish a human-readable changelog for review.

~25 min
api · openapi · ci

Choose Between Mocks, Stubs, and Fakes Deliberately

Pick test doubles by the question each test answers: stubs for state setup, mocks for interaction verification, fakes for realistic behavior.

~25 min
testing · unit-testing · design

Update a Huge Table in Safe Chunks

Rewrite millions of rows without a giant transaction by chunking on a key, committing per batch, tracking progress, and resuming after interruption.

~40 min
database · postgres · operations

Clone PostgreSQL Schema Without Data

Use pg_dump schema-only output to scaffold a staging database that matches production structure for safe query planning tests.

~25 min
postgresql · database · testing

Colorize CLI Output with ANSI Codes

Add ANSI colour to CLI output only when the stream is a terminal and NO_COLOR is unset, respecting user preference.

~20 min
cli · terminal · ux

Compare MySQL Query Plans Before and After an Index

Use EXPLAIN ANALYZE to measure real row counts and timing per step, then prove an index actually changed the plan instead of guessing.

~25 min
database · mysql · performance

Configure Docker Container Log Rotation Before It Fills the Disk

Set json-file log driver rotation options per container or daemon-wide, verify max-size and max-file take effect, and alert on remaining disk.

~20 min
deploy · docker · operations

Configure SSH Bastion Jumps and Connection Multiplexing

Centralize jump-host access with ProxyJump, reuse connections with ControlMaster, and keep per-host keys instead of a shared bastion credential.

~20 min
deploy · ssh · operations

Harden a systemd Service Against Crashes and Reboots

Set Restart, watchdog, and resource limits on a systemd unit so crashes self-heal, hangs get killed, and boot ordering is explicit.

~25 min
deploy · linux · operations

Configure External Uptime Probes That Users Agree With

Probe from outside the datacenter on the real user path, alert on consecutive failures with downtime tracking, and page on the right severity.

~25 min
deploy · observability · operations

Convert a Large Table to Partitions Online

Attach a partitioned twin, dual-write or replicate into it, backfill by range, and swap names in one transaction with minimal lock time.

~60 min
database · postgres · operations

Debounce Search Input Without Losing Keystrokes or Requests

Debounce the expensive effect, not the input value, cancel in-flight requests on new input, and keep every keystroke responsive.

~25 min
frontend · react · ux

Debounce ResizeObserver Layout Work

Throttle layout work triggered by ResizeObserver so rapid resizes do not thrash the main thread.

~25 min
frontend · performance · javascript

Debug API Payload Schema Rejection

Reproduce a 422 payload rejection and use schema validation diagnostics to find the exact property path that fails.

~25 min
api · validation · debugging

Debug Cache Variation Leaks Between Users

Prove that a shared cache is serving one user personalized response to another by testing with two identities, then fix the missing Vary header.

~25 min
api · caching · security

Debug a Failing CORS Preflight with curl

Reproduce an OPTIONS preflight by hand with curl, read the Access-Control-* response headers, and fix the exact header the browser is complaining about.

~20 min
api · cors · debugging

Debug CSS Specificity Wars with the Cascade Layers Toolbox

Identify which rule actually wins and why, quantify specificity instead of guessing, and end arms races with layers and :where.

~25 min
frontend · css · maintainability

Debug GraphQL Persisted Query Misses

Resolve persisted-query-not-found errors by checking the APQ hash registry and hash generation between client and server.

~30 min
graphql · api · debugging

Debug HTTP 503 with Retry-After Backoff

Reproduce a 503 response, read the Retry-After header, and prove a client backoff schedule respects server guidance under load.

~30 min
http · api · debugging · resilience

Debug a 406 Not Acceptable with curl Header Experiments

Bisect the Accept header piece by piece to find exactly which media type the server rejects, then fix the negotiation on the correct side.

~20 min
api · http · debugging

Debug HTTP/2 Stream Resets and Mysterious Failed Requests

Reproduce intermittent HTTP/2 RST_STREAM errors with nghttp, read the error code, and fix the framing or intermediary that resets streams silently.

~30 min
api · http2 · debugging

Debug a CrashLoopBackOff in Ten Minutes

Read previous container logs, exit codes, and event messages to classify the crash cause, then fix the right layer instead of restarting harder.

~20 min
deploy · kubernetes · debugging

Debug Kubernetes DNS ndots Latency

Measure resolver latency caused by the ndots search path and reduce unnecessary DNS queries for external names.

~30 min
kubernetes · dns · performance

Debug Mutual TLS Handshake Failures

Use openssl s_client to verify the client certificate chain and cipher agreement when mutual TLS handshakes fail intermittently.

~35 min
tls · security · debugging

Debug OAuth Token Clock Skew

Compare token issued-at, not-before, and expiry against server clocks to prove intermittent 401s come from time drift, not bad tokens.

~30 min
oauth · security · debugging

Diagnose an Infinite Rerender Loop in React

Identify which component re-mounts or re-renders endlessly, trace the state update that fuels the loop, and break the cycle at the dependency.

~30 min
frontend · react · debugging

Debug an SSE Reconnect Storm on the Server Side

Recognize the signature of every EventSource client reconnecting at once, add heartbeat frames, and fix client backoff so idle proxies stop amplifying drops.

~30 min
api · sse · resilience

Debug vi.mock Hoisting Surprises in Vitest

Understand why vi.mock runs before your imports, why factory closures capture stale variables, and how to reference live values correctly.

~25 min
testing · vitest · mocking

Debug Duplicate Webhook Deliveries

Correlate webhook delivery ids and timestamps to distinguish provider retries from duplicate events emitted by your own pipeline.

~30 min
webhook · api · idempotency

Decode Chunked Transfer Encoding Errors

Parse malformed chunked bodies frame by frame to pinpoint a broken chunk size or missing terminator in a streaming response.

~30 min
http · debugging · streaming

Deduplicate a Large CSV with a Hash Index

Remove duplicate rows from a huge CSV using an in-memory hash set of key hashes so it runs in a single streaming pass.

~35 min
data · python · csv

Deduplicate Rows with Window Functions

Use row_number to keep the newest row per natural key and delete the rest without losing referential consistency.

~30 min
sql · database · data

Defer Third-Party Scripts Without Breaking Their Features

Audit what each external script costs on the critical path, load analytics and widgets post-interaction, and verify events still arrive.

~35 min
frontend · performance · third-party

Deploy Pinned Artifacts by Digest, Not by Tag

Pin container images and packages by content digest, record the exact deployed artifact in metadata, and make tag drift impossible to ship.

~25 min
deploy · docker · ci

Detect Memory Leaks with a Soak Test

Drive repeated workload cycles for hours, plot heap against cycle count, and distinguish a leak from a plateau before blaming the runtime.

~40 min
testing · performance · observability

Detect MySQL Lock Wait and Deadlock Patterns

Read InnoDB lock-wait and deadlock diagnostics to find the transaction that always grabs locks in the opposite order.

~35 min
mysql · database · concurrency

Detect Outliers with the IQR Method

Flag statistical outliers using the interquartile range before they distort aggregates and model training.

~25 min
data · statistics · pandas

Detect Schema Drift Between Environments with migra

Compare two live Postgres schemas with migra, review the generated SQL diff, and push the drift back into versioned migrations.

~25 min
database · postgres · ci

Diagnose API Requests That Hang Forever

Spot requests stuck without timeouts, count half-open connections, find the dependency with no deadline, and add end-to-end request deadlines.

~35 min
api · resilience · debugging

Diagnose HTTP 499 Client Aborts in nginx Logs

Find 499 entries in nginx access logs, correlate them with upstream response times, and decide whether clients time out too early or the server is too slow.

~25 min
api · nginx · observability

Diagnose Connection Pool Exhaustion with PgBouncer

Distinguish pool exhaustion from database overload, read PgBouncer stats to find the thief, and size the pool to the database instead of to peak fear.

~30 min
database · postgres · operations

Diagnose SSE Heartbeat Timeout Disconnects

Measure server-sent event heartbeat intervals against proxy idle timeouts to stop long-lived streams from being cut mid-flight.

~25 min
sse · streaming · debugging

Diff Rendered Helm Manifests Before Applying Them

Render charts locally with helm template, diff against the cluster live state, and review the exact YAML that will change before it changes.

~25 min
deploy · helm · kubernetes

Diff a Live API Response Against Its OpenAPI Spec

Capture a real response, validate every field against the published OpenAPI schema, and list exact mismatches before clients discover them by breaking.

~30 min
api · openapi · contract-testing

Drain Traffic Before Maintenance and Restore It Safely

Use load balancer draining with health-check flip, watch in-flight requests complete, and restore traffic in stages with a rollback exit.

~30 min
deploy · operations · nginx

Validate Kubernetes Manifests with kubeconform

Validate manifests against the target server schema with kubeconform in CI before they reach the cluster.

~25 min
kubernetes · ops · validation

Enable auditd execve Rules

Add audit rules that record process execution on sensitive hosts so unexpected commands leave an auditable trail.

~30 min
security · linux · audit

Enable sudo Command Logging

Log every sudo invocation to syslog with the invoking user and command so privileged actions are auditable.

~25 min
security · linux · audit

Encrypt Secrets in Git with SOPS and age

Store encrypted secrets beside your configs with SOPS and age, keep decryption keys outside the repo, and rotate without re encrypting everything.

~25 min
security · secrets · git

Enforce an API Latency Budget as a CI Gate with k6

Encode percentile thresholds in a k6 scenario, run it against a staged build in CI, and fail the merge when p95 or error rate breaches budget.

~35 min
testing · performance · ci

Enforce a Non-Root Container User

Set a numeric non-root user and group in the image so a container escape does not start with root privileges.

~25 min
container · security · hardening

Export a Large Table to CSV Fast

Use COPY TO with a server-side file or stdout stream to export large tables far faster than row-by-row SELECT.

~20 min
postgresql · database · data

Fix an N+1 Query Problem in a GraphQL Resolver

Detect N+1 resolver queries with request-scoped query logging, batch them with DataLoader, and prove the query count drops from 1+N to exactly 2.

~45 min
api · graphql · performance

Fix React Hydration Mismatches at the Source

Read the exact server-versus-client diff, find the nondeterministic render input, and isolate it with suppressHydrationWarning only as a last resort.

~30 min
frontend · react · ssr

Find the Hot Path in Node with a CPU Flame Graph

Capture a sampling profile under load, read the flame graph width-first to find the widest frames, and verify the fix with a second capture.

~40 min
performance · nodejs · profiling

Flatten Nested JSON Arrays into Queryable Rows

Unwind arbitrary-depth arrays into flat rows with jq or Node streaming, keeping parent context and path provenance on every record.

~25 min
data · json · etl

Fuzz a JSON Parser with Property Tests

Generate random and adversarial inputs to assert your JSON handling never crashes and always round-trips valid documents.

~35 min
testing · fuzzing · javascript

Deduplicate Fuzzy-Matched Records Without Losing Real Rows

Generate similarity-scored candidate pairs, review the match threshold with humans, and merge duplicates through an auditable, reversible process.

~45 min
data · data-quality · deduplication