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.
Generate Realistic Test Data with Faker
Produce a million-row dataset with believable distributions, seeded reproducibility, and referential integrity, then load it with COPY.
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.
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.
Harden TLS Cipher Suites
Restrict a server to modern TLS versions and strong ciphers, then verify with a scanner and client handshake tests.
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.
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.
Hydrate Islands Progressively
Hydrate interactive components on idle or on visibility so static content is interactive without blocking the main thread.
Implement CLI Config Precedence
Define a clear precedence of flags over environment over config file over defaults so behaviour is predictable.
Implement Progressive Delivery Steps
Roll out a change in controlled increments with automated analysis between steps so a bad release is caught early.
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.
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.
Inspect and Defragment etcd Safely
Check etcd database size and fragmentation, then defragment one member at a time with a backup first.
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.
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.
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.
Instrument Unit Tests with a Coverage Threshold
Enable coverage instrumentation and set an enforceable threshold so new code cannot merge below the agreed bar.
Isolate HTTP 502 Upstream Reset
Correlate gateway access logs with upstream connection resets to prove which backend instance is closing connections early.
Lazy-Load Route Chunks in Vite
Split routes into dynamic imports so the initial bundle stays small and heavy views load on demand.
Diagnose Container CPU Throttling
Read cgroup throttling counters to prove whether a container's latency comes from CPU limits rather than slow code.
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.
Measure PostgreSQL Index Bloat
Use pgstattuple and statistics to estimate index bloat and decide whether a REINDEX is worth the lock cost.
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.
Merge Multiple Parquet Files Safely
Consolidate many small Parquet files into fewer larger ones to cut metadata overhead and improve scan efficiency.
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.
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.
Mock Time with Sinon Fake Timers
Control time in tests with fake timers so debounce, retry, and timeout logic is deterministic instead of flaky.
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.
Build Multi-Architecture Images with buildx
Build and push amd64 and arm64 variants in one command so the same tag runs on mixed clusters.
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.
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.
Optimize Array Deduplication with a Set
Replace O(n squared) deduplication loops with a hash set so large arrays dedupe in linear time.
Reduce Go Allocations with sync.Pool
Reuse hot short-lived buffers through sync.Pool to cut garbage collection pressure on high-throughput paths.
Serve Responsive Images with srcset
Provide width descriptors and modern formats so devices download the smallest adequate image.
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.
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.
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.
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.
Parallelize Vitest Across Threads
Tune the Vitest pool and per-file isolation so a large suite finishes faster without flaky shared-state failures.
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.
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.
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.
Write Partitioned Parquet Datasets
Write Parquet partitioned by a low-cardinality column so downstream queries prune partitions and scan far less data.
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.
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.
Prefetch Critical Resources with Resource Hints
Use preconnect and prefetch hints for the next likely navigation so critical resources arrive before they are requested.
Preflight Check Cluster Capacity
Compare requested resources against allocatable capacity so a deployment does not land pods in a permanently pending state.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Rebuild a MongoDB Index Online
Rebuild a fragmented MongoDB index without blocking writes by leveraging rolling index builds on a replica set.
Redact PII in Application Logs
Add structured log redaction for emails, tokens, and card numbers so sensitive data never lands in log storage.
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.
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.
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.
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.
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.
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.
Restrict CORS to an Origin Allowlist
Replace wildcard CORS with a strict origin allowlist that also handles credentials and preflight safely.
Enforce Pod Security Admission
Apply the restricted Pod Security Standard namespace by namespace so privileged pods are rejected at admission.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Scan Dependencies with OSV-Scanner
Scan lockfiles and container images for known vulnerabilities with OSV-Scanner and fail CI only on actionable findings.
Schedule an ECS Task with EventBridge
Run a periodic containerised job on a schedule with EventBridge rules and verify retries and logging.
Scrub PII from a Dataset with pandas
Detect and pseudonymise direct identifiers in a dataframe before sharing it with analysts.
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.
Set Statement Timeout per Role
Apply a default statement_timeout to reporting roles so a runaway query cannot monopolise connections and starve the pool.
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.
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.
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.
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.
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.
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.
Snapshot REST API Contracts
Capture normalised response snapshots for REST endpoints so unintended contract changes fail review instead of reaching clients.
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.
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.
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.
Transform Gigabyte Files with Constant Memory Streams
Replace readFileSync loops with pipeline streams, apply backpressure-aware transforms, and verify output equivalence on a sample.
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.
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.
Test Error Branches with Injected Failures
Inject dependency failures at call boundaries to exercise catch and fallback paths that normal runs never reach.
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.
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.
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.