Fiber Rate Limiter Middleware
Throttle Fiber routes with a sliding-window rate limiter middleware, keying by API key with burst tolerance and custom 429 bodies.
Page 5 of 14
Throttle Fiber routes with a sliding-window rate limiter middleware, keying by API key with burst tolerance and custom 429 bodies.
Write generic min and max helpers constrained to ordered types, avoiding duplication across numeric and string collections.
Extract and verify JWT claims in Gin middleware, checking issuer and role before handlers, with claims injected into context.
Build a Go CI pipeline with matrix versions, module caching, lint gates, race-enabled tests, and release artifact uploads.
Batch independent Redis commands into pipelines and transactions, measuring round-trip savings and verifying atomic MULTI execution.
Configure the go-redis universal client for single, sentinel, and cluster topologies, with pool sizing and timeout discipline.
Run a hub that registers WebSocket clients into rooms, broadcasts messages to a room, and unregisters on disconnect or expiry.
Paginate PostgreSQL result sets with GORM using keyset conditions on indexed sort columns, stable under concurrent inserts.
Implement Relay-style cursor pagination with gqlgen resolvers, resolving edges and pageInfo from a keyset-ordered store.
Stop an HTTP server gracefully on SIGTERM, draining connections with a bounded context deadline before forcing closure.
Listen for termination signals and shut an HTTP server down gracefully so in-flight requests finish before the process exits.
Set per-call deadlines on gRPC clients, propagate cancellation through context, and classify DEADLINE_EXCEEDED versus CANCELED codes.
Decode a stream of JSON values from a reader without buffering the whole payload, using a decoder that reads records one at a time.
Compose HTTP handlers through middleware that wrap the next handler, adding logging, recovery, and request identifiers without duplication.
Tail MongoDB collection changes with the Go driver, filtering server-side, resuming by token, and timing out idle watches.
Stream multipart uploads in a Go handler with a memory threshold, per-file size caps, and non-blocking cleanup of partial files.
Harden an HTTP server with read, write, idle, and header timeouts so slow or hostile clients cannot pin connections open.
Drive PostgreSQL through a pgx connection pool with statement timeouts, health pings, and context-scoped transactions.
Detect PostgreSQL serialization failures in pgx transactions and retry the whole unit with backoff, aborting only on hard errors.
Expose Go runtime profiling endpoints on an internal port, sampling CPU flame graphs, heap snapshots, and goroutine dumps.
Implement a token bucket rate limiter that refills at a configured rate and allows a burst, guarding handlers against traffic spikes.
Retry idempotent HTTP requests on server errors and throttling responses, backing off between attempts and honouring context cancellation.
Retry transient failures with capped exponential backoff plus jitter, classifying errors by retryability and giving up with context.
Shield a slow loader with singleflight and a shared cache, collapsing concurrent misses into one fetch and serving stale during refresh.
Collapse duplicate concurrent requests for the same key into a single upstream call so a burst of callers does not stampede a slow dependency.
Adopt Go structured logging with slog: leveled JSON handlers, grouped attributes, log record routing, and child loggers with bound context.
Wrap failing dependencies with sony/gobreaker, opening the circuit after consecutive failures and probing recovery in half-open.
Run a parameterised query and scan each row into a struct, closing rows and checking the iteration error so resources are not leaked.
Guard outbound fetches against SSRF with an allowlist of hosts and schemes, blocking private networks and redirects to internal IPs.
Emit structured logs with the standard slog package so records carry typed key-value attributes that are easy to filter and correlate.
Recycle byte buffers with sync.Pool to cut allocation churn in hot paths, using Get/Put discipline and clearing on store.
Structure Go tests as a table of cases with subtests, so each scenario is named, isolated, and easy to extend with new rows.
Cover function branches with table-driven tests: declarative cases with names, parallel subtests, and precise failure output.
Implement a concurrency-safe token bucket with atomic refill math, per-key buckets, and TryTake plus blocking Take semantics.
Layer application config with Viper across files, environment variables with key replacer, and overrides bound to flags.
Keep WebSocket connections alive with application-level ping frames, tracking liveness with deadlines and cleaning dead peers.
Process a job channel with a fixed pool of workers, draining remaining jobs on shutdown and collecting per-worker stats safely.
Dispatch jobs to a fixed pool of workers through channels, bounding concurrency while processing a large queue of tasks.
Validate request bodies against JSON Schema compiled with AJV using OpenAPI component schemas, with fast paths and collected error details.
Buffer a stream of items into adaptive batches with async cargo, flushing on size or timing thresholds so slow items never block the queue.
Pull remote pages lazily through an async generator, batching records per yield so consumers control pacing and memory stays flat.
Race a promise against a timer so a slow dependency cannot hold a request open indefinitely, aborting the underlying signal when the deadline passes.
Implement response-layer retry in Axios via a custom interceptor with attempt counters, exponential backoff, and idempotency-aware opt-in.
Search a sorted array in logarithmic time, returning the index of a match or the insertion point when the value is absent.
Smooth bursty traffic with Bottleneck using a token reservoir, rolling rate limit, and prioritized scheduled jobs that respect a fixed quota.
Enqueue background jobs with BullMQ backed by Redis, configure exponential backoff retries, and process them in a worker with failure handling.
Parse fetched HTML with Cheerio to extract OpenGraph metadata, clean text, and attribute values without executing any page scripts.
Split an array into fixed-size batches for bulk inserts, pagination, or parallel processing without mutating the original input.
Define a GitHub Actions CI pipeline with a Node version matrix, dependency caching, conditional deployment job, and pinned action versions.
Build a git-style CLI with Commander using nested subcommands, variadic arguments, option conflict rules, and typed hook-driven configuration.
Compose a list of functions so each wraps the next, matching the middleware style used by many web frameworks.
Split a CSV line into fields while respecting quoted values that contain commas or escaped quotes, a step that naive splitting gets wrong.
Parse CSV as a stream with csv-parse, validate each row against a schema, and pipe valid records onward while collecting row-level errors.
Curry a function so partial application returns a new function until every argument is supplied, enabling reusable configured variants.
Convert timestamps between timezones with Dayjs and its UTC plugin, keeping wall-clock semantics intact and formatting per-locale output.
Debounce wraps a callback so it runs only after activity stops for a set wait, collapsing bursts of calls into a single trailing invocation.
Remove duplicate records that share a key, keeping the first or last occurrence so the result is deterministic and easy to reason about.
Clone nested objects and arrays without sharing references, using the structured clone algorithm so dates, maps, and cycles are handled correctly.
Merge nested config objects where later sources override earlier scalars but nested objects are combined recursively, a common layering need.
Handle Docker stop signals in Node so in-flight requests drain, background jobs checkpoint, and the process exits within the grace period.
Layer environment configuration from shared defaults through environment-specific files up to process environment with explicit override rules.
Escape untrusted text before inserting it into HTML so angle brackets and quotes cannot break out of the surrounding context.
Build a small publish and subscribe emitter that registers listeners per event name and supports one-shot subscribers and clean removal.
Run child processes with execa to get parsed stdout and stderr, shell-free argument arrays, and non-zero exit codes surfaced as typed errors.
Route async failures into Express error middleware with a wrapper, classify status codes, and mask internal details before responding.
Accept streaming multipart uploads in Fastify with per-file size limits, MIME allowlists, and disk writes that never buffer whole files.
Wire Fastify to Pino for structured request logging with redaction, request ids, sampling, and slow-request warnings under load.
Read a fetch response body as a stream with manual reader control, honoring backpressure so a slow consumer cannot balloon memory.
Fetch JSON from an endpoint, applying a per-attempt timeout and retrying transient failures while treating client errors as final.
Subscribe to Firebase auth state, read the current ID token before each API call, and let the SDK refresh expired tokens transparently.
Flatten arrays nested to an arbitrary depth into a single level, with an optional depth limit so callers can control how far the flattening goes.
Validate a submitted form object against field rules and collect every error at once, so users see all problems instead of one at a time.
Configure the got client to retry transient failures with exponential backoff, status-code allowlists, and per-attempt timeouts for safer polling.
Fetch paginated GraphQL connections with graphql-request, following cursor edges and pageInfo detection until the full dataset is drained.
Group an array of records into a map keyed by one of their fields, a building block for reports, indexes, and bucketed aggregations.
Build interactive CLI flows with Inquirer checkbox prompts, validated input, default selections, and answer-driven branching between steps.
Harden ioredis connections with retry backoff, command timeouts, and sentinel failover so cache clients survive restarts and primary swaps.
Verify tokens against a rotating JWKS endpoint with jose, pinning allowed algorithms and caching the key set with stale fallback on outages.
Sign and verify JWTs with the jose library using an ECDSA P-256 key pair, protected headers, and explicit audience and expiry validation.
Decode the payload of a JSON Web Token and verify that its expiry and not-before claims are respected, without trusting the token's signature blindly.
Compose Koa middleware functions in explicit execution order, tracing the onion model pass-through with early termination and downstream control.
Compute the minimum number of insertions, deletions, and substitutions between two strings, the basis of fuzzy matching and spell suggestions.
Tame high-frequency DOM and scroll events with Lodash debounce and throttle, including leading and trailing edge control and cancelable handles.
Implement a least-recently-used cache that evicts the oldest entry when capacity is exceeded, reusing Map insertion order to track recency.
Combine LRU eviction with TTL expiry and stale-while-revalidate semantics so hot keys stay warm, expired entries serve stale, and refreshes dedupe.
Model calendar-aware time spans with Luxon Interval and Duration, splitting ranges into months, comparing overlaps, and humanizing output.
Cache a function's result by argument key with an expiry, so expensive pure calls are reused briefly and stale values eventually recompute.
Paginate large MongoDB collections with stable cursor queries on indexed compound sort keys, avoiding skipped documents on offset paging.
Group multi-document writes into an atomic MongoDB transaction with a session, abort on validation failure, and retry on transient errors.
Generate compact, URL-safe identifiers with nanoid, sized from collision probability math instead of guesswork, with a custom alphabet option.
Hash passwords with the built-in scrypt using random per-user salts, explicit cost parameters, and timing-safe comparison on verification.
Chain readable, transform, and writable streams with pipeline to process large files in constant memory while propagating backpressure and errors.
Offload CPU-bound work to a pool of worker threads with Piscina-style sizing, transferable buffers, and graceful pool shutdown.
Compare two flat objects field by field and report added, removed, and changed keys, the core of audit logging and change detection.
Cap parallel task execution with p-limit so large batches of promises run at a fixed concurrency instead of exhausting memory or API quotas.
Slice an array into a page and return metadata such as total pages and whether more results follow, the shape most list endpoints expose.
Query PostgreSQL through a pg pool with always-parameterized statements, statement timeouts, idle client recycling, and pool sizing guidance.
Prevent secrets from leaking into logs by configuring Pino redaction paths, nested wildcard censoring, and strict serializer boundaries.
Instrument a service with prom-client counters for totals, histograms for latency buckets, and a default metrics endpoint for scraping.
Run an array of async tasks with a maximum concurrency, so a large batch does not open all connections at once and overwhelm a downstream service.