How to Implement Correlation IDs in Logs
Correlate logs across services: carry a request id in the log context, inject it on outbound calls, and query every line for one request.
Step-by-step guides and in-depth articles to level up your skills.
Page 8 of 9
Correlate logs across services: carry a request id in the log context, inject it on outbound calls, and query every line for one request.
Separate the write and read models: write to a normalized model, project to a read model, keep them eventually consistent, and query the read side.
Issue a random token cookie, require the same value in a header or form field, compare in constant time, and layer SameSite on top.
Design data retention: set policies per data class, archive before deleting, enforce retention automatically, and prove compliance with tests.
Size and configure a database connection pool correctly: match it to database limits, detect leaks, set timeouts, and avoid the full-pool stall.
Trace a request across services: create spans, propagate the trace context, record useful attributes, and read the trace to find the slow hop.
Cache at the edge with a worker: use the cache API and Cache-Control, do stale-while-revalidate at the edge, and purge by tag.
Delete large volumes of rows efficiently: batch the deletes, control vacuum and bloat, prefer partition or table drops, and avoid long locks.
Write efficient SQL window functions: choose the right frame, index the partition and order, and avoid sorts that dominate the plan.
Define an SLO and its error budget: pick an SLI, set a target, measure the budget, and use the burn rate to alert and to decide.
Design an event-driven system: publish facts, keep events immutable, decouple producers from consumers, and handle the eventual consistency.
Model event sourcing in SQL: append immutable events, derive current state by replay, version aggregates, and snapshot to bound replay cost.
Build PostgreSQL full-text search: store a tsvector, query with tsquery, rank results, and keep the search index fresh as rows change.
Use generated columns for derived values and identity columns for keys: keep derivations consistent, index them, and avoid the wrong default.
Use golden files to test large output: compare against a stored artifact, review the diff on a change, and update the golden deliberately.
Shut down without dropping work: stop accepting, drain in-flight requests, bound the drain with a deadline, and close dependencies last.
Bridge browsers to a gRPC backend with gRPC-Web: set up the proxy, choose the wire mode, handle trailers, and expose deadlines.
Split liveness from readiness: fail liveness only when a restart helps, fail readiness when the instance cannot serve, and test both.
Generate stable validators, answer If-None-Match with 304 responses, keep ETags consistent across server replicas, and prove validation with curl.
Design Cache-Control for JSON APIs: choose public versus private, set max-age and stale-while-revalidate, use validators, and avoid caching errors.
Negotiate Accept-Encoding, choose between Brotli and gzip, compress the right response types, and avoid compressing already-compressed data.
Hold requests open until data arrives or a timeout fires, loop with AbortController and backoff, and respect connection budgets under HTTP/1.1.
Understand HTTP/2 multiplexing, configure connection reuse and priorities, and avoid the head-of-line and connection-churn mistakes that erase the benefit.
Make data loads safe to retry: upsert on a natural key, deduplicate within a batch, track load checkpoints, and test that a re-run changes nothing.
Keep a materialized aggregate fresh incrementally: track changed keys, refresh only affected rows, and reconcile with a periodic full refresh.
Validate all input at the system boundary: parse before you trust, reject invalid shapes early, and keep validation out of business logic.
Add revocation to stateless JWTs: keep a short lifetime, use a blocklist or a token version, and revoke efficiently without a lookup on every request.
Load expensive resources only when needed: defer, memoize, and invalidate, so work happens at most once and never for a caller that does not need it.
Control log volume and protect secrets: sample the high-volume events, always keep errors, and redact secrets before they are written.
Memoize without breaking correctness: key by all inputs, bound the cache, invalidate when data changes, and avoid caching errors or mutable values.
Cache builds in a monorepo: hash the inputs, reuse the output on a hash hit, cache remotely across CI, and invalidate correctly.
Parse multipart/form-data safely: understand the boundary framing, stream fields and files, enforce limits per part, and avoid buffering whole uploads.
Use ETags and conditional requests to prevent lost updates in a REST API, returning 304 for reads and 412 for stale writes without locking rows.
Hash passwords with Argon2: pick memory and time parameters, store the full encoded hash, verify and upgrade hashes over time, and test the work factor.
Enforce authorization without leaking: check at the object level, avoid 403-versus-404 leaks, filter lists by permission, and test every path.
Prefetch before the user asks: predict the next request, warm the cache and connections, and avoid wasted work for predictions that miss.
Test with properties: state an invariant, generate many inputs, shrink a failure to a minimal case, and keep the run reproducible with a seed.
Use a read-write lock: let many readers in at once, exclude writers from readers, and avoid writer starvation with a fair policy.
Enforce tenant and owner isolation with PostgreSQL row-level security: define policies, set the session context, and test that unscoped queries cannot leak.
Build a password reset that resists enumeration and token theft: send a single-use, expiring token, always respond the same, and rotate sessions.
Add the security headers around CSP: HSTS, nosniff, Referrer-Policy, Permissions-Policy, and framing controls, and test they reach every response.
Build a production Server-Sent Events endpoint in Node.js with heartbeats, reconnection, Last-Event-ID replay, and correct proxy and buffering headers.
Record and expose Server-Timing metrics, break down where request time goes, and use the header to debug latency without a denylisting conversation.
Let services find each other: use DNS or a registry, resolve at call time, cache with a TTL, and handle the instance that has gone away.
Generate signed URLs that grant narrow, time-boxed access to objects: sign the exact method and path, set expiry, and verify without leaking secrets.
Model changing attributes over time: compare Type 1, Type 2, and Type 4 history, write Type 2 rows with validity ranges, and query as of a date.
Use snapshots without rubber-stamping: snapshot stable output, review every change, keep snapshots small, and add assertions the snapshot cannot make.
Implement soft deletes with a tombstone column and partial indexes so deleted rows leave the hot index but remain recoverable and auditable.
Cache static assets effectively: fingerprint URLs, set immutable long max-age, differentiate HTML from assets, and test the caching policy.
Use structured concurrency: tie child tasks to their scope, propagate cancellation and errors, and never leave a task running past its parent.
Log structured events: emit JSON with stable fields, bind context, choose levels deliberately, and query logs as data rather than text.
Partition large PostgreSQL tables by range: create partitions, enable pruning, manage old partitions, and know when partitioning helps.
Publish events reliably with the outbox: write the event and the change in one transaction, relay the outbox, and dedupe on the consumer.
Coordinate a distributed transaction with a saga: run local steps, compensate on failure, and make each step and compensation idempotent.
Migrate incrementally with the strangler fig: route a slice to the new system, run both, and grow the new until the old is gone.
Layer Redis behind a local cache: size each tier, serialize values safely, handle Redis outages, and test hit rates across the tiers.
Add TOTP-based two-factor authentication: enroll a secret, verify time-based codes with a window, prevent replay, and provide recovery codes.
Detect half-open connections with ping frames, reconnect with jittered backoff, resync state after gaps, and test recovery without waiting for real outages.
Deliver secrets to an app at runtime instead of baking them in: load from a secret store, keep them out of images and env files, and rotate without rebuilds.
Instrument a service with the RED method: track rate, errors, and duration per endpoint, choose the right metric types, and alert on the signals.
Use coverage as a signal, not a goal: track line and branch coverage, watch the delta, and judge the tests by what they assert.
Upgrade legacy MD5 or weak bcrypt work factors to Argon2id lazily on login, wrap old hashes for dormant accounts, and verify with constant-time paths.
Enable Alt-Svc discovery, run QUIC over UDP 443, verify with curl, and constrain 0-RTT early data to idempotent requests during migration.
Keep a Node.js server responsive: detect blocking work, move it to a worker, and bound the pool so the loop stays free for requests.
Implement proactive content negotiation: parse Accept headers, honor quality values, choose a representation, and answer 406 only when truly nothing matches.
Use the Sec-WebSocket-Protocol header to select a versioned subprotocol, reject unsupported clients, and evolve the message format safely.
Serve images fast: pick modern formats with fallbacks, size and density per client, lazy-load below the fold, and cache fingerprinted variants.
Speed up JSON work: stream instead of buffering, avoid redundant stringify and parse, and pick a serializer that fits the payload.
Aggregate over JSONB efficiently: extract and cast in the right place, build expression indexes, and avoid per-row expansion that kills plans.
Prefer containment operators, add expression and GIN indexes for hot paths, promote frequent fields to columns, and verify with EXPLAIN ANALYZE.
Push WHERE predicates into the storage engine with MySQL ICP, mirror the win in PostgreSQL with partial indexes, and prove both with EXPLAIN.
Speed up SQL joins by indexing the join keys and filter columns, choosing a join strategy, and giving the planner the statistics it needs.
Preserve the order where it matters: partition by key so one entity stays ordered, and accept the cross-key parallelism as the design.
Stop attackers from learning which accounts exist: uniform responses, constant-time paths, and identical timing for login, signup, and reset.
Stop the thundering herd on a cache miss: coalesce concurrent loads, refresh ahead of expiry, and jitter TTLs so keys do not expire together.
Stop mass assignment: never spread request data into models, allowlist writable fields per operation, and separate input and persistence shapes.
Secure the OAuth redirect_uri and post-login return: register exact URIs, validate the return target, and stop token theft via open redirects.
Stop path traversal: reject .. and absolute paths, resolve against a fixed base, verify the result stays inside it, and test with encoded payloads.
Block prototype pollution from untrusted input: avoid unsafe merges, use null-prototype objects and maps, and validate keys before assignment.
Stop session fixation by rotating the session identifier on login and privilege change, binding it to the browser, and invalidating the old one.
Validate schemes, resolve DNS and check the IP against private ranges, control redirects hop by hop, and pin the connection to the validated address.
Use EXPLAIN and EXPLAIN ANALYZE to find why a query is slow: read the plan tree, spot row-estimate errors, and know when an index is ignored.
Cut database round trips: batch inserts and updates in one statement, chunk large batches, and measure the round trips per request.
Shrink API payloads with field selection: support sparse fieldsets and expansions, avoid over-fetching, and keep responses cacheable and typed.
Cut time to first byte: remove origin work before the first byte, stream the response, and use caching and connection reuse in front of the server.
Replace string concatenation with driver placeholders, whitelist the identifiers placeholders cannot carry, and find legacy code by scanning.
Pick CONCURRENTLY with a unique index, or dual-view atomic swap, schedule incremental windows, and monitor staleness with recorded refresh times.
Server push failed in practice. Replace it with preload links, 103 Early Hints, and cache-aware delivery that respects what the client already has.
Cut handshake round trips with session tickets and TLS 1.3 PSK resumption, enable client session caches, and weigh 0-RTT replay risks.
Give keys identifiers, verify with any active key while signing with the newest, overlap windows generously, and drain old usage to zero before removal.
Write hypotheses first, inject faults with bounded blast radius, auto-stop on guardrail breach, and convert findings into tracked fixes.
Render user-generated content safely: prefer escaping over sanitizing, allowlist tags and attributes when HTML is required, and stop XSS at the sink.
Harden a multipart upload endpoint with size limits, magic-byte type checks, path containment, safe storage names, and malware scanning before serving.
Use 103 Early Hints to start preloading critical subresources before the final response, and understand when it helps and when it does not.
Parse Range headers, answer with 206 and Content-Range, support multi-range responses, and handle invalid or unsatisfiable ranges correctly.
Serve stale content while refreshing in the background: set stale-while-revalidate, refresh on a hit, and keep the served value correct during the window.
Set cookies with the right flags: HttpOnly, Secure, SameSite, Path, and Max-Age, and avoid common session-hijacking and CSRF mistakes.
Report long-running CLI progress: stream the output, update the progress in place, and disable it when the output is not a terminal.
Structure each test in three phases: arrange the input, act once, and assert the outcome, so the test reads as one behavior.
Test concurrent code without flakes: control the schedule, use barriers and latches, assert invariants under contention, and run the race detector.