Redis Distributed Lock Acquisition
Serialize critical sections across instances with a Redis lock using SET NX with expiry, token-checked release, and lease renewal.
Page 8 of 14
Serialize critical sections across instances with a Redis lock using SET NX with expiry, token-checked release, and lease renewal.
Replace thrown exceptions with a Result union for expected failures, chaining async operations without try-catch pyramids or lost errors.
Use satisfies to check a config literal against a broad type while preserving its literal inference, catching typos without widening values.
Subscribe to a typed server-sent event stream with EventSource listeners per event type, auto-reconnect awareness, and clean teardown.
Stream newline-delimited JSON through a validating transform, quarantining malformed or schema-invalid lines while valid records flow on.
Lock down Supabase tables with row level security policies keyed to auth claims, scoping reads and writes to tenant ownership.
Drive cursor-based infinite lists with TanStack Query useInfiniteQuery, threading nextCursor through pages and prefetching ahead of scroll.
Spin up disposable PostgreSQL containers for integration tests with Testcontainers, waiting for readiness and reusing one container per suite.
Implement an async token bucket limiter with burst capacity, refill rate, per-key isolation, and wait semantics for queue-friendly callers.
Define typed RPC procedures with tRPC and Zod input schemas, sharing inferred types end to end without a schema registry or codegen step.
Read an existing TypeScript file with ts-morph, walk exported interfaces, and emit a generated barrel of constant type maps at build time.
Configure TypeScript path aliases for clean internal imports, wire runtime resolvers for each target, and ban deep relative chains.
Model patch updates with type-fest DeepPartial, merging partial trees into complete config objects while preserving nested key typing.
Write predicate functions that narrow unknown values to concrete types, turning runtime checks into compile-time guarantees at the call site.
Bind event names to their payload types in one map so listeners and emitters are checked together and misspelled events fail to compile.
Build a key-value cache that is generic over value type and fires an eviction callback, so callers get typed reads and can clean up resources.
Build a small HTTP client whose methods are typed against endpoint definitions, so request bodies and response shapes are checked at the call site.
Validate multipart FormData uploads with a Zod file schema, checking kind, size, and required metadata before persisting any file.
Model states and allowed transitions as types so invalid transitions are rejected by the compiler and the reducer stays exhaustive.
Model success and failure as a discriminated Result type instead of throwing, forcing callers to handle the error branch explicitly at compile time.
Keep TypeORM queries injection-safe with parameter placeholders, typed find options, and a guard against unsafe raw SQL fragments.
Constrain config objects with the satisfies operator, keeping literal inference for keys while enforcing the target shape.
Narrow unknown values safely with composable type guards, exhaustive switch on discriminants, and assertion helpers that throw precisely.
Derive view and input types from one canonical entity with Pick and Omit, so changes to the source shape propagate to every dependent type.
Chain validation and transformation steps with Valibot pipe syntax, from string trimming through branded IDs to parseable JSON payloads.
Isolate a module under test with Vitest vi.mock hoisting, typed mock functions, and restore between tests so suites stay order-independent.
Layer a typed message protocol over WebSocket with Zod parsing per message type, versioned envelopes, and safe close-frame handling.
Ship Winston logs to Elasticsearch with bulk indexing, retry on rejection, and index rotation mapping that keeps queries fast over time.
Coerce and transform incoming strings inside a Zod schema so trimming, defaults, and type conversion happen in one validated step.
Model variant form payloads with Zod discriminated unions, routing each discriminant to its own schema, fields, and submit handler.
Parse process environment variables through a schema at startup, failing fast with a clear message when a required setting is missing or malformed.
Convert a Zod validation error into a keyed field-message map so a form can render every issue next to the input that caused it.
Flatten process.env into a strongly typed nested config with Zod, supporting defaults, optional sections, and fail-fast startup checks.
Validate untrusted payloads with Zod safeParse, aggregate every issue with paths, and flatten errors into field-keyed message maps.
Define a validation schema once with Zod and derive the TypeScript type from it, so runtime checks and compile-time types never drift apart.
Enumerate and prune files with find -print0 and read -d '' so spaces, quotes, and newlines in filenames cannot break the script.
Guarantee one cron job at a time with a flock file descriptor, a bounded wait, exit code 75, and cleanup that always unlocks.
Parse short options with getopts, distinguish missing arguments from unknown flags, then validate exactly two positional paths.
Create a private temp directory with mktemp and remove it reliably from an EXIT trap, preserving the original exit status and signals.
Switch a product card from stacked to two columns based on its own inline size with container-type, named containers, and cqw units.
Style a high-contrast keyboard focus ring with :focus-visible, transparent base outlines, a halo, and forced-colors support.
Build a responsive gallery with repeat(auto-fit, minmax()) that never overflows, keeps captions aligned, and falls back gracefully.
Use :has with :user-invalid and aria-invalid to reveal inline errors, mark required labels, and highlight the focused field.
Hash passwords with Argon2id and a random salt, encode parameters into a PHC string, and verify in constant time.
Store integer identifiers in compact 64-bit words with set, clear, union, intersection, counting, and ordered iteration.
Connect a fast producer to a slow consumer through a small buffered channel, then stop the pipeline cleanly on deadline.
Parse dotenv files with export prefixes, quoted values, inline comments, and strict key validation, returning a plain map.
Take an exclusive non-blocking flock around a critical section, reject a second holder, and reacquire after release.
Swap immutable configuration snapshots atomically so readers never take a lock, while validating each new version first.
Build an IP allowlist from CIDR prefixes and check IPv4 or IPv6 addresses without allocating or trusting raw strings.
Protect a flaky dependency with closed, open, and half-open states, a failure threshold, and a cooldown before probing again.
Compare API tokens without leaking length or prefix through timing by hashing both sides to fixed size and using subtle.
Derive one deadline for a multi-step operation, check the remaining budget before each call, and fail fast with a wrapped error.
Apply a per-request deadline with context.WithTimeout, classify timeout errors, and cap response reads in a Go HTTP client.
Generate URL-safe tokens from crypto/rand with an entropy floor, plus unbiased numeric codes using crypto/rand.Int.
Issue a random CSRF cookie on safe requests and require a matching header on unsafe methods using constant-time comparison.
Decode CSV rows into typed structs with header checks, per-line error context, and rejection of negative numeric fields.
Coalesce bursts of events into one delayed function call using time.AfterFunc and a mutex-protected timer per debouncer.
Merge layered JSON-like configuration maps recursively so nested objects combine while scalar overrides replace base values.
Resolve a hostname through the default resolver with a context deadline, sort the addresses, and surface lookup failures clearly.
Collect every invalid signup field with errors.Join, then inspect the combined error using errors.As and Unwrap.
Send If-None-Match on repeat HTTP requests, handle 304 responses, and reuse the stored body when nothing changed.
Split work across fixed goroutines, merge every output through a fan-in channel, and restore the original input order in the result slice.
Flip a readiness probe before shutdown, wait for load balancers to stop routing, then drain in-flight HTTP requests with a bounded timeout.
Drain in-flight HTTP requests on SIGINT or SIGTERM with http.Server.Shutdown, a bounded grace period, and a clean Serve error check.
Compress HTTP responses when the client advertises gzip support, set Vary correctly, and skip negotiation for other clients.
Render untrusted names, bodies, and links through html/template so contextual escaping blocks script injection and bad URLs.
Cap JSON request bodies with MaxBytesReader, reject oversized payloads with 413, and reuse the middleware across handlers.
Format byte counts with binary units and parse human-readable sizes back into integers with rounding and unit validation.
Encode a large result set incrementally with json.Encoder and a buffered writer instead of marshalling the whole slice at once.
Resolve RFC 6901 JSON pointers against decoded documents, with strict escape validation and clear traversal errors.
Decode newline-delimited JSON events one at a time with json.Decoder, validate each record, and aggregate without buffering the file.
Encode keyset cursors as opaque base64 JSON and page records by creation time and ID without offset drift.
Compare two slices of text lines with a longest common subsequence table and emit stable add, remove, and equal operations.
Combine a map with a doubly linked list to evict least-recently-used entries and expire stale keys on read and write.
Compose request ID, structured logging, and panic recovery middleware in Go while preserving the original handler order.
Bucket observations into a fixed histogram and estimate p50, p90, and p99 without keeping every sample in memory.
Fan out events to multiple subscribers with buffered channels, dropping events for slow consumers instead of blocking publishers.
Validate or generate a request ID, echo it in the response header, and expose it through a private context key for logging.
Retry transient operations with capped exponential delays, full jitter, context cancellation, and a permanent-error sentinel.
Share one in-flight load across concurrent callers, report who led the work, and prevent a cache stampede after expiry.
Remove duplicate comparable values while preserving first-seen order, returning a new slice so the caller's data stays untouched.
Serve a built frontend from disk, fall back to index.html for extensionless routes, and return 404 for missing assets.
Map nullable database columns into sql.NullString and *string fields, then emit clean nulls through a custom JSON view.
Cut per-request allocations by borrowing bytes.Buffer from sync.Pool, copying the encoded JSON, and always returning the buffer.
Write table-driven Go tests that use subtests, parallel execution, and a shared example for email normalization cases.
Store strings in a rune-aware trie, check exact prefixes, and collect completions in sorted order with a depth-first walk.
Wrap database work in a transaction helper that rolls back on error and retries serialization conflicts with short backoff.
Store request-scoped values in context.Context with generic key types so lookups are type-safe and cannot collide by string.
Bound the total weight of concurrent work, acquire and release arbitrary weights, and wake waiters when capacity frees up.
Build a bounded Go worker pool that fans jobs out to fixed workers, streams results, and stops promptly on context cancellation.
Schedule jobs by priority with a bounded worker pool, keep FIFO order for equal priorities, and stream results through one channel.
Walk a directory into a zip file while rejecting entries that escape the root, preserving relative paths with forward slashes.
Write and compare golden files with trailing whitespace tolerance, producing a compact line diff when output drifts.
Compute great-circle distance in kilometers between coordinates and build a latitude and longitude bounding box for prefiltering.
Serve a single file from a confined root and rely on ServeContent for partial content, conditional requests, and range headers.
Spin up an in-process stub server with canned JSON responses, track request counts atomically, and exercise not-found paths.
Maintain a running median in logarithmic time using a max-heap for the lower half and a min-heap for the upper half.
Implement 32-bit Murmur3 and map keys to stable shards, with a distribution check over ten thousand sample keys.
Forward requests with httputil.ReverseProxy, add a forwarded-host header, strip internal headers, and return 502 on failure.