How to Secure File Downloads with Presigned URLs
Serve private files through short-lived signed URLs so storage credentials stay on the server and access is time-bounded.
Step-by-step guides and in-depth articles to level up your skills.
Page 7 of 9
Serve private files through short-lived signed URLs so storage credentials stay on the server and access is time-bounded.
Preserve the real client address through a load balancer with the PROXY protocol header, and configure the proxy to trust it only from the balancer.
Manage multiple packages in one repository with linked dependencies, a single lockfile and reproducible installs.
Reject excess work at the door so a service stays responsive for the requests it accepts instead of timing out for all of them.
Analyse what is in the bundle, remove or replace the heavy dependencies, enable tree shaking, and set a budget so it stays small.
Attach a cryptographic signature to container images so a cluster can verify provenance before it runs a tag.
Diagnose and shrink a bloated Docker image: layer analysis, smaller bases, pruning dev dependencies and removing build leftovers.
Share build outputs between machines so CI rebuilds only what changed, keyed by content rather than by timestamps.
Reduce the cost of window functions by indexing for their ordering, shrinking the frame, and aggregating in stages.
Test transaction boundaries, rollback behaviour and isolation with real databases, covering the paths that a mock cannot represent.
Test functions whose correct output is hard to compute by asserting invariant relationships between pairs of inputs and their outputs.
Find which tests fail without a code change, quarantine them so the suite stays trustworthy, and fix the root cause instead of retrying.
Detect dead gRPC connections early with keepalive and health checking: pings, timeouts, server policy and avoiding keepalive abuse.
Stop bloat and transaction ID wraparound by setting per-table autovacuum thresholds, scale factors and cost limits that match your write rate.
Tune TCP for low latency: congestion control, socket buffers, fast open, nagle and delayed ACK, and measure the effect rather than guessing.
Adjust send and receive buffers, window scaling and congestion control so a high-latency link is not limited by defaults.
Serialize application-level work with advisory locks: session versus transaction locks, keying, ordering, and avoiding lock leaks.
Propagate request-scoped context such as trace ids and tenant ids through async calls with AsyncLocalStorage, without threading arguments everywhere.
Use BRIN indexes for huge, naturally ordered tables: tiny size, cheap maintenance and fast range scans when the data correlates with its position.
Cut request latency with preconnect, dns-prefetch and preload hints, so the browser sets up connections and fetches resources before they are needed.
Turn queries into index-only scans with covering indexes and INCLUDE, and understand when the visibility map still forces a heap visit.
Issue short-lived, per-instance database credentials from HashiCorp Vault so there are no long-lived passwords to rotate or leak.
Find the queries that cost the most with pg_stat_statements: normalized fingerprints, per-query timing and the limits of the view.
Split a large TypeScript codebase into projects that build incrementally and enforce dependency direction, so a type-check is not a full rebuild.
Move heavy computation off the event loop with worker threads so request latency stays low under load.
Verify an OpenID Connect ID token against the provider JWKS and enforce issuer, audience, nonce and time claims so login cannot be spoofed.
Record intended version bumps per change and let a tool compute package versions and changelogs deterministically.
Evolve event schemas safely with a schema registry: compatibility modes, writer and reader schemas, and a CI check before publish.
Pin down the current behaviour of legacy code with tests that record what it does, so you can refactor safely.
Compile in one stage and copy only the runtime artifacts into a smaller final image, with cached dependency layers.
Query trees and graphs in SQL with recursive common table expressions, including cycle protection and depth-limited traversal.
Carry a trace identifier through HTTP, queues and background jobs so a single request can be followed end to end without gaps that hide the real bottleneck.
Shape outbound model traffic with token buckets, respect provider limits and Retry-After, and keep one abusive tenant from starving every other caller.
Diagnose stop the world pauses, cut allocation pressure at the source, and tune the collector so latency budgets survive real traffic instead of benchmarks.
Rerank retrieval candidates by scoring each query and document pair directly, and weigh the latency and cost before adding this stage to the request path.
Keep vectors in PostgreSQL beside the rows they describe, choose the right index and operator, and write similarity queries that filter correctly.
Deliver model output token by token with server sent events, handle disconnects cleanly, and avoid buffering that turns a fast first token into a long wait.
Capture usage from every model response, attribute spend to features and tenants, and set budgets that trip before a runaway loop becomes a surprising invoice.
See why fresh connections transfer slowly, why connection reuse wins throughput, and how to apply AIMD-style concurrency control in clients.
Prevent async races: serialize access to shared state, use a keyed mutex, ignore stale responses, and test the interleavings that break.
Keep database transactions short: move slow work outside the transaction, detect a long transaction, and understand the vacuum and lock damage it causes.
Detect and fix the N+1 query pattern: load related data in one round trip, batch by key, and verify the query count stays constant as rows grow.
Collapse duplicate in-flight requests with singleflight, merge small calls into batch endpoints, and keep failure semantics honest at the merge point.
Use INSERT ON CONFLICT with a real unique target, chunk large ingest batches, return actual outcomes, and distinguish inserts from updates.
Implement a circuit breaker in Node.js with closed, open, and half-open states, failure thresholds, timeouts, fallbacks, and tests for every transition.
Parse with schemas before logic, collect per-field errors with paths, quarantine bad rows with reasons, and replay from the dead-letter store.
Normalize keys before comparing, dedupe exactly with unique constraints, pre-filter with bloom filters, and quantify miss and false-positive rates.
Design a durable job queue with atomic claiming, exponential backoff with jitter, maximum attempts, and a dead-letter path that keeps failures inspectable.
Automate the release and the changelog: derive the version and the notes from the commits, tag and publish, and keep it repeatable.
Generate safe Content-Disposition headers for downloads, handle non-ASCII filenames with RFC 5987 encoding, and avoid header injection.
Design a dashboard for the question it answers: lead with the RED signals, add context, avoid vanity panels, and keep it for a purpose.
Build interactive prompts: detect the terminal, validate the input, support non-interactive flags, and never hang a scripted run.
Add shell completion: generate the script for each shell, complete the subcommands and the flags, and test the generated words.
Stream rows through COPY, stage into an unlogged table, validate with SQL, then insert-select in chunks with resumable checkpoints.
Cache query results without stale correctness: key by all inputs, scope by user where needed, invalidate on write, and guard the N+1 case.
Decide when to store structured data in JSONB columns versus normalized tables: weigh querying, indexing, constraints, and schema evolution.
Pick the right observability signal: metrics for trends and alerts, logs for detail, traces for causality, and use each for what it is good at.
Pick the right synchronization primitive: mutex for exclusive access, semaphore for bounded concurrency, and keyed locks for partitioned state.
Compare SELECT FOR UPDATE against version-column checks, pick by contention level and transaction length, and implement retries for conflicts.
Apply HTTP method semantics correctly: PUT replaces, PATCH modifies, POST creates or acts, and each carries different idempotency guarantees.
Pick REST or GraphQL from the client needs: weigh over-fetching, caching, versioning, and tooling, and match the choice to the workload.
Compare transport semantics, reconnection behavior, proxy compatibility, and HTTP/2 limits to pick server-sent events or WebSockets with confidence.
Pick correct HTTP status codes for success, redirect, client error, and server error cases, and avoid the 200-with-an-error-field anti-pattern.
Sort failures by layer, gate retries on idempotency, parse Retry-After, and add full-jitter backoff with a deadline so retries help instead of amplify.
Propagate one deadline from the entry point, derive per-call timeouts from the remainder, and keep retries inside the same budget.
Set s-maxage and stale-while-revalidate for shared caches, add an origin shield, purge by fingerprint, and verify hits with Age headers.
Start from default-src, move scripts to nonces with strict-dynamic, deploy through report-only, and tighten the policy per violation report.
Issue short-lived SAN certificates, require and verify client certificates on every hop, extract identity from the cert, and automate rotation.
Route writes to the primary and reads to replicas, pin post-write reads, monitor replication lag, and keep failover semantics explicit.
Debug a production issue methodically: start from the symptom metric, narrow by time and scope, follow the trace, and confirm with logs.
Ladder from full features to cached, simplified, and queued modes, drive the ladder by dependency health, and make degraded states visible to users.
Split liveness from readiness, keep dependency checks out of liveness, add startup probes, and cache results so probes cannot stampede.
Make a message consumer idempotent: dedupe on the event id, apply the effect and the id in one transaction, and handle the out-of-order delivery.
Choose a multi-tenant data model: shared tables with a tenant key, schema-per-tenant, or database-per-tenant, and enforce tenant isolation.
Add deleted_at with partial unique indexes, enforce default filtering in one place, and plan restore conflicts and eventual purging.
Chain records with per-entry hashes, anchor chain heads externally, redact secrets at write time, and verify the chain continuously.
Build test data with builders: default every field, override only what matters, and keep the test focused on the behaviour under test.
Alert on symptoms, not causes: use a sustained condition, tie each alert to an action, and reduce noise so every alert is actionable.
Find and fix a leak: watch the heap over time, take heap snapshots, look for grown object groups, and remove the retention path.
Detect half-open TCP connections, use keepalive and heartbeats, handle unexpected socket resets, and retry only when it is safe.
Replace OFFSET with keyset pagination on a stable composite sort, estimate totals instead of counting, and keep cursor state tamper-proof.
Cancel async work cleanly: propagate an abort signal, release resources in finally, and make downstream operations observe the cancellation.
Configure CORS correctly for browser clients: respond to preflight, allow only intended origins, handle credentials, and expose response headers.
Recognize database deadlocks, reduce their likelihood with consistent lock order, and retry the losing transaction safely with backoff.
Make outbound calls resilient to DNS failures: cache resolutions, add timeouts, retry other records, and avoid tight retry loops on resolution errors.
Choose the right redirect status, avoid open redirects, preserve methods across 307 and 308, and prevent redirect loops and header leakage.
Rotate JWT signing keys without invalidation: publish a JWKS with a kid, keep old keys to verify, and let verifiers select the key by kid.
Stream large uploads and payloads safely: enforce size limits early, spool to disk, apply timeouts, and avoid buffering the whole body in memory.
Work with SQL three-valued logic correctly: use IS NULL, COALESCE, and NULL-safe comparison, and avoid the comparisons that silently drop rows.
Read X-Forwarded-For and Forwarded correctly, configure trusted proxies, and derive a client IP that cannot be spoofed by attackers.
Downsample time-series data: bucket by interval, roll up aggregates incrementally, and keep raw data for a shorter window than rollups.
Store timestamptz in UTC, convert at boundaries, keep future local events with their zone name, and test DST boundaries deliberately.
Stop unhandled rejections from crashing or hiding: attach handlers, catch at the boundary, avoid fire-and-forget, and monitor the global hook.
Add a BFF per client: shape the response for one client, aggregate the services, keep the client simple, and own the client-specific logic.
Build a layered cache: a local layer for speed, a shared layer for consistency, and a clear read path that falls through the layers in order.
Use pre-commit hooks to catch problems early: run the fast checks on the staged files, keep them quick, and let the CI enforce the rest.
Use a semaphore to cap concurrency: acquire a permit before work, release it in finally, and weigh fairness against throughput.
Build an in-process task queue: prioritise work, bound concurrency, retry with backoff, and survive a worker crash without losing tasks.
Build a worker pool: spawn a fixed set, distribute tasks, collect results in order or as they finish, and handle a worker that crashes.
Build an API gateway: route to the services, handle the cross-cutting concerns, authenticate at the edge, and keep it from becoming a bottleneck.