⚡ rezilia v0.1.0 ✓ 0 Runtime Dependencies 📦 Dual ESM + CJS 🛡️ 100% TypeScript 🌐 CDN / Script Tag Ready

rezilia

The ultimate backend resilience toolkit for Node.js ≥ 18 and Bun ≥ 1.0. Engineered to eliminate cache stampedes, lost log contexts, and cascading microservice outages with zero operational overhead.

Runtime Footprint 0 Dependencies
Environments Node • Bun
License MIT Open Source
Tree-Shaking Sub-path ESM

💡 What rezilia Solves (In Detail)

Modern distributed backends inevitably face three fatal architectural failures under load. Here is how rezilia completely eliminates each one:

📦 1. Cache Stampede & Thundering Herd Problem
Failure Mode SmartCache Solution
High-traffic backends fail when hot cached items (e.g., user:profile or feed:home) expire during peak traffic. If 1,000 requests arrive concurrently at that millisecond, naive backends run 1,000 separate database queries at once.
✕ Without rezilia

Database Exhaustion: 1,000 queries flood the connection pool simultaneously. CPU hits 100%, read latency spikes from 3ms to 8,000ms, and un-indexed DB queries trigger timeouts or full crashes.

✓ With rezilia (Singleflight + SWR)

Single in-flight Promise: Exactly 1 database fetch executes. The other 999 callers await the same in-memory mutex. With SWR, stale data returns in 0ms while refreshing in the background, and TTL Jitter (±10%) prevents mass synchronized expiry.

📝 2. Lost Log Context & Uncorrelated Production Debugging
Failure Mode SmartLogger Solution
In Node.js's event-loop model, the instant code awaits an external HTTP call or database promise, the original execution context disconnects. Correlating logs across multi-tenant requests becomes nearly impossible.
✕ Without rezilia

Debugging Nightmare: Developers must manually thread requestId, userId, and tenantId as arguments through dozens of service functions. One forgotten parameter breaks the log chain, leaving disjointed production logs.

✓ With rezilia (AsyncLocalStorage)

Zero-Parameter Propagation: Context initialized once at the middleware boundary automatically flows across every nested async call, promise, and timer. Plus, Automatic Secret Redaction scrubs API keys, auth tokens, and passwords before writing JSON.

🔄 3. Cascading Microservice Outages & Retry Storms
Failure Mode SmartRetry Solution
When a downstream third-party partner (e.g. payment processor, shipping API) degrades or hangs, calling services keep dispatching requests and immediate retries, causing thread and socket exhaustion.
✕ Without rezilia

Cascading Outages: Hundreds of concurrent requests hang waiting for unresponsive downstreams, depleting HTTP sockets and event loop capacity until your entire microservice mesh collapses with 504 Gateway Timeouts.

✓ With rezilia (Circuit Breaker)

0ms Fast-Fail Isolation: After consecutive errors reach threshold, the breaker trips to OPEN, rejecting callers immediately in 0ms so the downstream service can recover. Exponential Backoff + Jitter (±20%) prevents synchronized retry spikes.

🚀 Installation

rezilia works seamlessly across all modern Node.js and Bun package managers:

npm install rezilia

Quick Start

import { SmartCache, SmartLogger, retry } from 'rezilia';

// 1. Cache: 1000 concurrent calls collapse into exactly 1 database fetch
const cache = new SmartCache({ defaultTtl: 60_000 });
const user = await cache.get('user:42', () => db.findUser(42));

// 2. Logger: Context & requestId auto-propagate across all async boundaries
const logger = new SmartLogger({ serviceName: 'payment-service' });
logger.runWithContext({ requestId: req.id }, async () => {
  logger.info('Processing transaction'); // contains requestId automatically!
});

// 3. Retry: Exponential backoff + Circuit breaker protection
const data = await retry(() => paymentGateway.charge(order), {
  attempts: 4,
  timeout: 5_000,
  circuitBreaker: { threshold: 5, resetAfter: 30_000 }
});

Play CDN

No bundler, no npm install, no build step. Drop a single <script> tag into any plain HTML page and rezilia attaches itself to window.rezilia — ready to use immediately.

<script src="https://cdn.jsdelivr.net/npm/rezilia/dist/browser/rezilia.min.js"></script>
💡 Use rezilia.min.js (~7 KB gzipped) in production. Swap to the unminified rezilia.js while debugging — both expose the exact same window.rezilia global, built straight from src/browser/index.ts via the dedicated IIFE target in tsup.config.ts.

Quick Start (Plain HTML)

<script src="https://cdn.jsdelivr.net/npm/rezilia/dist/browser/rezilia.min.js"></script>
<script>
  const { SmartRetry, SmartCache, BrowserLogger } = window.rezilia;

  // Structured logging — no bundler required
  const logger = new BrowserLogger({ service: 'landing-page', pretty: true });
  logger.setContext({ userId: 'u_42' });

  // Retry with exponential backoff + circuit breaker
  const retry = new SmartRetry({ attempts: 3, baseDelay: 500 });

  // Singleflight cache — dedupes concurrent fetches, in-memory
  const cache = new SmartCache({ defaultTtl: 60_000 });

  async function loadUser() {
    logger.info('Fetching user profile');
    const user = await cache.get('user:42', () =>
      retry.execute(() => fetch('/api/user/42').then(r => r.json()))
    );
    logger.info('User loaded', { user });
  }

  loadUser();
</script>

What's Included in the CDN Build

The browser bundle only ships APIs that run without Node.js internals (no AsyncLocalStorage, no ioredis). It is built from src/browser/index.ts, which re-exports a browser-safe subset of the toolkit:

SmartRetry retry CircuitBreaker RetryExhaustedError TimeoutError CircuitOpenError SmartCache MemoryStore BrowserLogger
⚠️ SmartLogger (Node's AsyncLocalStorage-based logger) and the Redis-backed store option for SmartCache are not part of the CDN bundle — they depend on Node.js APIs unavailable in a browser. Use BrowserLogger instead for script-tag projects.

🎯 Problems rezilia Solves

Every production Node.js backend eventually runs into the same three catastrophic walls:

Failure Mode Without rezilia With rezilia
Cache Stampede 1,000 requests hit your database simultaneously the moment a TTL expires, causing severe query latency and DB lockouts. Singleflight Mutex — exactly 1 query executes; the other 999 callers await and share the identical result in memory.
Lost Context Logs requestId disappears as soon as code awaits an external microservice or timer, leaving disjointed log files. AsyncLocalStorage — requestId and correlation tags flow through all nested async calls automatically with zero manual parameter passing.
Cascading Outages A slow downstream partner API backs up thread queues and crashes your entire microservice mesh. Circuit Breaker — trips OPEN on consecutive failures, immediately failing fast to protect server health until the provider recovers.

1. 🔄 SmartRetry & Circuit Breaker

Resilient retries with exponential backoff, randomized jitter, individual attempt timeouts, and an integrated 3-state Circuit Breaker.

⚡ Interactive Circuit Breaker Simulator (Dotted Line Theme)
Watch the physical breaker switch open on failures and halt cascading traffic along the dotted bus.
Failure Threshold:
(0/5)
● CLOSED (Healthy)
💻 Client App Inbound Traffic rezilia Guard Circuit CLOSED 🏢 Payment API Upstream Target
🟢 Circuit CLOSED: Physical switch engaged. Inbound requests travel directly through the dotted bus to the downstream API. Passed: 0 | Blocked: 0
⏳ Fast-Fail Cooldown Window Probing in 8s...
Live Circuit Event Log
[Ready] rezilia initialized: Dotted bus armed. Breaker threshold = 5 failures, resetAfter = 8000ms.
1. CLOSED Active
Healthy state. Physical contact closed. 5 consecutive errors trip switch to OPEN.
2. OPEN Fails Fast
Tripped! Switch lever swings open. Rejects 100% of calls along dotted return in 0ms.
3. HALF_OPEN Probe
Cooldown elapsed. Allows exactly 1 canary probe. If successful, resets switch to CLOSED!

SmartRetry Options Reference

Attribute Type Default Allowed Values / Range Description
attempts number 3 1 to 20 Maximum total execution attempts (initial try + retries) before throwing error.
baseDelay number (ms) 500 50 to 10000 Initial wait time before the first retry attempt.
maxDelay number (ms) 30000 1000 to 120000 Ceiling limit for exponential backoff delay to avoid infinite stalls.
jitter number 0.2 0.0 (0%) to 1.0 (100%) Randomized delay variance (+/- percentage) preventing synchronized thundering herds.
timeout number (ms) 10000 0 (disabled) or > 0 Per-attempt execution timeout. If an attempt hangs, it is aborted and retried.
circuitBreaker object undefined { threshold, resetAfter, halfOpenSuccesses } Configuration object enabling the stateful Circuit Breaker.
shouldRetry (err: Error) => boolean () => true Custom predicate function Inspects errors to skip retries on 4xx client issues and only retry on 5xx/network errors.

2. 📦 SmartCache & Singleflight

Two-tier caching engine with Singleflight deduplication to eradicate cache stampedes, plus Stale-While-Revalidate (SWR) for zero latency spikes.

Singleflight Mutex Architecture (Dotted Flow) Status: Ready
Client #1 Client #2 Client #3 Client #4 rezilia Mutex Single In-Flight Key Lock: Idle (0 active) Database / API Executions: 0
Concurrence Path 1 Executed Fetch Shared Broadcast
💡 Without rezilia: 4 concurrent hits trigger 4 queries. With Singleflight: Exactly 1 runs.

SmartCache Options Reference

Attribute Type Default Allowed Values / Range Description
defaultTtl number (ms) 60000 (1m) 1000 to 86400000 Default expiration lifetime for stored cache items.
jitterFactor number 0.1 (10%) 0.0 to 0.5 Applies +/- randomness to TTL to prevent simultaneous mass cache eviction.
staleWhileRevalidate boolean false true | false If enabled, serves expired data immediately while fetching fresh data in the background.
staleTtl number (ms) 5000 (5s) 1000 to 60000 Maximum time window allowed to serve stale data while revalidation finishes.
store CacheStore MemoryStore MemoryStore | RedisStore Storage backend adapter. Supports optional Redis clustering via ioredis.

3. 📝 SmartLogger & Context Propagation

Zero-overhead structured JSON logger powered by Node.js AsyncLocalStorage. Auto-redacts sensitive secrets and carries correlation IDs across async boundaries.

import { SmartLogger } from 'rezilia/logger';

const logger = new SmartLogger({ serviceName: 'billing-api' });

// Context flows automatically into every nested function call
logger.runWithContext({ requestId: 'req_981a', userId: 'usr_42' }, async () => {
  logger.info('Initiating payment');
  await chargeCustomer();
  logger.info('Charge complete'); 
});

// Automatic Secret Redaction
logger.info('User auth', { apiKey: 'sk_live_990182', password: 'hunter2' });
// Output: { "apiKey": "[REDACTED]", "password": "[REDACTED]" }

SmartLogger Options Reference

Attribute Type Default Allowed Values Description
serviceName string Required e.g. 'order-api' Service name injected into every emitted JSON log record.
minLevel string 'info' 'debug' | 'info' | 'warn' | 'error' | 'silent' Minimum threshold required for a log message to be output.
redactKeys string[] [password, token, apiKey, secret, authorization, ...] Array of keys List of sensitive key names that are automatically replaced with "[REDACTED]".

4. 📟 BrowserLogger & Live Demo CDN

The drop-in logger for plain HTML/JS projects — a lightweight sibling of SmartLogger that swaps AsyncLocalStorage for a simple context object and process.stdout for console.*. Same structured-JSON output, same automatic secret redaction, zero Node.js dependency.

Watch exactly what appears in your browser console as each log call runs — press ▶ Replay Animation to see it again:

🖥️ Browser DevTools Console — Simulated Output
Ready

Sample Code

import { BrowserLogger } from 'rezilia/browser'; // or window.rezilia via CDN

const logger = new BrowserLogger({
  service: 'checkout-widget',
  pretty: true,          // human-readable console output (default: JSON)
  timeFormat: 'time',  // 'iso' | 'full' | 'time'
});

// Context merges into every subsequent log call
logger.setContext({ requestId: 'req_981a', userId: 'u_42' });

logger.debug('Widget mounted');
logger.info('Fetching cart', { cartId: 'cart_77' });
logger.warn('Coupon expired', { code: 'SAVE10' });

// Automatic secret redaction — sensitive keys become '***'
logger.info('User authenticated', { token: 'sk_live_990182', password: 'hunter2' });
// → { ..., "token": "***", "password": "***" }

logger.error('Payment failed', { reason: 'card_declined' });

BrowserLogger Options Reference

Attribute Type Default Allowed Values Description
service string 'app' e.g. 'checkout-widget' Service name stamped onto every log entry.
level LogLevel 'info' 'debug' | 'info' | 'warn' | 'error' Minimum level emitted — anything below this threshold is silently dropped.
pretty boolean false true | false When true, emits human-readable [time] [LEVEL] [service] message lines instead of raw JSON.
redact string[] [password, token, secret, authorization] Array of field names Field names replaced with '***' before being logged, matched case-insensitively.
timeFormat string 'iso' 'iso' | 'full' | 'time' Timestamp style used in pretty mode — ISO string, full date-time, or local time only.

🌳 Tree-Shakeable Imports

rezilia is engineered for minimal bundle footprint. You can import only the specific sub-modules your service requires:

import { SmartCache }  from 'rezilia/cache';   // Cache only
import { SmartLogger } from 'rezilia/logger';  // Logger only
import { retry }       from 'rezilia/retry';   // Retry only
import { SmartCache, SmartLogger, retry } from 'rezilia'; // All utilities

// CommonJS is fully supported
const { SmartCache } = require('rezilia/cache');

🏆 Why rezilia vs Alternatives

A feature-by-feature comparison with common standalone libraries in the Node.js ecosystem:

Capability rezilia node-cache winston axios-retry
Singleflight Stampede Protection ✓ Built-in ✗ No ✗ No ✗ No
Stale-While-Revalidate (SWR) ✓ Built-in ✗ No ✗ No ✗ No
AsyncLocalStorage Auto-Context ✓ Built-in ✗ No ✗ Manual ✗ No
Automatic Secret Redaction ✓ Built-in ✗ No ∼ Plugin ✗ No
Circuit Breaker Protection ✓ Built-in ✗ No ✗ No ∼ Partial
Per-Attempt Timeouts ✓ Built-in ✗ No ✗ No ✗ No
Runtime Dependencies 0 Dependencies 0 12+ 1
Bun Compatible ✓ Native ✓ Yes ✓ Yes ✓ Yes