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.

~30 min
postgresql · migrations · locking

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.

~35 min
database · migrations · ci

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.

~40 min
testing · quality · ci

Drain a Node Without Dropping Requests

Cordon first, drain with explicit flags, respect disruption budgets, and verify workloads moved before terminating the node.

~25 min
kubernetes · maintenance · availability

Escalate Unacknowledged Alerts Automatically

Configure Alertmanager grouping and repeat intervals plus a two-tier escalation path, so a missed page reaches someone awake.

~30 min
alerting · oncall · reliability

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.

~15 min
on-call · operations · incident-response

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.

~40 min
webhooks · reliability · queues

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.

~30 min
testing · pagination · api

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.

~30 min
postgresql · indexes · performance

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.

~25 min
postgresql · deadlocks · transactions

Scan Databases for Unlabeled PII

Sample column values, run Presidio analyzers, and produce a report of likely personal data that lacks classification tags.

~40 min
privacy · pii · data-governance

Protect Availability with a PodDisruptionBudget

Set minAvailable for critical deployments and verify that node drains respect the budget instead of evicting every replica.

~25 min
kubernetes · availability · operations

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.

~30 min
deployment · smoke-test · rollback

Add a Blameless Postmortem Template

Ship a postmortem template with timeline, contributing factors, and owned action items, and enforce required sections in CI.

~30 min
incident-response · documentation · process

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.

~40 min
observability · prometheus · nodejs

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.

~30 min
testing · property-based · typescript

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.

~30 min
testing · performance · sql

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.

~40 min
postgresql · testing · performance

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.

~25 min
aws · queues · alerting

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.

~30 min
api · rate-limiting · http

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.

~30 min
postgresql · replication · reliability

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.

~35 min
dependencies · ci · supply-chain

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.

~20 min
nodejs · express · http

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.

~35 min
queues · redis · latency

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.

~20 min
nodejs · performance · http

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.

~45 min
backups · disaster-recovery · postgresql

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.

~30 min
release · rollback · drill

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.

~25 min
kubernetes · deployment · pipeline

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.

~20 min
runbooks · ci · documentation

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.

~35 min
kafka · schema-registry · ci

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.

~40 min
secrets · aws · rotation

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.

~20 min
security · secrets · git

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.

~25 min
ownership · service-catalog · operations

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.

~40 min
security · cookies · sessions

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.

~30 min
slo · reliability · prometheus

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.

~30 min
postgresql · indexes · data-modeling

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.

~25 min
caching · frontend · deployment

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.

~35 min
postgresql · partitioning · performance

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.

~40 min
testing · multi-tenancy · security

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.

~30 min
terraform · drift · monitoring

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.

~25 min
terraform · state · reliability

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.

~35 min
testing · postgresql · isolation

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.

~35 min
testing · docker · postgresql

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.

~35 min
testing · resilience · timeouts

Monitor TLS Certificate Expiry

Probe TLS endpoints with blackbox_exporter and alert when a certificate expires within 21 days or the chain fails validation.

~30 min
tls · monitoring · prometheus

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.

~35 min
testing · opentelemetry · observability

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.

~30 min
postgresql · transactions · resilience

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.

~30 min
testing · webhooks · security

Roll Out Config Changes Without Restarting Everything

Version ConfigMaps, roll pods gradually with maxUnavailable 0, and keep serving when a configuration key is missing.

~30 min
kubernetes · config · deployment

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.

~50 min
postgresql · migrations · zero-downtime

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.

~30 min
api · lifecycle · operations

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.

~35 min
database · audit · security

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.

~30 min
caching · performance · operations

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.

~30 min
resilience · nodejs · reliability

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.

~25 min
database · capacity · reliability

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.

~25 min
messaging · reliability · operations

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.

~25 min
security · supply-chain · ci-cd

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.

~35 min
reliability · observability · alerting

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.

~35 min
events · data-integration · contracts

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.

~30 min
distributed-systems · locking · data-consistency

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.

~30 min
resilience · api · user-experience

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.

~25 min
nodejs · operations · deployment

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.

~15 min
security · http · tls

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.

~30 min
messaging · idempotency · reliability

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.

~30 min
webhooks · idempotency · security

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.

~30 min
kubernetes · capacity · reliability

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.

~30 min
resilience · testing · operations

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.

~25 min
resilience · nodejs · capacity

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.

~35 min
api · testing · openapi

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.

~40 min
observability · tracing · nodejs

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.

~25 min
database · concurrency · postgresql

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.

~40 min
messaging · data-consistency · reliability

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.

~25 min
performance · ci-cd · frontend

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.

~25 min
database · postgresql · observability

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.

~25 min
security · rate-limiting · nodejs

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.

~25 min
caching · performance · concurrency

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.

~20 min
nodejs · http · reliability

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.

~30 min
supply-chain · ci-cd · security

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.

~40 min
observability · reliability · metrics

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.

~20 min
observability · logging · nodejs

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.

~25 min
testing · maintainability · typescript

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.

~25 min
redis · caching · operations

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.

~25 min
security · ci-cd · supply-chain

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.

~45 min
database · backup · operations

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.

~20 min
operations · http · kubernetes

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.

~30 min
api-design · reliability · http

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.

~20 min
git · quality · automation

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.

~20 min
observability · logging · http

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.

~30 min
security · http · xss

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.

~20 min
security · http · api-design

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.

~10 min
git · recovery · version-control

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.

~10 min
git · version-control · recovery

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.

~30 min
api-design · databases · pagination

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.

~20 min
git · collaboration · version-control

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.

~30 min
security · secrets · git

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.

~15 min
performance · http · caching

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.

~10 min
git · workflow · history · version-control

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.

~20 min
sql · postgres · performance · indexing

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.

~15 min
docker · devops · deployment · typescript · node