Recipes
Step-by-step solutions for real development tasks.
699 published
Page 7 of 7
Bound Lock Waits in Schema Migrations
Set lock_timeout and statement_timeout inside migrations so DDL fails fast instead of queueing behind a long query and freezing reads.
Test Migration Rollbacks in CI
Apply, roll back, and re-apply every migration against a throwaway database, and fail the build when the down path breaks or drifts.
Add Mutation Testing to Critical Modules
Run Stryker on money and authorization code, set a mutation score threshold, and strengthen tests for the mutants that survive.
Drain a Node Without Dropping Requests
Cordon first, drain with explicit flags, respect disruption budgets, and verify workloads moved before terminating the node.
Escalate Unacknowledged Alerts Automatically
Configure Alertmanager grouping and repeat intervals plus a two-tier escalation path, so a missed page reaches someone awake.
Standardize the On-Call Handoff
Run a 15-minute handoff that transfers open incidents, recent changes, and known risks with a written summary in the channel.
Retry Outbound Webhooks with Bounded Exponential Backoff
Deliver outbound webhooks reliably with bounded exponential backoff, jitter, Retry-After handling, and a replayable failure store for terminal errors.
Test Pagination at Its Boundaries
Cover empty results, exact page size, last page, invalid cursors, and tied sort keys so clients never loop or skip records.
Add a Partial Index for Active Rows
Index only the rows queries actually read, cutting index size and write cost for soft-deleted or status-filtered tables.
Order Row Locks to Prevent Deadlocks
Acquire locks in one deterministic order across every writer, add a lock timeout, and prove with a concurrency test that 40P01 stops happening.
Scan Databases for Unlabeled PII
Sample column values, run Presidio analyzers, and produce a report of likely personal data that lacks classification tags.
Protect Availability with a PodDisruptionBudget
Set minAvailable for critical deployments and verify that node drains respect the budget instead of evicting every replica.
Run Post-Deploy Smoke Checks with Automatic Rollback
Verify the new version with real requests, retry briefly, and roll back automatically when the checks keep failing.
Add a Blameless Postmortem Template
Ship a postmortem template with timeline, contributing factors, and owned action items, and enforce required sections in CI.
Expose Application Metrics for Prometheus Scraping
Add a token-protected /metrics endpoint with default Node.js metrics, a low-cardinality request histogram, and a Prometheus scrape job that reports the target up.
Add Property-Based Tests for Business Rules
Generate inputs with fast-check, assert invariants that must always hold, and let shrinking reduce a failure to the smallest reproducer.
Set a Query Budget per Request
Count SQL statements per request, fail tests that exceed the budget, and expose the count so N+1 regressions surface before users do.
Detect Query Plan Regressions in CI
Capture EXPLAIN output for critical queries as golden files and fail CI when a plan introduces sequential scans or a much higher cost.
Alert on Queue Backlog Age, Not Depth
Page on ApproximateAgeOfOldestMessage with a CloudWatch alarm so a stalled consumer is detected before the queue depth explodes.
Return Standard Rate Limit Headers
Expose RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset on every response and keep 429 bodies consistent so clients can back off.
Gate Reads on Replica Lag
Measure replay lag on the replica, route to the primary above a threshold, and alert before stale reads become visible to users.
Automate Dependency Updates with Renovate
Configure Renovate to group non-major updates, pin GitHub Actions to commit SHAs, require passing CI, and cap the number of concurrent pull requests.
Enforce a Request Body Size Limit
Cap JSON and raw payloads at the parser, reject oversized requests with a stable 413, and prove the limit before a single byte is buffered.
Add a Request Priority Queue
Route interactive traffic ahead of batch work with separate queues, weighted workers, and aging so latency-sensitive requests keep their SLO.
Enable Response Compression Safely
Compress JSON and HTML with gzip, skip pre-compressed assets, keep Vary correct, and measure the transfer win instead of assuming it.
Run a Quarterly Restore Drill
Restore the latest production backup into an isolated database, validate row counts and checksums, and record how long it took.
Rehearse a Rollback Before You Need It
Time a real rollback in staging, verify the old version still handles new data, and write the exact commands into the release runbook.
Fail the Deploy When a Rollout Stalls
Gate the pipeline on kubectl rollout status with a timeout, inspect the stuck ReplicaSet, and roll back instead of hanging.
Check Runbook Links in CI
Run lychee against runbook Markdown on a schedule so dead dashboards, wiki pages, and pager links are fixed before an incident.
Gate Deploys on Schema Compatibility
Run a Schema Registry compatibility check in CI before merging producer changes so backward-incompatible Avro updates never reach consumers.
Schedule Automatic Database Secret Rotation
Enable Secrets Manager rotation on a 30-day schedule, make consumers reload credentials, and prove the old password stops working.
Scan Commits for Secrets Before They Reach main
Run gitleaks on every push and pull request, rotate anything it finds, and block merges until the history is clean.
Declare Service Ownership in a Catalog
Add a catalog-info.yaml with owner, lifecycle, and on-call reference, and validate that every production service has an owner in CI.
Harden Session Cookies Against Theft and CSRF
Set HttpOnly, Secure, SameSite, and __Host- cookie attributes, rotate session IDs on login, and verify that browsers reject unsafe cookie writes.
Run a Monthly SLO Review
Pull error budget burn from Prometheus, compare it with the SLO target, and decide whether to ship features or invest in reliability.
Keep Unique Constraints Working With Soft Deletes
Swap a plain unique constraint for a partial unique index so active rows stay unique while deleted rows stop reserving the value forever.
Version Static Assets for Long-Lived Caching
Use content-hashed filenames with immutable caching, keep HTML revalidated, and verify a deploy never serves mismatched assets.
Partition a Large Table by Time Range
Convert a growing events table into monthly partitions, keep indexes attached, and verify that queries scan only the partitions they need.
Test Tenant Isolation End to End
Attempt cross-tenant reads and writes with another tenant's ids, assert 404, and prove row-level security fails closed without context.
Detect Terraform Drift on a Schedule
Run a read-only plan nightly, use detailed exit codes, and alert on real drift instead of waiting for the next apply to fail.
Enable Terraform State Locking and Unlock Safely
Lock remote state with a conditional write or DynamoDB table, and force-unlock only after confirming no apply is still running.
Isolate Test Fixtures Between Tests
Give each worker its own database from a migrated template, roll back per-test writes, and stop depending on execution order.
Run Integration Tests With Testcontainers
Start a disposable PostgreSQL container per test run, apply the real migrations, and tear it down so tests never share a database.
Inject Timeouts at the Dependency Boundary
Make a downstream call hang in a controlled way, then assert the timeout path returns 504, cancels the request, and releases resources.
Monitor TLS Certificate Expiry
Probe TLS endpoints with blackbox_exporter and alert when a certificate expires within 21 days or the chain fails validation.
Assert Spans in Trace Tests
Use an in-memory span exporter to assert span names, parent-child links, attributes, and error status for a single request.
Retry Transactions on Serialization Failures
Retry the whole unit of work on SQLSTATE 40001 and 40P01 with bounded backoff, and never retry errors that will fail again.
Test Webhook Signature Verification
Sign payloads the way the provider does, then assert that tampering, replay, and timestamp skew are rejected before any handler runs.
Roll Out Config Changes Without Restarting Everything
Version ConfigMaps, roll pods gradually with maxUnavailable 0, and keep serving when a configuration key is missing.
Apply a Zero-Downtime PostgreSQL Column Migration
Use the expand-contract pattern with lock timeouts, batched backfills, and a bidirectional trigger to rename a column without breaking rolling deploys.
Add API Deprecation Headers
Announce deprecation with Deprecation, Sunset, and Link headers, keep clients informed, and remove the old endpoint only after the sunset date.
Add an Append-Only Audit Log
Record who changed which record, when, and from where in an append-only table written in the same transaction as the business change.
Warm Critical Cache Keys Before Traffic
Preload high-value keys after a deploy or cache flush, coalesce the warm-up, and verify hit ratio without turning startup into a stampede.
Add a Circuit Breaker Around a Dependency
Wrap a flaky dependency with a closed/open/half-open circuit breaker, cap failures, allow one probe, and expose state for metrics.
Set a Connection Pool Budget
Size database pools from the server's connection limit, reserve capacity for operations, and verify the total across replicas and background workers.
Add a Dead-Letter Queue Policy
Bound retries, route poison messages to a DLQ with context, alarm on depth and age, and document a safe replay procedure.
Add a Dependency Lockfile Audit
Audit the committed lockfile for known vulnerabilities, fail CI on high severity, and remediate through version updates rather than blanket overrides.
Add an Error-Budget Burn-Rate Alert
Alert on how fast the error budget is being consumed with multi-window burn rates, instead of waiting for a monthly SLO to be exhausted.
Add Event Schema Versioning with an Envelope
Wrap events in a versioned envelope, keep payload changes compatible, and upcast old versions when reading so historical events remain replayable.
Add Fencing Tokens to Protected Writes
Attach a monotonically increasing token to every write and reject older tokens at storage so a paused lock holder cannot overwrite newer data.
Add a Graceful Degradation Fallback
Serve a stale or reduced response when a dependency fails, mark it explicitly, and verify that the fallback cannot mask a data-integrity problem.
Add a Graceful Shutdown Handler
Handle SIGTERM in a Node.js service by failing readiness, stopping new connections, draining in-flight requests, and forcing exit after a deadline.
Add HTTP Strict Transport Security
Send a Strict-Transport-Security header only over HTTPS, start with a short max-age, verify it at the edge, and understand the commitment of preload.
Add an Idempotent Consumer Handler
Record message ids in the same transaction as the business change so at-least-once delivery produces a single effect after retries and restarts.
Add an Idempotent Webhook Handler
Verify webhook signatures over the raw body, deduplicate event ids in a transaction, and return quickly so provider retries cannot apply the same event twice.
Set Kubernetes Resource Requests and Limits
Choose CPU and memory requests from measured usage, set limits that prevent noisy neighbors, and verify QoS, throttling, and OOM behavior.
Add Latency Fault Injection for Resilience Tests
Inject bounded latency behind an explicit test flag, verify timeouts and fallbacks, and guarantee the injection is disabled outside test environments.
Add Load-Shedding Middleware
Reject new work with 503 and Retry-After when in-flight requests exceed a measured limit, keeping accepted requests within their latency target.
Add an OpenAPI Contract Test
Lint the OpenAPI document in CI, exercise every endpoint with Schemathesis against a test server, and fail on responses that violate the contract.
Add OpenTelemetry Tracing to a Node.js Service
Initialize the OpenTelemetry SDK before the app loads, instrument HTTP and database calls, export traces, and shut down cleanly.
Add Optimistic Locking with a Version Column
Prevent lost updates by adding a version column, updating with a version predicate, and returning 409 when two writers modify the same row concurrently.
Add an Outbox Relay
Publish events reliably by writing them to an outbox in the business transaction, then relaying unpublished rows with retries and idempotent consumers.
Add a Performance Budget to CI
Set gzip size limits for entry bundles, fail pull requests that exceed them, and keep the budget visible as a review signal rather than a surprise outage.
Add PostgreSQL Slow Query Logging
Enable slow query logging with a measured threshold, use pg_stat_statements for aggregates, and analyze plans without logging sensitive bind values.
Add Rate Limiting Middleware
Add a fixed-window rate limiter to an Express service, return 429 with Retry-After, and understand when an in-memory limiter stops being correct.
Coalesce Concurrent Requests for the Same Key
Merge simultaneous cache misses for one key into a single origin call, share the result, and clean up the in-flight entry so retries are possible.
Add a Request Timeout Wrapper
Enforce a per-request deadline in Node.js, propagate cancellation to downstream calls, and return a clear 503 instead of holding connections open.
Generate and Scan an SBOM in CI
Produce a software bill of materials for every build, scan it for known vulnerabilities, retain it with the release, and fail the pipeline on high-severity findings.
Add an SLO Dashboard
Define a request success SLI, record it with Prometheus rules, and chart the SLO target, current attainment, and remaining error budget.
Add Structured JSON Logging
Replace ad-hoc console output with structured JSON logs that carry request ids, status, latency, and redacted headers for reliable production debugging.
Add a Test Data Builder
Replace ad-hoc test fixtures with a builder that has valid defaults, explicit overrides, and small factory functions for related objects.
Configure Redis Memory and Eviction Policy
Set a memory ceiling and an eviction policy that matches the data's role, monitor evictions, and prevent Redis from silently deleting queues or sessions.
Pin GitHub Actions by Commit SHA
Replace mutable action tags with full commit SHAs, keep the version in a comment, and let Dependabot update pins without reopening a supply-chain hole.
Verify Database Backups by Restoring Them
Prove a PostgreSQL backup is usable by restoring it into an isolated database, comparing row counts and checksums, and recording the recovery time.
Add a Health Check Endpoint
Expose a liveness and readiness endpoint that checks critical dependencies with a timeout, so orchestrators can restart or remove unhealthy instances.
Add Idempotency Keys to a Write Endpoint
Accept an Idempotency-Key header, store the request fingerprint and response, and replay the original result for retries instead of creating duplicates.
Add Pre-commit Hooks for Lint and Tests
Install the pre-commit framework, run lint and fast tests before every commit, and keep hooks reproducible across the team instead of relying on manual discipline.
Propagate Request IDs Through Logs
Generate or accept a traceable request ID, attach it to every log line and response, and propagate it to downstream calls so one user action can be followed end to end.
Add a Content Security Policy with Nonces
Ship a restrictive Content Security Policy that blocks inline script injection, uses per-request nonces, and is verified without breaking legitimate assets.
Configure CORS with an Origin Allowlist
Allow only trusted browser origins, handle preflight requests correctly, and avoid the insecure combination of wildcard origins with credentials.
Recover a Deleted Git Branch
Use the reflog to find the last commit of a deleted local branch and recreate the branch before garbage collection removes the commit.
Undo a Bad Commit with git revert
Undo a commit on a shared branch by creating a new inverse commit, preserving history and avoiding the disruption of a force-push.
Implement Stable Cursor Pagination
Paginate a changing dataset with an encoded cursor instead of offsets, keeping results stable when rows are inserted or deleted between requests.
Resolve a Merge Conflict Without Losing Work
Inspect both sides of a conflict, choose or combine the intended changes, stage the result, and verify with tests before completing the merge.
Rotate a Leaked Secret Safely
Revoke a leaked credential, issue a replacement, deploy it through a secret manager, and purge the old value from history where your threat model requires it.
Set HTTP Cache Headers for Static Assets and HTML
Give fingerprinted assets a long immutable cache while forcing browsers and CDNs to revalidate HTML, preventing stale deployments without sacrificing repeat-visit performance.
Clean Up Local Commits with Interactive Rebase
Rewrite local commit history using git rebase --interactive to squash, reorder, or edit commits before sharing. Use this when preparing a clean pull request from messy WIP commits.
Speed Up Slow Queries with SQL Indexes
Diagnose slow SQL queries using EXPLAIN and add targeted indexes to reduce row scans from millions to dozens. Covers B-tree indexes, composite ordering, and when indexes hurt performance.
Create a Multi-Stage Dockerfile for Smaller Images
Use multi-stage Docker builds to compile your application in one stage and copy only the runtime artifacts into the final small image. This pattern can reduce image sizes by 10x or more.