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.
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.
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.