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.

~20 min
typescript · refactor · types

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.

~30 min
tls · certbot · automation

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.

~25 min
csp · iframe · security

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.

~25 min
testing · faker · fixtures

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.

~20 min
testing · snapshot · dom

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.

~35 min
csv · streaming · postgres

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.

~20 min
chrony · ntp · operations

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.

~30 min
rate-limit · token-bucket · api

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.

~25 min
zod · validation · api

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.

~40 min
opentelemetry · tracing · observability

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.

~35 min
ansible · secrets · automation

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.

~45 min
gitops · argocd · kubernetes

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.

~25 min
tls · caddy · automation

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.

~35 min
tls · security · monitoring

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.

~45 min
security · anti-abuse · reliability

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.

~30 min
cloud-init · security · infrastructure

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.

~35 min
kubernetes · autoscaling · reliability

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.

~25 min
observability · logging · distributed-systems

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.

~50 min
cqrs · event-sourcing · data

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.

~30 min
scheduling · reliability · jobs

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.

~35 min
security · web · performance

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.

~40 min
security · csp · web

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.

~25 min
docker · ci · security

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.

~35 min
envoy · reliability · service-mesh

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.

~40 min
authentication · security · session

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.

~35 min
graphql · frontend · caching

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.

~40 min
graphql · security · api-design

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.

~30 min
http · caching · frontend

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.

~30 min
sql · pagination · performance

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.

~25 min
makefile · tooling · dx

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.

~35 min
postgresql · performance · data

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.

~45 min
security · mtls · tls

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.

~40 min
mysql · migrations · zero-downtime

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.

~45 min
kubernetes · security · networking

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.

~45 min
oauth · cli · authentication

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.

~30 min
tls · pki · security

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.

~50 min
webauthn · authentication · security

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.

~35 min
kubernetes · reliability · scheduling

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.

~40 min
postgis · geospatial · postgresql

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.

~35 min
security · postgresql · privacy

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.

~25 min
prettier · tooling · dx

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.

~30 min
protobuf · ci · api-design

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.

~40 min
caching · databases · performance

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.

~45 min
messaging · reliability · rabbitmq

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.

~40 min
distributed-systems · locking · redis

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.

~35 min
reliability · timeouts · distributed-systems

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.

~45 min
security · multi-tenant · postgresql

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.

~50 min
distributed-systems · transactions · architecture

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.

~45 min
saml · authentication · security

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.

~45 min
pwa · offline · frontend

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.

~35 min
databases · data-lifecycle · api-design

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.

~30 min
security · sri · web

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.

~35 min
terraform · iac · reliability

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.

~35 min
turborepo · ci · performance

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.

~50 min
security · secrets · databases

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.

~40 min
kubernetes · autoscaling · performance

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.

~40 min
networking · vpn · automation

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.

~30 min
validation · forms · typescript

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.

~45 min
accessibility · frontend · aria

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.

~40 min
tls · acme · automation

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.

~30 min
api-design · rest · consistency

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.

~50 min
security · encryption · databases

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.

~40 min
monorepo · release · ci

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.

~30 min
frontend · performance · http

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.

~20 min
docker · compose · reliability

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.

~45 min
privacy · compliance · security

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.

~35 min
messaging · performance · reliability

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.

~30 min
kubernetes · jobs · scheduling

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.

~35 min
frontend · performance · api-design

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.

~35 min
docker · buildkit · ci

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.

~35 min
security · csrf · web

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.

~50 min
authentication · oauth · security

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.

~45 min
security · encryption · kms

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.

~40 min
eslint · tooling · typescript

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.

~45 min
event-sourcing · performance · data

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.

~45 min
gitops · flux · deployment

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.

~35 min
grpc · reliability · timeouts

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.

~30 min
security · web · iframe

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.

~40 min
frontend · performance · ux

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.

~45 min
istio · kubernetes · deployment

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.

~50 min
kafka · transactions · reliability

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.

~45 min
kubernetes · autoscaling · messaging

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.

~45 min
distributed-systems · scheduling · reliability

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.

~40 min
authentication · passwordless · security

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.

~30 min
caching · performance · reliability

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.

~30 min
nginx · rate-limiting · reliability

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.

~30 min
kubernetes · scheduling · infrastructure

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.

~40 min
nx · ci · performance

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.

~45 min
authentication · oidc · security

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.

~45 min
databases · migrations · zero-downtime

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.

~35 min
frontend · ux · state-management

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.

~45 min
packer · iac · images

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.

~30 min
security · web · headers

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.

~35 min
kubernetes · security · containers

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.

~35 min
postgresql · search · performance

Share Outputs Across Pulumi Stacks

Export stack outputs, read them from another stack with StackReference, and keep dependency direction acyclic so infrastructure composes cleanly.

~35 min
pulumi · iac · infrastructure

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.

~35 min
databases · consistency · replication

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.

~30 min
reliability · resilience · http

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.

~50 min
multi-tenant · databases · isolation

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.

~30 min
authentication · session · security