Recipes
Step-by-step solutions for real development tasks.
699 published
Page 3 of 7
Refactor a String Enum to a Literal Union Type
Replace a runtime enum with a union of string literals, narrow at the boundaries, and verify exhaustiveness with a never check so missing cases fail to compile.
Rotate TLS Certificates with an Automated Hook
Issue a certificate with an ACME client, install it behind a load balancer, and wire a post-renewal hook that reloads the server so rotation needs no human step.
Sandbox an Iframe with CSP and Sandbox Attributes
Load untrusted content in an iframe with a strict sandbox attribute and a matching frame-src CSP rule so the framed page cannot script its parent or navigate the top window.
Seed a Test Database with Faker and a Fixture Seed
Generate deterministic fake rows with faker, pin the random seed so every run produces the same data, and reset the database between test suites with a transaction rollback.
Snapshot Test a Virtual DOM for Regressions
Render a component to a virtual DOM, serialize the tree to a stable string, and diff the snapshot on every run so structural changes fail the test.
Stream a Large CSV into a Database Without Loading It All
Parse a multi-gigabyte CSV with a streaming parser, batch the rows into prepared inserts, and report progress so the import never holds the whole file in memory.
Sync System Time with Chrony for Skew-Sensitive Work
Install chrony, point it at a nearby NTP source, and verify the clock skew stays under 50 milliseconds so certificate and log timestamps stay trustworthy.
Throttle an API with a Token Bucket Limiter
Implement a token bucket that refills at a fixed rate, consume one token per request, and return 429 with Retry-After when the bucket is empty.
Validate an API Payload with Zod at the Edge
Define a zod schema for the request body, parse the incoming payload before the handler runs, and return a 400 with a field-level error map on failure.
Wire Distributed Tracing with OpenTelemetry
Auto-instrument HTTP and database calls with the OpenTelemetry SDK, configure a batch exporter to a collector, and verify a trace spans three services.
Encrypt Secrets in Ansible with Vault
Encrypt variable files with ansible-vault, reference the vault password from a secure source, and structure variables so secrets stay out of plaintext inventory.
Manage Environments with the App-of-Apps Pattern
Define a root Application that references child Applications, keep per-environment values in Git, and let sync waves order dependencies.
Serve HTTPS Automatically with Caddy
Point a domain at Caddy, let it obtain and renew certificates automatically, and set a couple of headers and proxies without a separate certbot step.
Monitor Certificate Transparency Logs
Watch CT logs for certificates issued for your domains, alert on unknown issuances, and investigate before an attacker can use a mis-issued certificate.
Challenge Suspected Abuse Instead of Blocking
When traffic looks automated, return a lightweight challenge or require stronger proof instead of a hard block, so real users are not locked out.
Harden Cloud-Init User Data
Keep user data minimal, never embed secrets, disable password SSH, and use cloud-init only for bootstrap before configuration management takes over.
Guard Cluster Scale-Down from Disruption
Protect workloads from node removal with pod disruption budgets, annotate safe-to-evict, and let the autoscaler scale down only nodes it is sure are idle.
Propagate a Correlation ID Across Services
Generate a request identifier at the edge, forward it in headers and logs, and return it to the client so a single trace can be reconstructed later.
Rebuild Read Models by Replaying Events
Keep a projection version, consume events into a read model, and be able to replay from zero or from a checkpoint to rebuild after a bug.
Prevent Overlapping Cron Runs
Guard a scheduled job with a lock or a run-state check so a slow run cannot overlap the next tick and double-process the same window.
Enable Cross-Origin Isolation Safely
Set COOP and COEP to unlock powerful APIs like SharedArrayBuffer, then handle the resource-loading consequences so the app still works.
Harden Content Security Policy with Nonces
Drop unsafe-inline, generate a per-response nonce for legitimate scripts, and report violations so a CSP actually blocks injected scripts.
Keep Docker Build Context Small
Add a .dockerignore that excludes node_modules, build output, VCS data, and secrets so the context is small and no secret can be copied accidentally.
Configure Envoy Retries with a Budget
Enable Envoy retries with a retry budget and per-try timeout so transient failures recover without amplifying load on a struggling upstream.
Support Global Logout with Token Revocation
Track token families or a per-user token version, revoke on logout-everywhere and password change, and validate the version on every request.
Configure GraphQL Client Cache Policies
Set per-field cache and fetch policies so lists refresh when needed, single entities stay cache-first, and mutations update the cache without a refetch.
Limit GraphQL Query Complexity
Compute a cost for each query from field weights and list multipliers, reject queries above a budget, and return a clear error before execution.
Use Conditional Requests to Save Bandwidth
Store the ETag or Last-Modified value, send it back with If-None-Match, and handle the 304 so unchanged resources cost almost nothing.
Add Keyset Pagination to a SQL Endpoint
Page by a stable ordered key instead of OFFSET so deep pages stay fast and rows are neither skipped nor duplicated as data changes.
Use a Makefile as the Task Runner
Define phony targets for build, test, lint, and deploy, mark them .PHONY, and keep the Makefile as the discoverable entry point for the project.
Refresh a Materialized View without Blocking Reads
Build a materialized view for an expensive aggregate, refresh it concurrently, and manage the unique index that concurrent refresh requires.
Require mTLS for Service-to-Service Calls
Issue client certificates, configure the server to require and verify them, and validate the chain and identity so only trusted services can connect.
Guard MySQL Online DDL Changes
Check whether an ALTER can use INPLACE or INSTANT, set lock and timeout limits, and use a shadow-table tool for changes that would otherwise block writes.
Apply Default-Deny Network Policies
Deny all pod traffic by default, then allow only the flows each workload needs, so a compromised pod cannot reach unrelated services.
Add OAuth Device Authorization for CLI Clients
Use the device authorization grant so a command-line tool can authenticate through the browser without a local callback and without embedding secrets.
Generate a CSR and Key with OpenSSL
Create a private key, generate a CSR with the correct subject and SANs, verify it, and keep the key protected so a certificate can be issued cleanly.
Register a Passkey with WebAuthn
Offer a WebAuthn registration ceremony, store the credential public key and counter, and verify assertions on login without ever storing a shared secret.
Spread Critical Pods with Anti-Affinity
Use pod anti-affinity or topology spread so replicas of a critical service never land on the same node or zone, surviving a single failure.
Run a Nearby Query with PostGIS
Store locations as geography points, build a GiST index, and query with ST_DWithin so radius searches use the index and return in meters.
Mask Sensitive Columns with a View
Expose masked columns through a view for support and analytics roles, grant access to the view instead of the table, and keep the raw table restricted.
Keep Formatting Deterministic with Prettier
Run Prettier as the single formatting authority, add ignore files for generated output, and enforce it in CI so diffs never mix formatting with logic.
Enforce Protobuf Field Compatibility in CI
Catch wire-incompatible schema changes by comparing the new descriptor against the released one and failing the build on removed or renumbered fields.
Add a Read-Through Result Cache
Cache expensive query results keyed by a normalized query plus tenant, invalidate on writes, and set a TTL so stale data cannot persist after a missed invalidation.
Adopt Quorum Queues for Durable Messaging
Replace classic mirrored queues with quorum queues to get raft-based replication, safer failover, and predictable behavior under broker restarts.
Use a Distributed Lock with Fencing
Acquire a lock with a token, renew it with a watchdog, and guard the critical section with a fencing token so a delayed holder cannot corrupt shared state.
Propagate Request Deadlines Downstream
Pass an absolute deadline to every downstream call, budget the time between hops, and cancel work when the deadline passes instead of waiting indefinitely.
Enforce Row-Level Security in Postgres
Enable row-level security, write policies that filter by the current tenant, and force policies even for the table owner so isolation is enforced by the database.
Coordinate a Saga with Compensating Actions
Break a multi-service operation into local steps, define a compensation for each step, and run compensations in reverse order when a later step fails.
Refresh SAML Metadata Automatically
Store the identity provider metadata, rotate signing certificates before they expire, and validate assertion signatures against the current and next keys.
Serve an Offline Page with a Service Worker
Precache a shell and a fallback page, use a network-first strategy for navigation, and clean up old caches so users see a clear offline experience.
Add a Restore Path for Soft Deletes
Mark rows deleted instead of removing them, filter them from normal queries, and expose restore and purge endpoints with clear retention rules.
Pin CDN Assets with Subresource Integrity
Add SRI hashes to third-party scripts and styles, use crossorigin correctly, and regenerate hashes when the asset version changes so a hijacked CDN cannot inject code.
Version Terraform Modules Properly
Tag module releases, pin module sources to exact versions, keep inputs documented, and use a lock file so plans are reproducible.
Share Turborepo Cache Across CI and Developers
Configure remote caching, declare task inputs and outputs precisely, and use the cache so a task already run anywhere is not repeated locally or in CI.
Issue Dynamic Database Credentials with Vault
Configure a database secrets engine so each application instance gets a short-lived credential it does not have to store, and revoke on lease expiry.
Right-Size Pods with the Vertical Pod Autoscaler
Run VPA in recommendation mode first, review suggested requests and limits, then enable it in a controlled mode so pods get resources matching real usage.
Provision WireGuard Peers Automatically
Generate peer keys, assign addresses and allowed IPs, and reload the interface so new peers join the mesh without hand-editing config or restarting tunnels.
Add Schema Validation to a Form
Define one schema, validate on the client for instant feedback, and reject invalid payloads on the server so no rules live only in the browser.
Build an Accessible Tabs Component
Create a tabs widget with correct ARIA roles, roving tabindex, and arrow-key navigation so keyboard and screen-reader users can switch panels reliably.
Issue a Wildcard Certificate with DNS-01
Use the ACME DNS-01 challenge with a provider API token to obtain wildcard certificates, and automate renewal before expiry.
Implement a Consistent API Response Envelope
Wrap every JSON response in a uniform success/error envelope so clients parse results, errors, and pagination without special-casing each endpoint.
Encrypt Sensitive Fields at the Application Layer
Encrypt sensitive columns before writing and decrypt after reading, key by tenant where needed, and keep indexes on deterministic derived values instead of plaintext.
Version Packages with Changesets
Have contributors add a changeset describing the change, let CI open a version PR that bumps packages and updates the changelog, then publish on merge.
Deduplicate Concurrent Client Requests
Share one in-flight promise among callers of the same resource so a burst of identical requests hits the network once.
Gate Compose Services on Health
Add healthchecks and depends_on conditions so services that need a database wait for it to be healthy, not merely started.
Store and Honor Consent Records
Record what each user consented to, when, and under which policy version, then gate optional processing on the current consent so you can prove and honor it.
Tune Consumer Prefetch for Fair Throughput
Set prefetch limits per consumer, use manual acknowledgements, and size the value from processing time so one slow message does not starve the worker pool.
Set Concurrency Policy on CronJobs
Choose Forbid, Replace, or Allow intentionally, set deadlines and history limits, and make the job idempotent so an overlap cannot double-process data.
Implement a Debounced Autocomplete
Debounce keystrokes, cancel stale requests, and render suggestions in order so the list always reflects the latest query without flooding the API.
Speed Up Docker Builds with BuildKit Cache
Order layers from least to most volatile, mount caches for dependencies, and use a registry or GitHub Actions cache so CI rebuilds reuse work.
Refresh a Double-Submit CSRF Token Safely
Issue a random CSRF token in a readable cookie and require it in a header, refreshing it on login and comparing with a constant-time check.
Bind Tokens to the Client with DPoP
Use a proof-of-possession key so a stolen bearer token cannot be replayed from another machine, and validate the proof and its replay id at the resource server.
Envelope-Encrypt Data with a KMS
Generate a data key per object, encrypt data with it locally, and wrap the data key with a KMS master key so rotation does not require re-encrypting everything.
Migrate ESLint to Flat Config
Replace the eslintrc cascade with a flat eslint.config.js, compose typed rule sets explicitly, and keep overrides per file pattern.
Add Snapshots to an Event-Sourced Aggregate
Persist periodic snapshots so rebuilding an aggregate does not replay thousands of events, and version snapshots so a schema change can invalidate them safely.
Automate Image Updates with Flux
Add an ImageRepository and ImagePolicy, let Flux commit the selected tag back to Git, and keep deployments moving without manually editing tags.
Propagate gRPC Deadlines in a Service Chain
Set a deadline on every gRPC call, forward the remaining time to downstream calls, and return DEADLINE_EXCEEDED instead of waiting forever.
Harden Third-Party Iframes with Sandbox
Sandbox embedded iframes to the minimum tokens they need, never grant top navigation, and combine with a strict CSP allowlist.
Implement Infinite Scroll with IntersectionObserver
Load the next page when a sentinel enters the viewport, guard against duplicate requests, and keep a keyboard-accessible fallback for users who never scroll.
Shift Traffic Progressively with Istio
Split traffic between stable and canary with VirtualService weights, watch metrics, and promote or roll back by changing weights rather than redeploying.
Write with an Atomic Kafka Produce-and-Commit
Use transactions so a database commit and a Kafka produce either both happen or neither does, and set a stable transaction id for fencing.
Scale on Queue Depth with KEDA
Use KEDA to scale a consumer deployment from queue length, set a sensible target and cooldown, and scale to zero when the queue is empty.
Implement Leader Election with Leases
Elect a single leader using a renewable lease, let followers detect expiry, and make steps idempotent so a brief dual-leader window is harmless.
Implement Secure Magic-Link Login
Issue a single-use, short-lived, hashed token in an email link, verify it atomically, and bind it to the requesting context to prevent reuse.
Cache Negative Results Safely
Cache not-found results for a short period to protect against repeated lookups, but keep the TTL short and bypass it on user-visible writes.
Add Nginx Rate Limiting Near the Edge
Define a shared memory zone, apply a limit_req with burst and nodelay, and return 429 so abusive clients are slowed before they reach the application.
Isolate Workloads with Taints and Tolerations
Taint special nodes so only workloads that tolerate them are scheduled there, and pair it with node affinity so pods land where they belong.
Build Only Affected Projects with Nx
Let Nx compute the affected graph from the changed files, run only affected targets in CI, and cache outputs so untouched projects are never rebuilt.
Validate OIDC Tokens with JWKS
Fetch the issuer JWKS, verify the signature, check iss, aud, exp and nbf, cache keys by kid, and refresh the key set on rotation.
Rename a Column with Zero Downtime
Introduce the new column, dual-write and backfill, switch reads, then drop the old column in a separate deploy so no release breaks the running app.
Implement Optimistic UI Updates with Rollback
Apply a UI change immediately, reconcile it with the server response, and restore the previous state when the request fails so the interface never lies.
Build Immutable Images with Packer
Define a Packer template that bakes a hardened base image, validate and build it in CI, and version the resulting image so instances boot identically.
Restrict Features with Permissions-Policy
Send a Permissions-Policy header that disables powerful browser features the app does not use, so injected or third-party code cannot call them.
Harden Pods with a Security Context
Run as non-root, disable privilege escalation, drop capabilities, use a read-only root filesystem, and set seccomp so a container breakout is much harder.
Add Fuzzy Search with Postgres Trigram Indexes
Enable pg_trgm, build a GIN index on the search column, and query with similarity operators so misspellings still match fast.
Share Outputs Across Pulumi Stacks
Export stack outputs, read them from another stack with StackReference, and keep dependency direction acyclic so infrastructure composes cleanly.
Guarantee Read-Your-Writes Consistency
Route a user's reads to the primary after a write, or carry a version token, so a user never sees their own change vanish on a replica.
Retry with Exponential Backoff and Jitter
Retry transient failures a bounded number of times with exponential delay plus jitter, and only retry operations that are safe to repeat.
Isolate Tenants with a Schema per Tenant
Give each tenant its own database schema, route connections by tenant, and run migrations across all schemas so isolation does not become a migration burden.
Prevent Session Fixation on Login
Rotate the session identifier on privilege change, regenerate the cookie after authentication, and invalidate the pre-login session so a fixed id cannot be reused.