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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Trigger a Cross-Repository Pipeline on Tag
Use a repository dispatch event so tagging a shared library triggers downstream consumers to rebuild and test.
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.
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.
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.
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.
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.
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.
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.
Debounce Search Input to Reduce API Calls
Wrap the search handler in a 300ms debounce so typing five characters fires one request not five.
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.
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.
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.
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.
Propagate Distributed Trace Context Across Hops
Inject the traceparent header on every outbound call so a request is traceable across service boundaries.
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.
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.
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.
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.
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.
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.
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.
Protect Deployment Environments with Required Reviewers
Configure environment protection rules so production deploys require a human reviewer and a deployment branch.
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.
Group Errors by Fingerprint Not Message
Hash the stack trace frames into a fingerprint so the same error with different variable values groups together.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Negotiate Brotli Over Gzip for Better Ratio
Check Accept-Encoding and serve Brotli when available so text assets are 20 percent smaller than gzip.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Create Indexes Concurrently Without Locking
Use CREATE INDEX CONCURRENTLY so the table stays available for reads and writes during the index build.
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.
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.
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.
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.
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.
Set Job Backoff Limit for Retry Exhaustion
Configure backoffLimit and activeDeadlineSeconds so a failing job retries 3 times then stops instead of looping forever.
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.
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.
Enable Automatic KMS Key Rotation
Turn on automatic rotation for the KMS key so the key material changes yearly without re-encrypting existing data.
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.
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.
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.
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.
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.
Refresh a Materialized View Concurrently
Refresh the materialized view concurrently so readers never block and the dashboard stays available during the 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.
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.
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.
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.
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.
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.