Recipes

Step-by-step solutions for real development tasks.

699 published

Page 1 of 7

Gate on Accessibility with axe-core

Run axe-core in CI so a PR that introduces a WCAG violation is blocked before merge, not found in a yearly audit.

~20 min
testing · accessibility · axe

Announce Dynamic Updates with aria-live Regions

Add an aria-live region so screen readers announce search results and toast notifications without the user moving focus.

~15 min
frontend · accessibility · aria

Alert with Multi-Window Burn Rate

Check the error budget burn rate over both 1h and 5m windows so a fast burn pages immediately and a slow burn notifies within an hour.

~25 min
observability · alerting · slo

Detect Anomalies Against a Rolling Baseline

Compute a 7-day rolling median and alert when the current value exceeds 3 sigma so a gradual regression is caught not just spikes.

~25 min
observability · anomaly · baseline

Rotate API Keys with Overlap and Grace Period

Issue the new key, accept both during a grace period, then revoke the old so clients update without downtime.

~20 min
api · api-key · rotation

Test API Schema Diff for Breaking Changes

Compare the OpenAPI spec before and after a PR so a removed field or narrowed type is flagged as a breaking change.

~25 min
testing · api · schema

Version an API with URL Path Segments

Mount v1 and v2 on separate path prefixes so a breaking change in v2 does not affect v1 clients still in production.

~20 min
api · versioning · routing

Keep an Audit History with a Trigger

Create a trigger that writes the old and new values to an audit table on every update so changes are traceable without app code.

~25 min
database · audit · trigger

Restore the Database to a Point in Time

Use point-in-time recovery to restore to 5 minutes before the bad migration so data loss is minimized.

~30 min
database · backup · pitr

Detect Performance Regression with Benchmark CI

Run benchmarks on every PR and compare against the main branch baseline so a 10 percent slowdown is flagged before merge.

~30 min
testing · benchmark · regression

Isolate Resources with the Bulkhead Pattern

Allocate a fixed thread pool per downstream service so a slow service does not exhaust threads needed by healthy ones.

~20 min
api · bulkhead · isolation

Split Bundles at Route Level for Faster Loads

Configure dynamic imports per route so the initial bundle is 40KB not 400KB and each page loads only its own code.

~20 min
performance · bundling · code-split

Design CDN Cache Keys to Avoid Stale Variants

Include the variant in the cache key so a mobile and desktop response do not collide and serve the wrong layout.

~20 min
performance · cdn · caching

Limit Chaos Experiment Blast Radius

Define a steady-state hypothesis and abort conditions so a chaos experiment auto-stops before it takes down the whole fleet.

~40 min
testing · chaos · resilience

Add a Circuit Breaker with Half-Open State

Trip the breaker after 5 failures, allow one probe in half-open, and close on success so cascading failures are contained.

~25 min
api · circuit-breaker · resilience

Distribute Private Content with CloudFront Signed URLs

Generate a signed URL with a short expiry so a user can download a protected asset without the bucket being public.

~25 min
cloud · cloudfront · signed-url

Audit API Calls with CloudTrail Event History

Query CloudTrail for who created or deleted a resource in a time window so an unauthorized change is attributable.

~20 min
cloud · cloudtrail · audit

Query Logs with CloudWatch Logs Insights

Write a Logs Insights query that filters by error and groups by service so the top error source is visible in seconds.

~20 min
cloud · cloudwatch · logs

Balance the Cluster Autoscaler Across Zones

Configure the autoscaler with balance-similar-node-groups so a zone outage does not leave all pods in one zone.

~20 min
kubernetes · autoscaler · zones

Add a Command Palette with Keyboard Shortcut

Register a Cmd+K shortcut that opens a searchable command palette so power users navigate without touching the mouse.

~25 min
frontend · ux · command-palette

Cancel Duplicate Runs on Concurrent Pushes

Add a concurrency group so a second push to the same branch cancels the in-flight run and frees the runner.

~10 min
ci · optimization · concurrency

Skip CI Jobs on Documentation-Only Changes

Add path filters so jobs that compile or test code are skipped when the diff touches only markdown and docs.

~15 min
ci · optimization · paths

Hot Reload ConfigMap Changes Without Restart

Mount the ConfigMap as a projected volume and watch for changes so the app picks up config updates without a rolling restart.

~25 min
kubernetes · configmap · hot-reload

Size the Connection Pool to Avoid Exhaustion

Set the pool max to twice the CPU cores and add a acquire timeout so a spike does not exhaust connections and queue forever.

~20 min
performance · database · pooling

Pin the Database Connection SSL Certificate

Set sslmode to verify-full and pin the CA so a rogue DB proxy with a valid but different certificate is rejected.

~20 min
database · ssl · pinning

Scan Container Images for Known CVEs

Scan the built image against a vulnerability database so a critical CVE in a base layer blocks the deploy.

~20 min
security · containers · cve

Add Consumer-Driven Contract Tests with Pact

Generate a pact from the consumer's test suite and verify it in the provider pipeline so breaking API changes are caught before deploy.

~35 min
testing · contract · pact

Propagate a Correlation ID Through All Logs

Generate a correlation ID at the edge and attach it to every log line so a single user request is traceable end to end.

~15 min
observability · logging · correlation

Cache CORS Preflight Responses Server-Side

Set Access-Control-Max-Age so OPTIONS preflight responses are cached and do not add a round-trip to every cross-origin request.

~15 min
security · cors · caching

Gate on Coverage Diff Not Absolute Number

Compare coverage against the base branch so a PR that drops coverage by 2 percent fails even if the total is still above 80 percent.

~20 min
testing · coverage · gate

Inline Critical CSS and Async Load the Rest

Extract above-the-fold CSS into a style tag and load the rest asynchronously so the first paint does not wait for the full stylesheet.

~20 min
performance · css · critical

Prevent Overlapping CronJobs with Concurrency Rule

Set concurrencyPolicy to Forbid so a slow cron job does not start a second instance while the first is still running.

~15 min
kubernetes · cronjob · concurrency

Trigger a Cross-Repository Pipeline on Tag

Use a repository dispatch event so tagging a shared library triggers downstream consumers to rebuild and test.

~20 min
ci · monorepo · triggers

Report CSP Violations to a Collector Endpoint

Add a report-uri to the Content-Security-Policy header so browser violations are collected and triaged as security events.

~20 min
security · csp · headers

Prevent CSRF with Double-Submit Cookie

Issue a CSRF token as a cookie and require it as a header so a cross-site form post without the header is rejected.

~20 min
security · csrf · cookies

Expose a Custom Metric for a Business KPI

Instrument the checkout flow to emit a conversion counter so the business KPI is on the same dashboard as latency.

~20 min
observability · metrics · business

Follow System Dark Mode Preference with CSS

Use prefers-color-scheme media query and a manual toggle that persists to localStorage so the theme follows the OS unless overridden.

~15 min
frontend · dark-mode · css

Version Dashboards as Code with Grafana

Define dashboards in JSON committed to the repo so changes are reviewed and reproducible, not lost in a UI edit.

~20 min
observability · dashboards · grafana

Migrate Data in Batches with a Cursor

Process records in batches of 1000 using a cursor so a 10 million row migration does not blow up memory or lock the table.

~30 min
database · migration · batch

Enforce a Data Retention Policy with TTL Jobs

Schedule a job that deletes records past their retention window so the database does not hold data longer than the policy allows.

~20 min
security · retention · compliance

Debounce Search Input to Reduce API Calls

Wrap the search handler in a 300ms debounce so typing five characters fires one request not five.

~15 min
performance · frontend · debounce

Defer Non-Critical JS to After Interactive

Add defer to analytics and widget scripts so they do not block parsing and the page reaches interactive 800ms sooner.

~10 min
performance · frontend · defer

Audit Dependency Licenses Against an Allowlist

Run a license scanner on every dependency so a GPL-licensed transitive package is caught before it ships in a proprietary product.

~20 min
security · licensing · dependencies

Collect Deploy Timing Metrics per Stage

Instrument the deploy pipeline to emit per-stage duration metrics so regressions in deploy time are visible on a dashboard.

~20 min
ci · metrics · deployment

Automate Deployment Rollback on Failed Health Check

Wire a rollback step into the deploy pipeline that triggers when the post-deploy health check fails beyond a retry threshold.

~30 min
ci · deployment · kubernetes

Propagate Distributed Trace Context Across Hops

Inject the traceparent header on every outbound call so a request is traceable across service boundaries.

~20 min
observability · tracing · otel

Switch to a Distroless Base Image for Security

Replace debian with gcr.io/distroless so the image has no shell, no package manager, and a 90 percent smaller attack surface.

~20 min
kubernetes · security · distroless

Spin Up a Dynamic Review Environment per PR

Create an ephemeral namespace per pull request so reviewers can test the change before merge, then tear it down on close.

~35 min
ci · kubernetes · review-env

Build a Dynamic Matrix Across Node Versions

Generate a CI matrix from the lockfile so every supported runtime is tested without hardcoding version numbers in the workflow.

~25 min
ci · testing · matrix

Auto-Scale DynamoDB Read and Write Capacity

Enable autoscaling on the table with a target utilization of 70 percent so a traffic spike does not throttle reads or writes.

~20 min
cloud · dynamodb · autoscaling

Handle EC2 Spot Interruption Notices Gracefully

Poll the instance metadata for an interruption notice and drain gracefully so a spot instance is not killed mid-request.

~25 min
cloud · ec2 · spot

Size ECS Fargate Tasks for Cost and Headroom

Set the task CPU and memory to the p95 usage plus 20 percent headroom so tasks are not throttled or over-provisioned.

~20 min
cloud · ecs · fargate

Convert an Enum to a Lookup Table

Replace the enum with a foreign key to a lookup table so new values are added with INSERT not a migration.

~25 min
database · refactor · lookup

Protect Deployment Environments with Required Reviewers

Configure environment protection rules so production deploys require a human reviewer and a deployment branch.

~20 min
ci · security · environments

Recover from Render Errors with an Error Boundary

Add an error boundary that shows a fallback and a retry button so a null pointer in one widget does not blank the whole page.

~20 min
frontend · react · error-boundary

Group Errors by Fingerprint Not Message

Hash the stack trace frames into a fingerprint so the same error with different variable values groups together.

~15 min
observability · errors · grouping

Apply Expand-Contract for Backward-Compatible Schema

Add the new column, backfill it, switch reads, then drop the old column so no deploy sees a missing or extra column.

~25 min
database · migration · expand-contract

Choose Fakes Over Mocks for Stable Tests

Replace brittle mock call-count assertions with a fake implementation that captures state so tests survive refactors of the call pattern.

~20 min
testing · mocking · fakes

Quarantine Flaky Tests with Auto-Retry

Detect tests that fail intermittently, quarantine them in a separate suite, and open an issue so they are fixed not ignored.

~20 min
testing · flaky · quarantine

Use font-display Swap to Avoid FOIT

Set font-display: swap so text renders immediately in a fallback and swaps to the custom font when it loads, eliminating invisible text.

~10 min
performance · fonts · fouf

Validate Forms Progressively from Blur to Submit

Validate on blur, then on change after first error, then on submit so the user gets feedback without aggressive red fields on first focus.

~20 min
frontend · forms · validation

Compare Output Against a Golden Master File

Record a golden master output from a stable build and diff future runs against it so unintended output changes fail the test.

~25 min
testing · golden · regression

Limit GraphQL Query Depth to Prevent Nested Abuse

Set a max depth of 7 so a malicious query like { user { posts { user { posts ... } } } } is rejected before execution.

~20 min
api · graphql · security

Fix GraphQL N+1 with DataLoader

Batch per-request data loads with DataLoader so a list of 50 items fetches their authors in one query not 50.

~25 min
api · graphql · dataloader

Propagate gRPC Deadlines Across Service Hops

Set a deadline on the client and propagate it so a downstream call does not hang past the upstream caller's timeout.

~20 min
api · grpc · deadline

Automate a Response to GuardDuty Findings

Send GuardDuty findings to an EventBridge rule that isolates the instance so a compromised host is quarantined within minutes.

~30 min
cloud · guardduty · automation

Negotiate Brotli Over Gzip for Better Ratio

Check Accept-Encoding and serve Brotli when available so text assets are 20 percent smaller than gzip.

~15 min
performance · compression · brotli

Scale on a Custom Metric with HPA

Configure a Horizontal Pod Autoscaler on a custom queue depth metric so the deployment scales with backlog not just CPU.

~25 min
kubernetes · hpa · autoscaling

Submit HSTS to the Browser Preload List

Set Strict-Transport-Security with preload and submit the domain so future browsers refuse HTTP connections without a first-visit redirect.

~15 min
security · hsts · tls

Use HTTP/2 Server Push for Critical Resources

Push the CSS and font before the browser parses the HTML so the waterfall collapses and LCP drops by 400ms.

~20 min
performance · http2 · server-push

Lazy Load Locale Bundles on Language Switch

Dynamically import the locale bundle on switch so the initial bundle is not bloated with translations for every language.

~20 min
frontend · i18n · lazy-load

Scan IaC for Misconfigurations with tfsec

Run a static analyzer on Terraform so an S3 bucket without encryption or a security group open to 0.0.0.0/0 is caught before apply.

~20 min
security · iac · terraform

Write IAM Policies with Least Privilege Actions

Scope the IAM policy to exact actions and resources so a leaked key can only read one bucket not the whole account.

~25 min
cloud · iam · security

Make Retries Safe with an Idempotency Key

Accept an idempotency key header so a retried payment request returns the original result instead of charging twice.

~20 min
api · idempotency · retry

Lazy Load Below-the-Fold Images with Native API

Add loading=lazy to offscreen images so the browser defers their fetch until scroll, cutting initial page weight by 60 percent.

~10 min
performance · images · lazy-load

Rotate Image Pull Secrets Periodically

Create a new pull secret, patch the service account, and remove the old one so registry credentials rotate without a pod restart storm.

~25 min
kubernetes · secrets · rotation

Reconstruct an Incident Timeline from Audit Logs

Query the audit log for all actions in the incident window and produce a timeline so the postmortem has facts not memory.

~25 min
observability · incident · timeline

Add a Covering Index for Hot Query Columns

Include all columns the query reads in the index so the database answers from the index without touching the table.

~20 min
performance · database · indexing

Create Indexes Concurrently Without Locking

Use CREATE INDEX CONCURRENTLY so the table stays available for reads and writes during the index build.

~20 min
database · index · concurrent

Infinite Scroll with Intersection Observer

Observe a sentinel element at the list bottom and load more when it enters the viewport so there are no page buttons and scrolling is seamless.

~20 min
frontend · scroll · intersection

Terminate TLS at the Ingress Controller

Configure the ingress with a TLS secret so the controller terminates TLS and backend pods receive plain HTTP on localhost.

~15 min
kubernetes · ingress · tls

Run a Migration in an Init Container

Put the database migration in an init container so the app container starts only after the schema is at the expected version.

~20 min
kubernetes · init · migration

Validate All Inputs with a Zod Schema

Parse every request body and query param through a Zod schema so malformed input is rejected with a 400 before it reaches the handler.

~20 min
security · validation · zod

Run Integration Tests Against docker-compose

Spin up dependencies in compose, run integration tests against them, and tear down so tests run identically locally and in CI.

~30 min
testing · integration · docker

Set Job Backoff Limit for Retry Exhaustion

Configure backoffLimit and activeDeadlineSeconds so a failing job retries 3 times then stops instead of looping forever.

~15 min
kubernetes · job · retry

Index JSONB Columns with GIN for Fast Lookups

Create a GIN index on the JSONB path so queries like data->>'type' = 'x' use the index instead of a sequential scan.

~20 min
database · jsonb · gin

Issue Short-Lived JWT Tokens with Refresh

Set JWT expiry to 15 minutes and use a refresh token rotation scheme so a stolen access token is useless within a quarter hour.

~25 min
security · jwt · tokens

Enable Automatic KMS Key Rotation

Turn on automatic rotation for the KMS key so the key material changes yearly without re-encrypting existing data.

~15 min
cloud · kms · rotation

Reduce Lambda Cold Starts with Provisioned Concurrency

Set provisioned concurrency on the alias so the first N invocations have no init delay and p99 latency drops.

~20 min
cloud · lambda · cold-start

Ramp Load with k6 Stages Profile

Define a k6 stage profile that ramps from 10 to 500 virtual users over 5 minutes so the breaking point is visible in the metrics.

~35 min
testing · load · k6

Set Log Aggregation Retention by Index

Configure hot-warm-cold retention so recent logs are fast to query, old logs are cheap, and expired logs are deleted automatically.

~15 min
observability · logging · retention

Redact PII from Logs Before Shipping

Pipe logs through a redaction filter that masks email and phone fields so PII never reaches the aggregation system.

~20 min
observability · logging · pii

Sample High-Volume Logs to Control Cost

Apply a 10 percent sampling rate to debug logs so the volume is manageable but errors are always logged at 100 percent.

~15 min
observability · logging · sampling

Refresh a Materialized View Concurrently

Refresh the materialized view concurrently so readers never block and the dashboard stays available during the refresh.

~20 min
database · materialized-view · refresh

Memoize Expensive Pure Functions with Cache Key

Cache the result of a pure sort or filter by its input hash so repeated calls with the same data return instantly.

~15 min
performance · memoization · caching

Batch Pull Requests Through a Merge Queue

Enable a GitHub merge queue so multiple pull requests are batched and validated together before landing on main.

~15 min
ci · github · workflow

Configure Histogram Buckets for Latency SLOs

Set histogram bucket boundaries around the SLO threshold so p99 is accurate and not rounded into the wrong bucket.

~20 min
observability · metrics · histogram

Run a Zero-Downtime Migration in Three Phases

Split the migration into expand, migrate, and contract phases so the old and new code run side by side during the transition.

~30 min
database · migration · zero-downtime

Trap Focus Inside a Modal Dialog

Move focus to the modal on open, cycle within, and restore to the trigger on close so keyboard users cannot tab behind the overlay.

~20 min
frontend · accessibility · focus-trap

Build Multi-Arch Images with buildx

Use docker buildx with linux/amd64 and linux/arm64 platforms so the image runs on both Intel nodes and Graviton instances.

~25 min
kubernetes · multi-arch · buildx