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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Add Bash Shell Completion
Ship a completion script that suggests subcommands and flags so users discover options without reading docs.
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.
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.
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.
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.
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.
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.
Assert Structured Log Fields
Capture structured logs in tests and assert on fields rather than substrings so logging behaviour is regression-tested.
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.
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.
Audit Missing Security Headers
Scan responses for missing HSTS, CSP, X-Content-Type-Options, and frame protections, then fix them with a middleware.
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.
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.
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.
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.
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.
Batch Network Calls Without Losing Latency
Coalesce many small requests into fewer batched calls using a short scheduling window to cut round-trip overhead.
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.
Block Unnecessary Outbound Egress
Apply a default-deny egress policy so a compromised workload cannot reach arbitrary hosts on the internet.
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.
Build argparse Subcommands
Structure a Python CLI with subparsers so each command has its own arguments and a shared top-level parser.
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.
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.
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.
Cache Serialization with MessagePack
Swap JSON for MessagePack in a hot cache path to cut serialization CPU and payload size without changing semantics.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Debounce ResizeObserver Layout Work
Throttle layout work triggered by ResizeObserver so rapid resizes do not thrash the main thread.
Debug API Payload Schema Rejection
Reproduce a 422 payload rejection and use schema validation diagnostics to find the exact property path that fails.
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.
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.
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.
Debug GraphQL Persisted Query Misses
Resolve persisted-query-not-found errors by checking the APQ hash registry and hash generation between client and server.
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.
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.
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.
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.
Debug Kubernetes DNS ndots Latency
Measure resolver latency caused by the ndots search path and reduce unnecessary DNS queries for external names.
Debug Mutual TLS Handshake Failures
Use openssl s_client to verify the client certificate chain and cipher agreement when mutual TLS handshakes fail intermittently.
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.
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.
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.
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.
Debug Duplicate Webhook Deliveries
Correlate webhook delivery ids and timestamps to distinguish provider retries from duplicate events emitted by your own pipeline.
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.
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.
Deduplicate Rows with Window Functions
Use row_number to keep the newest row per natural key and delete the rest without losing referential consistency.
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.
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.
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.
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.
Detect Outliers with the IQR Method
Flag statistical outliers using the interquartile range before they distort aggregates and model training.
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.
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.
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.
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.
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.
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.
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.
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.
Validate Kubernetes Manifests with kubeconform
Validate manifests against the target server schema with kubeconform in CI before they reach the cluster.
Enable auditd execve Rules
Add audit rules that record process execution on sensitive hosts so unexpected commands leave an auditable trail.
Enable sudo Command Logging
Log every sudo invocation to syslog with the invoking user and command so privileged actions are auditable.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.