How to Implement a Fair Async Mutex
Serialize access to a shared resource with a FIFO lock so no task starves and lock waits are observable.
Step-by-step guides and in-depth articles to level up your skills.
Page 6 of 9
Serialize access to a shared resource with a FIFO lock so no task starves and lock waits are observable.
Exchange tokens between services with the RFC 8693 token exchange grant so a service acts on behalf of a user without a shared long-lived credential.
Build actors with private state, a mailbox and message passing so shared mutable state becomes a queue of messages instead of a race.
Build an affected-only task graph for a monorepo so CI runs only the tasks a change requires, using git diff and package dependencies.
Keep a fast producer from exhausting memory by respecting write() return values, using pipeline() and pausing sources when read buffers fill.
Use async iterators to let a slow consumer pull from a fast producer, so memory stays bounded and pressure propagates upstream.
Limit how many tasks run at once so a fan-out does not exhaust file descriptors, connections or memory.
Move data between concurrent tasks with bounded channels instead of shared memory, so synchronisation is part of the data transfer.
Run controlled chaos experiments that inject real failures, state a hypothesis and blast radius, and stop safely, to prove resilience.
Secure service-to-service and device authentication with mutual TLS: certificate issuance, verification, rotation and revocation.
Load only the JavaScript a route needs, defer the rest, and prefetch the next chunk so a split never costs a delay.
Run always-on, low-overhead profiling in production to attribute CPU and memory cost to specific functions and find regressions before users do.
Replace brittle integration tests with contract tests between consumers and providers, using consumer-driven pacts and a broker.
Keep the event loop responsive by yielding between units of CPU work, using chunked processing and setImmediate to avoid starving I/O.
Share immutable snapshots safely across readers and writers using copy-on-write, so readers never block and mutations stay consistent.
Guard data pipelines with SQL assertions for nulls, uniqueness, referential integrity, freshness and ranges, failing the job when data is wrong.
Propagate a single deadline through a call graph and cancel work in flight so a slow leaf does not tie up every caller above it.
Bind access tokens to a client-held key with DPoP so a stolen bearer token cannot be replayed by an attacker.
Make multi-step workflows survive crashes with durable execution: persisted state, deterministic replay, activities and idempotent effects.
Confirm a user owns an email address with a single-use, expiring token, and resend safely without enabling abuse or enumeration.
Avoid re-embedding identical text by keying a cache on a content hash and the model version, with LRU eviction and stampede protection.
Protect data at rest with envelope encryption: a KMS master key wraps per-object data keys, limiting blast radius and enabling rotation.
Build tumbling, sliding and session windows over event time with watermarks, so stream aggregates reflect when things happened, not when they arrived.
Version features and compute training sets point-in-time correctly, so a model sees only what was knowable at the moment of each prediction.
Encrypt sensitive columns individually with per-field keys and authenticated encryption, keeping plaintext out of databases, backups and logs.
Generate missing time buckets and carry the last known value forward in SQL, so charts and reports have a continuous series without holes.
Keep a service usable under stress by disabling expensive features at runtime with flags instead of failing the whole request.
Stop sending traffic to an instance before shutting it down, let in-flight requests finish, then exit so deploys are invisible.
Enable gRPC server reflection for dynamic clients and propagate deadlines across calls, so latency budgets and discovery work end to end.
Validate, constrain and repair large language model output before it reaches users, with schema checks, allow-list tools and safe fallbacks.
Connect fast on dual-stack hosts with Happy Eyeballs: race IPv6 and IPv4, prefer IPv6 with a head start, and connect to whichever answers first.
Combine lexical BM25 search with dense vector retrieval and fuse the rankings so keyword and semantic queries both return relevant results.
Make retried requests safe by storing a client-supplied key and replaying the original result instead of performing the work twice.
Make stream consumers idempotent so at-least-once delivery, retries and rebalances never double-apply an event or lose one silently.
Give a language model tools without letting it run arbitrary actions, using typed schemas, least-privilege scopes and human confirmation gates.
Replicate selected tables between databases with logical replication: publications, subscriptions, initial sync and conflict handling.
Cache the answer that something does not exist for a short time, so repeated lookups for a missing key do not hammer the origin.
Add the authorization code flow to a server-rendered app with state, PKCE, exact redirect URIs and server-side token storage.
Add Proof Key for Code Exchange to a single-page app so a public client can use the authorization code flow without shipping a client secret.
Prevent lost updates without holding locks by adding a version column and rejecting writes based on a stale version.
Apply UI changes before the server confirms, then reconcile or roll back on failure, keeping the interface responsive and correct.
Add passkey sign-in with WebAuthn: registration and authentication ceremonies, credential storage, and the checks that prevent phishing.
Collect implicit and explicit feedback, turn it into training signal, and avoid the feedback loop that makes a recommender narrow over time.
Capture, deduplicate and route exceptions reliably without flooding a tracker, leaking secrets or losing the errors that matter.
Deduplicate identical concurrent calls into a single upstream request so a burst of readers does not fan out into a burst of fetches.
Meter usage per API key over a billing period, enforce it beyond the short-term rate limit, and tell clients how much remains.
Build SCIM endpoints so an identity provider can create, update and deactivate users automatically, with correct filtering and ETags.
Serve prefix suggestions in milliseconds with an indexed prefix structure, client debouncing and a ranking that favours useful results.
Alert on error-budget burn rate with multi-window, multi-burn-rate rules so alarms fire on real outages without paging on every blip.
Produce SLSA provenance for builds so artifacts carry verifiable evidence of what source produced them and how, enabling policy checks.
Pin the exact bytes of third-party scripts and styles with integrity hashes so a compromised CDN cannot run altered code in your pages.
Use PostgreSQL table inheritance and partitioning to model shared columns and query across child tables, with the constraints that apply.
Keep tenant data separate in one database with row-level policies, scoped queries and defence so a missing filter cannot leak data.
Validate opaque access tokens with the introspection endpoint, cache the results, and reason about the trade-offs versus JWT validation.
Choose head, tail and per-key sampling so traces stay useful and cheap: keep every error and slow request while sampling the boring majority.
Share types between a TypeScript server and client with tRPC: routers and procedures, input validation, context and error handling.
Render only the visible rows of a long list, keeping the DOM small so a list of thousands stays smooth.
Catch unintended UI changes with screenshot comparison: stable rendering, controlled environments, reviewable diffs and meaningful thresholds.
Add indexes to a busy table without blocking writes: concurrent index creation, its cost, failure handling and safe rollback.
Add traces, spans and context propagation to a service so a single request can be followed across every hop it touches.
Instrument latency, traffic, errors and saturation for every service using consistent metrics, so health is visible before customers report it.
Organise a lakehouse into bronze, silver and gold layers, with clear responsibilities, contracts and reprocessing so each layer earns its keep.
Attach trace ids to histogram measurements as exemplars so you can jump from a latency spike on a dashboard straight to the request that caused it.
Measure how an API behaves under realistic load with scripted virtual users, thresholds and staged ramps before real traffic arrives.
Issue opaque session tokens, store only their hash, rotate on privilege change, and revoke cleanly so a stolen token has a short life.
Collect field metrics from real visitors so you optimise what users experience, not what a lab test with a fast laptop shows.
Use mutation testing to find assertions that never fail by injecting small code changes and checking whether your suite detects them.
Measure how far a replica trails its primary, understand what causes lag, and bound the staleness your readers can tolerate.
Use esbuild for fast JS/TS bundling: entry points, code splitting, external deps, CSS and defining production globals correctly.
Design composite, covering and partial indexes from the queries you actually run, and drop indexes you do not need.
Keep a web font from blocking text or shifting layout with font-display, preload, subsetting and a size-adjusted fallback.
Speed up CI by sharding tests across workers with stable distribution, isolated databases and deterministic ordering, without hiding failures.
Enforce authorization on every request at the object level, deny by default, and test it adversarially so a missing check cannot leak data.
Compare secrets in constant time, equalise visible work, and close the timing side channels that leak values byte by byte.
Find what is re-rendering, why, and fix it by memoising props, moving state down and keeping context from fanning out.
Rotate database passwords without downtime using dual credentials, connection pool draining and a verified cutover, plus a rollback path.
Manage encryption keys and application secrets so rotation happens on schedule without downtime or redeploys.
Add automated accessibility checks to CI with axe, keyboard tests and manual review, and gate merges on regressions without false confidence.
Change a schema while old and new code run at once by expanding first, migrating data, and contracting last.
Keep credentials out of the repository by scanning every pull request for secret patterns and blocking merges on high-confidence findings.
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.