Recipes

Step-by-step solutions for real development tasks.

699 published

Page 6 of 20

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.

~20 min
performance · web-worker · offload

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.

~20 min
api · webhook · security

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.

~20 min
api · websocket · reconnect

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.

~20 min
security · xss · encoding

Enforce Conventional Commit Lint in CI

Add commitlint to a GitHub Actions workflow so non-conforming commit messages block the pull request before merge.

~20 min
ci · linting · git

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.

~35 min
redis · sentinel · failover

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.

~25 min
npm · security · supply-chain

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.

~30 min
pnpm · monorepo · tooling

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.

~30 min
graphql · dataloader · performance

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.

~40 min
testing · http · fixtures

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.

~30 min
docker · multistage · optimization

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.

~20 min
security · secrets · ci

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.

~20 min
github · branch-protection · governance

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.

~25 min
prometheus · metrics · observability

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.

~35 min
openapi · documentation · node

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.

~25 min
privacy · bloom-filter · pii

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.

~45 min
postgres · migration · zero-downtime

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.

~20 min
dependencies · security · overrides

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.

~15 min
git · maintenance · branches

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.

~25 min
terraform · drift · import

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