Recipes
Step-by-step solutions for real development tasks.
699 published
Page 6 of 7
Break a Slow HTTP Response into DNS, TLS, and Server Time
Use the curl write-out timer to split one slow request into name lookup, connect, TLS, time-to-first-byte, and transfer phases, then aim the fix at the right layer.
Track Deployments in Sentry to Correlate Errors with Releases
Send release events from CI, tag each deploy with git SHA and environment, and use release stats to catch error-rate regressions within minutes.
Track GraphQL Operation Usage to Find Abusive Queries
Fingerprint every GraphQL operation by name and hash, aggregate call counts and depth, and spot the one client sending giant or unbounded queries.
Transform CSV to NDJSON in a Stream
Convert a large CSV to newline-delimited JSON with a streaming reader and writer so memory stays flat regardless of file size.
Guarantee Cleanup Runs When a Shell Script Exits
Install EXIT and signal traps that release locks, remove temp files, and kill child processes on success, failure, and Ctrl-C alike.
Trap Focus Correctly in a Modal Dialog
Move focus in on open, cycle Tab inside the dialog, return focus on close, and handle background scroll and screen-reader announcement.
Tune Argon2id Password Hashing Parameters
Pick memory, iterations, and parallelism from your hardware budget and target latency, then verify the choices against both login UX and attack cost.
Tune JVM G1 Heap Regions
Adjust G1 region size and pause target to cut GC pauses on a heap that is too large for the default region count.
Tune a PodDisruptionBudget minAvailable
Set a disruption budget that protects availability during drains without blocking voluntary disruptions entirely.
Benchmark MySQL InnoDB Flush Settings
Measure write throughput at different innodb_flush_log_at_trx_commit levels and pick the safest setting that meets the durability target.
Tune Node Heap and GC Settings from Evidence
Chart heap usage and GC pause times across load, identify premature promotion and oversized young generation, then set flags deliberately.
Tune Autovacuum for a High-Churn Table
Watch dead tuples accumulate, compute the actual churn rate, set per-table scale factors and cost limits, and verify bloat stays flat.
Tune Kubernetes Rolling Updates for Zero Downtime
Set maxSurge, maxUnavailable, readiness gates, and preStop sleep so pods replace each other without serving a single failed request.
Tune a Rust Release Profile for Throughput
Enable LTO and codegen tuning in the release profile to improve runtime throughput at the cost of build time.
Write Tests That Actually Catch Concurrency Races
Use stress loops, synchronization barriers, and race detectors to make latent races fail deterministically in the test suite.
Vacuum SQLite Safely Offline
Reclaim SQLite space with VACUUM INTO and swap the compacted file atomically to avoid blocking a live application.
Validate a TLS Certificate Chain with openssl Only
Hand-verify the served chain, intermediate match, expiration, and hostname coverage before blaming the app for handshake failures.
Validate JSONL with Expectation Suites
Define expectation suites over a JSONL dataset to catch missing fields and range violations before loading a warehouse.
Verify SameSite Cookie Behavior Across Browsers
Set deliberately misconfigured SameSite cookies in a test page, observe which requests carry them, and prove the hardening actually blocks cross-site sends.
Verify Database Transaction Rollback
Assert that a failed multi-step write leaves no partial state, using a real database in the test rather than mocks.
Verify Helm Values Override Precedence
Render charts with multiple values files to confirm the final merged values match the intended precedence before release.
Verify Provider Contracts with Consumer-Driven Pact
Publish consumer expectations as pacts, verify the provider against them in CI, and break the build on any contract drift before deploy.
Verify Rate Limiting Holds Under a Burst of Concurrent Requests
Prove that an express-rate-limit middleware actually throttles by firing concurrent bursts, checking 429 headers, and counting admitted versus rejected requests.
Verify SQLite Database Integrity Before and After Backup
Run integrity_check on the source, take an online backup with the backup API instead of copying the file, and verify the copy row-for-row.
Prove Test Isolation with Random Order Execution
Run the suite under shuffled orders and multiple seeds, identify tests that leak state into siblings, and fix the leak at the source.
Version Container Images with the Git SHA
Tag images with immutable commit SHAs and digest digests so deployments reference an exact artifact rather than a moving tag.
Virtualize a 10,000-Row List Without Breaking Search or Scroll
Render only the visible window plus overscan, restore scroll position on navigation, and keep typeahead search working against the full dataset.
Write Custom Arbitraries for Business Rules
Move property tests beyond primitives by composing fast-check arbitraries for money, date ranges, and entity graphs that respect invariants.
Write Unit Tests for Error Paths First
Inventory failure modes per dependency, force each one in a test, and assert the observable behavior users see when things go wrong.
Write Shell Scripts That Are Safe to Run Twice
Make setup and deploy scripts idempotent: guard file creation, detect prior success, and structure mutations so reruns converge instead of duplicate.
Test Access Control as a Matrix
Enumerate role, ownership, and tenant combinations, assert 401 versus 403 versus 404, and catch broken object-level authorization.
Run a Quarterly Access Review
Generate an IAM credential report, flag unused keys and administrator roles, and record reviewer sign-off before the due date.
Fuzz the API Against Its OpenAPI Schema
Drive Schemathesis from the OpenAPI document, skip destructive endpoints, and turn every unexpected 500 into a regression test.
Block Argo CD Syncs During a Release Freeze
Use sync windows to deny automatic syncs during a freeze while still allowing audited manual syncs for real emergencies.
Attest Release Archives and Verify Before Deploy
Sign a build artifact with GitHub attestations, then verify its digest and source ref in the deploy job so a swapped archive never ships.
Export Database Audit Logs to Object Storage
Enable pgaudit for DDL and role changes, ship the log stream to object storage, and keep tamper-resistant copies for compliance review.
Encrypt Backups Before Uploading
Encrypt database dumps with age recipients before they leave the host, keep the identity offline, and prove decryption during a restore test.
Switch Traffic with a Blue-Green Service Cutover
Run the new version beside the old one, flip the Service selector in one step, and keep the old ReplicaSet warm for an instant rollback.
Share a Docker Build Cache Across CI Runs
Use the GitHub Actions cache backend for BuildKit so image rebuilds reuse layers instead of reinstalling dependencies every run.
Attach Build Provenance to Release Artifacts
Generate a signed SLSA provenance attestation in GitHub Actions and verify it before deploying the container image.
Isolate Downstreams with Bulkhead Pools
Give each downstream dependency its own bounded connection or concurrency pool so one slow service cannot consume every shared slot.
Invalidate CDN Cache by Tag
Attach cache tags to origin responses and purge a whole tag group on deploy or data change instead of enumerating every URL and query string.
Gate a Canary on Error Rate and Latency
Compare canary metrics with a Prometheus query, abort automatically on regression, and fail closed when the canary has no traffic.
Review Cluster Capacity Headroom
Compare allocatable CPU and memory with requests, simulate losing one node, and record the headroom needed before peak season.
Purge CDN Cache After Every Deploy
Invalidate only the paths that changed, wait for completion, and verify that the new HTML is served from the edge.
Serve Stale Content on Origin Errors
Configure stale-if-error and stale-while-revalidate so a caching proxy keeps serving a recent copy when the origin returns 5xx or times out.
Alert Before a TLS Certificate Expires
Monitor cert-manager renewal status and expiry with a Prometheus rule, so a failed renewal pages someone before the outage.
Run a Controlled Latency Chaos Experiment
Inject 500ms of latency into one dependency with Toxiproxy during business hours, observe SLO burn, and verify timeouts and fallbacks.
Inject a Clock Instead of Calling Date.now
Pass a clock through the domain code, freeze time in tests, and assert expiry exactly at the TTL boundary instead of sleeping.
Add an AWS Budget Alert for Monthly Cloud Spend
Provision a monthly AWS Cost Budget with actual and forecasted thresholds that publish to an SNS topic, so spend anomalies reach the team before the invoice.
Detect and Report CloudFormation Stack Drift
Run drift detection on a schedule, parse resource-level results, and alert on the specific resources changed outside the stack.
Upgrade a Kubernetes Cluster One Minor Version at a Time
Check version skew and removed APIs, upgrade the control plane before nodes, and validate workloads on a canary node pool.
Alert on Runtime Config Drift from Git
Diff live ConfigMaps against the manifests in Git, alert on differences, and stop emergency edits from becoming permanent.
Drain Connections Before Pod Termination
Combine a preStop sleep, a long enough grace period, and readiness gating so in-flight requests finish before Kubernetes removes a pod from service.
Catch Connection Pool Leaks in Tests
Push concurrency past the pool size and assert every acquired client is returned, so a missing release fails in CI instead of hanging production.
Add Container Health Probes That Match Reality
Separate startup, liveness, and readiness probes so slow boots are not killed and a broken dependency does not restart-loop every pod.
Harden a Container with a Read-Only Root Filesystem
Run a Kubernetes container with a read-only root filesystem, drop Linux capabilities, and mount only the writable paths the workload actually needs.
Create a Cloud Cost Anomaly Alert
Enable AWS Cost Anomaly Detection with a dollar threshold and route alerts to the owning team's on-call channel.
Block Deploys That Miss Cost Allocation Tags
Validate required cost tags on infrastructure plans and block resources that would be invisible to the billing report.
Monitor Cron Jobs with Dead-Man's-Switch Heartbeats
Send a heartbeat only after a scheduled backup succeeds, and alert when the heartbeat is late, so silent cron failures are detected within the expected window.
Build a Tenant Data Deletion Job
Delete tenant rows across tables in dependency order, remove object storage prefixes, and write a completion receipt with counts.
Add a Data Integrity Reconciliation Check
Compare row counts and content fingerprints between primary and replica on a schedule, and alert on drift before it reaches a report.
Test Data Masking Before It Ships
Assert that emails, card numbers, and tokens are masked in logs, exports, and fixtures, and that raw values never reach shared storage.
Route Read Queries to a PostgreSQL Replica Safely
Split primary writes from replica reads with explicit consistency rules, request-level pinning, and a replication lag guard so stale reads never leak into user-visible paths.
Validate Pooled Database Connections
Combine keepalives, idle timeouts, lifetime limits, and a checkout probe so dead sockets are replaced instead of failing user requests.
Gate Deploys on Backward-Compatible Migrations
Lint migrations for destructive changes before they run, and require expand and contract releases so old and new code can coexist.
Enforce Database Query Timeouts
Set statement_timeout, lock_timeout, and idle_in_transaction_session_timeout per role and transaction so runaway queries cannot exhaust the pool.
Build a Dead Letter Queue Dashboard
Export dead-letter depth and message age to Prometheus, add a Grafana panel, and give operators a documented replay command.
Freeze Dependency Updates Before a Release
Pin installs with a frozen lockfile and pause automated update pull requests during the release window, then unfreeze deliberately.
Block Vulnerable Dependencies at Pull Request Time
Run GitHub dependency review on every pull request and fail when a new dependency brings a known vulnerability or a denied license.
Fail Over DNS to a Standby Region
Create health-checked primary and secondary records, verify the failover with a forced health check, and account for TTL lag.
Verify DNS TTL Before a Migration
Inspect TTLs across authoritative and public resolvers, lower them ahead of a cutover, and confirm propagation before switching traffic.
Inject an Error Rate Into a Dependency
Return a controlled share of 500s from a fake dependency, then assert retry limits, circuit breaking, and graceful degradation.
Add ETag Revalidation to Read Endpoints
Derive stable entity tags, answer If-None-Match with 304, and keep validators correct when compression or CDNs transform the bytes.
Audit Every Feature Flag Change
Record who toggled which flag, when, and from where in an append-only table, and alert on production changes to high-risk flags.
Add a Feature Flag Kill Switch with Fail-Safe Defaults
Ship a database-backed kill switch that disables a risky feature without redeploying, with a bounded cache, safe defaults, and an audit trail for every toggle.
Release Behind a Flag and Remove It on Schedule
Ship dark, enable for a small percentage, watch metrics, and delete the flag within a fixed window so branches do not accumulate.
Test Both Sides of a Feature Flag
Run the same behaviour tests with the flag on and off, assert the default and kill switch, and retire the flag when it expires.
Add Full-Text Search Without LIKE Scans
Build a generated tsvector column, index it with GIN, and query with websearch_to_tsquery and ranking instead of leading-wildcard LIKE.
Implement a GDPR Right-to-Erasure Deletion Job
Build an idempotent erasure job that deletes disposable personal data, anonymizes retained records, records a minimal audit tombstone, and verifies completion across tables.
Fan Out CI with a GitHub Actions Matrix
Run the same job across supported runtimes in parallel, fail fast on the first broken combination, and keep one required status check.
Add Golden File Tests for API Responses
Commit canonical API responses as golden files, review every diff in pull requests, and regenerate only through an explicit opt-in command.
Add a gRPC Health Check Probe
Expose the standard grpc.health.v1 service, wire Kubernetes probes through grpc-health-probe, and flip to NOT_SERVING during shutdown.
Lint and Render Helm Charts Before Every Release
Catch schema errors, missing values, and broken templates by linting and rendering every chart in CI before it reaches a cluster.
Enable HTTP/2 on NGINX with ALPN
Serve an existing HTTPS virtual host over HTTP/2 by enabling ALPN, turning on the ngx_http_v2 module, and verifying the negotiated protocol with curl.
Review Terraform Plans Before Anyone Applies
Publish the plan as a reviewable artifact, require approval, and apply exactly that plan so the approved diff is what reaches the cloud.
Clean Up Expired Idempotency Keys
Partition idempotency records by day, drop old partitions on a schedule, and keep a retention window longer than the client retry horizon.
Test Idempotency Keys End to End
Replay the same request key and assert one side effect, an identical response, and a conflict when the payload changes.
Fail the Pipeline on Fixable Image Vulnerabilities
Scan the built container image, ignore unfixed findings, and block promotion on high or critical vulnerabilities that already have a patch.
Tune Ingress Timeouts for Slow Endpoints
Raise proxy read and send timeouts only for routes that need them, and keep the default short everywhere else.
Terminate TLS at the Ingress with cert-manager
Request a certificate through an ACME issuer, store it in a Secret, and redirect every plain HTTP request to HTTPS.
Index JSONB Attributes for Containment Queries
Add a GIN index on JSONB attributes, query with containment operators, and confirm the planner uses the index instead of scanning.
Tune a HorizontalPodAutoscaler for Stable Scaling
Set behavior policies, a sensible utilization target, and a floor that survives bursty traffic instead of flapping between replica counts.
Spread Replicas Across Zones with Topology Constraints
Use topologySpreadConstraints with DoNotSchedule so one zone failure cannot take every replica, then verify the spread on real pods.
Layer Environment Differences with Kustomize Overlays
Keep one shared base manifest and a thin overlay per environment, so staging and production differ only where they must.
Gate Releases on a Dependency License Allowlist
Inventory production dependency licenses, fail on copyleft licenses outside policy, and keep the report with every release.
Write a Realistic Load Test Scenario
Model arrival rate, ramp-up, and think time in k6, assert p95 latency and error thresholds, and run it against staging before release.
Assert Structured Logs in Tests
Capture log output in tests, assert required fields and redaction, and catch missing request context before production debugging does.
Test That Logs Redact Sensitive Fields
Add an automated test that captures structured log output and fails if emails, tokens, or card numbers appear in plain text.
Sample High-Volume Info Logs Without Losing Errors
Reduce log volume and cost by sampling info-level events deterministically per request while keeping warnings, errors, and slow requests at full fidelity.