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.
Enforce Resource Quotas per Namespace
Set CPU and memory quotas on each namespace so a team cannot accidentally consume all cluster resources.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Hash Passwords with Argon2id Tuned Parameters
Use Argon2id with memory and iteration parameters tuned to the hardware so offline cracking takes years not hours.
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.
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.
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.
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.
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.
Scan for Secrets Leaked in Pipeline Output
Add a secret scanning step that checks build logs and artifacts for leaked tokens before publishing.
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.
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.
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.
Spread Pods Across Zones with Topology Constraints
Add a topologySpreadConstraint so a zone failure takes down at most one replica not the whole deployment.
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.
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.
Prefetch Route Data on Link Hover
Add a mouseenter listener that prefetches the next route's data so navigation feels instant on click.
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.
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.
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.
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.
Rate Limit with a Redis Token Bucket
Implement a token bucket in Redis so distributed rate limiting works across multiple instances with atomic decrements.
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.
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.
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.
Respect prefers-reduced-motion for Animations
Disable or shorten animations when the user sets reduce-motion so vestibular sensitivity is respected not ignored.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Generate an SBOM in the Build Pipeline
Produce a Software Bill of Materials on every build so downstream consumers can audit transitive dependencies.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Model Complex UI State with XState
Replace nested boolean flags with a state machine so impossible states like loading AND error are unrepresentable.
Emit Structured JSON Logs for Parsing
Replace console.log with a JSON logger so logs are machine-parseable and queryable in the aggregation system.
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.
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.
Enable Terraform State Locking with S3 and DynamoDB
Configure a DynamoDB lock table so concurrent terraform runs do not corrupt the state file.
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.
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.
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.
Retry Flaky Network Tests with Backoff
Add exponential backoff retry to tests that hit external APIs so transient 503s do not fail the pipeline.
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.
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.
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.
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.
Retry Transactions on Deadlock with Jitter
Detect a deadlock error, wait with jitter, and retry the transaction so concurrent operations do not permanently fail.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Enforce Conventional Commit Lint in CI
Add commitlint to a GitHub Actions workflow so non-conforming commit messages block the pull request before merge.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.