Recipes

Step-by-step solutions for real development tasks.

699 published

Page 2 of 7

Gate on Mutation Testing Score

Run a mutation testing tool on new code so a high line coverage that hides untested logic is caught before merge.

~40 min
testing · mutation · quality

Enforce Resource Quotas per Namespace

Set CPU and memory quotas on each namespace so a team cannot accidentally consume all cluster resources.

~15 min
kubernetes · quota · governance

Default-Deny Network Traffic with NetworkPolicy

Apply a default-deny ingress policy so pods are isolated by default and only explicit allow rules open connections.

~20 min
kubernetes · networkpolicy · security

Link Alerts to Runbooks for On-Call Guidance

Attach a runbook URL to every alert so the on-call engineer sees the exact steps to diagnose and mitigate, not just a metric name.

~15 min
observability · alerting · runbook

Use Optimistic Locking with a Version Column

Add a version column and check it on update so concurrent edits are detected and the last writer gets a 409 not a silent overwrite.

~20 min
database · optimistic-lock · concurrency

Apply Optimistic UI Updates with Rollback

Update the UI immediately, send the request, and roll back on error so the interaction feels instant and stays correct.

~20 min
frontend · optimistic · ui

Route Logs Through an OTel Collector Pipeline

Send logs to the OpenTelemetry Collector which batches, transforms, and exports to multiple backends without app code changes.

~25 min
observability · otel · collector

Publish Events via the Outbox Pattern

Write the event to an outbox table in the same transaction as the business write so the event is not lost if the broker is down.

~25 min
api · outbox · events

Switch from Offset to Cursor Pagination

Use a cursor based on the last item's sort key so page 2 does not skip or duplicate items when new data arrives between requests.

~25 min
api · pagination · cursor

Shard Tests Across CI Runners for Speed

Split the test suite into N shards by historical duration so all runners finish at the same time instead of one straggler.

~25 min
testing · parallel · sharding

Partition a Large Table by Date for Pruning

Partition by month so a query on the last 30 days scans one partition not the entire years of history.

~30 min
database · partition · pruning

Hash Passwords with Argon2id Tuned Parameters

Use Argon2id with memory and iteration parameters tuned to the hardware so offline cracking takes years not hours.

~20 min
security · passwords · argon2

Guarantee Drain Safety with a Pod Disruption Budget

Set a Pod Disruption Budget so a voluntary drain like a node upgrade cannot evict the last replica and cause downtime.

~15 min
kubernetes · pdb · drain

Set Pipeline Artifact Retention by Type

Configure artifact retention rules so build outputs expire after 14 days but signed releases are kept for a year.

~15 min
ci · artifacts · governance

Use Restore Keys for Fallback Cache Matching

Configure cache restore keys so a partial key match still reuses a previous cache when the exact key misses.

~15 min
ci · caching · fallback

Notify On-Call on Pipeline Failure with Context

Send a structured notification with the failing job, logs link, and last commit when a critical pipeline fails.

~15 min
ci · alerts · notifications

Route Jobs to Runners by Label

Assign runner labels so GPU jobs go to GPU runners and lint jobs go to the cheapest available runner.

~10 min
ci · runners · routing

Scan for Secrets Leaked in Pipeline Output

Add a secret scanning step that checks build logs and artifacts for leaked tokens before publishing.

~20 min
ci · security · secrets

Skip Heavy Jobs When Only Docs Changed

Use dorny paths-filter to detect doc-only changes and skip compilation and test jobs to save runner time.

~15 min
ci · optimization · paths

Set a Pipeline Timeout Budget per Stage

Configure per-job timeouts so a hung step fails fast instead of burning runner minutes for the default six hours.

~10 min
ci · optimization · timeouts

Enforce Pod Security Standards at Admission

Apply a restricted Pod Security Standard at the namespace level so privileged containers are rejected by the API server.

~20 min
kubernetes · security · psa

Spread Pods Across Zones with Topology Constraints

Add a topologySpreadConstraint so a zone failure takes down at most one replica not the whole deployment.

~20 min
kubernetes · topology · spread

Use a Blameless Postmortem Template for Incidents

Fill a structured template with timeline, root cause, impact, and action items so the postmortem focuses on systems not people.

~20 min
observability · incident · postmortem

Precompute Aggregates in a Materialized View

Store the daily sum in a materialized view refreshed nightly so the dashboard query reads one row instead of scanning a million.

~25 min
performance · database · precompute

Prefetch Route Data on Link Hover

Add a mouseenter listener that prefetches the next route's data so navigation feels instant on click.

~15 min
performance · frontend · prefetch

Automate Privacy Impact Assessment Checks

Run a data flow analysis so a new field that contains PII is flagged for review before it is added to the schema.

~25 min
security · privacy · compliance

Add Property-Based Testing with fast-check

Replace hand-written examples with property-based generators that explore the input space and shrink failures to a minimal counterexample.

~30 min
testing · property-based · fast-check

Detect N+1 Queries with an ORM Logger

Enable query logging in tests so a list endpoint that fires one query per item is visible in the log and fixed with a join.

~25 min
performance · database · n-plus-one

Analyze a Slow Query Plan with EXPLAIN

Run EXPLAIN ANALYZE on the slow query so the plan shows whether it is a sequential scan, a bad join, or missing index.

~20 min
database · query-plan · explain

Rate Limit with a Redis Token Bucket

Implement a token bucket in Redis so distributed rate limiting works across multiple instances with atomic decrements.

~25 min
security · rate-limit · redis

Pool Database Connections with RDS Proxy

Put an RDS Proxy between Lambda and the database so connection opens are pooled and a Lambda spike does not exhaust DB connections.

~25 min
cloud · rds · proxy

Guarantee Read-After-Write Consistency

Route reads from the same session to the primary or use a causal token so a user sees their own write immediately.

~25 min
database · consistency · read-write

Route Reads to a Replica and Writes to Primary

Split the connection so read-heavy endpoints hit the replica and the primary is reserved for writes, cutting read latency by half.

~20 min
performance · database · replica

Respect prefers-reduced-motion for Animations

Disable or shorten animations when the user sets reduce-motion so vestibular sensitivity is respected not ignored.

~10 min
frontend · accessibility · motion

Monitor Replication Lag and Alert on Threshold

Query the replication lag and alert when it exceeds 5 seconds so a stale read replica does not serve outdated data.

~20 min
database · replication · lag

Require Status Checks Before Merge with Strict Mode

Enable branch protection with strict status checks so a pull request cannot merge if any required check is pending or failing.

~15 min
ci · github · branch-protection

Rightsize Resource Requests from Metrics

Read the 95th percentile CPU and memory from metrics and set requests to p95 so pods are not throttled or over-provisioned.

~25 min
kubernetes · resources · rightsize

Serve Responsive Images with srcset Sizes

Provide srcset with 480, 800, and 1200 widths so the browser downloads the smallest image that fills the viewport.

~15 min
frontend · images · responsive

Retry with Exponential Backoff and Full Jitter

Add full jitter to the backoff so retries spread across time and do not synchronize into a retry storm on recovery.

~15 min
api · retry · backoff

Compose Reusable Workflows to Share CI Logic

Extract repeated CI steps into a reusable workflow so consumer repos call it with one line instead of duplicating YAML.

~20 min
ci · reusable · dry-run

Tune Rolling Update Max Surge for Capacity

Set maxSurge to 1 and maxUnavailable to 0 so updates add a new pod before removing an old one and capacity never drops.

~15 min
kubernetes · rolling-update · deploy

Show Route Transitions with Suspense Boundaries

Wrap each route in a Suspense boundary with a fallback spinner so navigation shows a skeleton instead of a blank flash.

~15 min
frontend · react · suspense

Fail Over DNS with Route53 Health Checks

Configure a health check on the primary and a failover record so traffic routes to the standby within 30 seconds of failure.

~20 min
cloud · route53 · failover

Tier S3 Objects with Lifecycle Rules

Transition objects to Infrequent Access after 30 days and Glacier after 90 so storage costs drop without deleting data.

~15 min
cloud · s3 · lifecycle

Generate an SBOM in the Build Pipeline

Produce a Software Bill of Materials on every build so downstream consumers can audit transitive dependencies.

~15 min
ci · security · sbom

Detect Schema Drift Between Environments

Dump the schema from staging and production and diff them so a missing index or column is caught before deploy.

~20 min
database · schema · drift

Sync Secrets from External Secrets Operator

Reference a secret in the external secrets store so Kubernetes pulls and rotates it without the value ever touching Git.

~25 min
kubernetes · secrets · eso

Automate Secret Rotation with a Cron Job

Schedule a rotation job that generates a new secret, updates consumers, and verifies the old one is revoked within one hour.

~30 min
security · secrets · rotation

Set Secure Cookie Attributes Consistently

Add Secure, HttpOnly, SameSite=Strict to every auth cookie so it is not sent over HTTP, not readable by JS, and not included in cross-site requests.

~15 min
security · cookies · attributes

Enable mTLS Across the Service Mesh

Turn on strict mTLS in the mesh so all inter-service traffic is encrypted and a pod on a compromised node cannot sniff calls.

~25 min
kubernetes · mtls · service-mesh

Cache API Responses with a Service Worker Strategy

Use stale-while-revalidate for API calls so the page loads instantly from cache and updates in the background.

~25 min
performance · service-worker · caching

Inject a Sidecar with a Mutating Webhook

Configure a mutating admission webhook so every pod in the namespace gets a proxy sidecar without developers editing specs.

~30 min
kubernetes · sidecar · webhook

Show Skeleton Placeholders During Data Fetch

Render a skeleton that matches the layout so the user sees structure immediately and there is no layout shift when data arrives.

~15 min
frontend · loading · skeleton

Define an SLO Error Budget and Burn Policy

Set a 99.9 percent SLO with a 30-day window so the error budget is explicit and a burn rate triggers a freeze on deploys.

~25 min
observability · slo · error-budget

Review Snapshot Diffs Before Updating

Configure snapshot tests to fail on mismatch and require a reviewed update flag so blind --update-snapshot does not hide regressions.

~20 min
testing · snapshots · review

Cascade Soft Deletes to Child Records

Set deleted_at on the parent and all children in one transaction so a soft delete is consistent without orphaned rows.

~20 min
database · soft-delete · cascade

Add Span Attributes for Log Correlation

Attach the user ID and request ID as span attributes so a trace can be correlated to logs and the user's journey is visible.

~15 min
observability · tracing · correlation

Detect SQL Injection with Parameterized Queries

Replace string concatenation in SQL with parameterized queries so a user input of ' OR 1=1 -- cannot escape the query structure.

~20 min
security · sqli · database

Redrive SQS Dead-Letter Queue Messages

Move messages from the DLQ back to the source queue after fixing the consumer so failed messages are retried not abandoned.

~20 min
cloud · sqs · dlq

Block SSRF with a Fetch Allowlist

Validate every outbound URL against a host allowlist before fetching so a user-supplied URL cannot reach internal metadata endpoints.

~20 min
security · ssrf · allowlist

Model Complex UI State with XState

Replace nested boolean flags with a state machine so impossible states like loading AND error are unrepresentable.

~30 min
frontend · xstate · state-machine

Emit Structured JSON Logs for Parsing

Replace console.log with a JSON logger so logs are machine-parseable and queryable in the aggregation system.

~15 min
observability · logging · json

Scan for Subdomain Takeover Vulnerabilities

Check dangling DNS records that point to unprovisioned cloud services so an attacker cannot claim the CNAME and host content on your subdomain.

~25 min
security · dns · takeover

Monitor with Synthetic Probes from Multiple Regions

Run a synthetic check every minute from three regions so a regional outage is detected before users report it.

~25 min
observability · synthetics · monitoring

Enable Terraform State Locking with S3 and DynamoDB

Configure a DynamoDB lock table so concurrent terraform runs do not corrupt the state file.

~20 min
cloud · terraform · state

Use Builder Pattern for Readable Test Data

Create a builder fluent API for test fixtures so complex objects are constructed with only the fields each test cares about.

~20 min
testing · fixtures · builder

Isolate Test Database per Worker with Transactions

Wrap each test in a transaction that rolls back so parallel workers never see each other's data and tests are order-independent.

~25 min
testing · database · isolation

Verify Test Environment Parity with Production

Compare the test and production dependency versions and config so a bug that only reproduces on a version skew is caught early.

~25 min
testing · parity · environments

Retry Flaky Network Tests with Backoff

Add exponential backoff retry to tests that hit external APIs so transient 503s do not fail the pipeline.

~15 min
testing · retry · network

Distribute a Timeout Budget Across Hops

Subtract each hop's elapsed time from the total budget so the last hop gets the remainder not a fresh full timeout.

~20 min
api · timeout · budget

Pin TLS Certificates for Mobile API Clients

Embed the expected certificate hash so a compromised CA or MITM proxy is rejected even if the chain is technically valid.

~25 min
security · tls · pinning

Stack Toast Notifications with a Queue Limit

Cap the visible toasts at 3 and queue the rest so a burst of 10 notifications does not cover the screen.

~15 min
frontend · ux · toasts

Sample Traces at the Tail for Completeness

Buffer all spans and sample at the end so traces with errors are always kept and healthy traces are sampled by rate.

~25 min
observability · tracing · sampling

Retry Transactions on Deadlock with Jitter

Detect a deadlock error, wait with jitter, and retry the transaction so concurrent operations do not permanently fail.

~20 min
database · deadlock · retry

Tree Shake Unused Exports with Side Effects Flag

Mark the package with sideEffects false so the bundler drops unused exports and the bundle shrinks by 30 percent.

~15 min
performance · bundling · tree-shaking

Migrate from Serial to UUID Primary Keys

Add a UUID column, backfill with generated values, make it the primary key, and drop the serial so offline ID guessing is impossible.

~35 min
database · migration · uuid

Reclaim Bloat with a Targeted Vacuum

Run VACUUM with a threshold on the dead tuple ratio so only bloated tables are vacuumed aggressively, not the whole database.

~20 min
database · vacuum · bloat

Virtual Scroll Large Lists for Constant DOM

Render only the visible window of a 10000-row list so the DOM stays under 100 nodes and scrolling is smooth.

~20 min
performance · frontend · virtualization

Set a Visual Regression Threshold per Component

Configure per-component pixel diff thresholds so minor anti-aliasing differences pass but real layout shifts fail the build.

~25 min
testing · visual · playwright

Access Services Privately with a VPC Endpoint

Create a VPC endpoint so traffic to S3 or DynamoDB stays on the AWS network and never traverses the public internet.

~20 min
cloud · vpc · endpoint

Offload Heavy Compute to a Web Worker

Move a 200ms image processing loop into a worker so the main thread stays responsive and the UI does not jank.

~20 min
performance · web-worker · offload

Verify Webhook Signatures with HMAC

Recompute the HMAC over the raw body and constant-time compare so a forged webhook from a spoofed source is rejected.

~20 min
api · webhook · security

Reconnect WebSockets with Exponential Backoff

Retry the connection with exponential backoff and jitter so a server restart does not cause a thundering herd of reconnections.

~20 min
api · websocket · reconnect

Prevent XSS with Context-Aware Output Encoding

Encode dynamic output for the correct context so a value in an HTML attribute is escaped differently than one in a script block.

~20 min
security · xss · encoding

Enforce Conventional Commit Lint in CI

Add commitlint to a GitHub Actions workflow so non-conforming commit messages block the pull request before merge.

~20 min
ci · linting · git

Configure Redis Sentinel Quorum for Failover

Deploy three Sentinel monitors across separate nodes, set a quorum of two, and verify automatic master promotion when the primary loses contact with the majority.

~35 min
redis · sentinel · failover

Audit npm Script Permissions for Supply-Chain Risk

List every package that runs lifecycle scripts on install, block preinstall and postinstall where untrusted, and record the allowlist in a checked-in policy file.

~25 min
npm · security · supply-chain

Bootstrap a pnpm Monorepo with Workspace Protocol

Create a pnpm workspace with shared tooling, declare cross-package dependencies with the workspace protocol, and verify that changes in one package rebuild dependents.

~30 min
pnpm · monorepo · tooling

Cache a GraphQL Resolver with DataLoader

Wrap a N+1 resolver in a DataLoader, batch the keys within one request, and cache the per-request result so the same key is fetched once.

~30 min
graphql · dataloader · performance

Capture HTTP Replay Fixtures for Deterministic Tests

Record real HTTP responses into version-controlled fixtures, redact secrets, and replay them in tests so the suite never hits the network and stays deterministic.

~40 min
testing · http · fixtures

Compress a Docker Image with a Multi-Stage Build

Split a Dockerfile into a build stage and a runtime stage, copy only the compiled artifacts, and measure the size reduction before pushing the smaller image.

~30 min
docker · multistage · optimization

Detect Secret Leaks in CI with a Pre-Commit Scan

Run a secret scanner on every push, fail the build on a high-confidence finding, and route the alert to the on-call so the leaked credential can be rotated before it is used.

~20 min
security · secrets · ci

Enforce Branch Protection Rules via GitHub API

Require pull request reviews and status checks on the main branch, enforce linear history, and audit the rules with a single API call that fails CI on drift.

~20 min
github · branch-protection · governance

Export Prometheus Metrics with a Default Registry

Register a counter and a histogram with the default registry, instrument the request path, and expose /metrics in the text format Prometheus scrapes.

~25 min
prometheus · metrics · observability

Generate OpenAPI Spec from Existing Routes

Walk an Express or Fastify route table, infer parameter and response types from handlers and validation schemas, and emit an OpenAPI 3.1 document for clients and docs.

~35 min
openapi · documentation · node

Hash PII with a Bloom Filter for Set Membership

Hash personally identifiable information into a Bloom filter so you can test membership without storing the raw values, and size the filter for your false-positive budget.

~25 min
privacy · bloom-filter · pii

Migrate a Postgres Column with Zero Downtime

Add a new column, backfill it in batches, swap reads and writes in code, then drop the old column in a follow-up deploy without locking the table.

~45 min
postgres · migration · zero-downtime

Pin Transitive Dependencies with Overrides

Identify a vulnerable transitive package, add a pnpm override or npm resolution that forces a safe version, and verify the lockfile no longer contains the bad release.

~20 min
dependencies · security · overrides

Prune Stale Git Branches with a Date Cutoff

List local and remote branches older than a cutoff, confirm none are linked to open PRs, and delete them in one scripted pass with a dry-run first.

~15 min
git · maintenance · branches

Reconcile State Drift with terraform import

Detect resources that exist in the cloud but not in state, import them with terraform import, and run a plan that shows zero diff before adopting the resources.

~25 min
terraform · drift · import