Luminara is a modern, universal HTTP client built on native fetch, engineered for developers and teams who demand reliability, scalability, and architectural clarity. It provides full lifecycle control over HTTP requests — from orchestration and interception to retries, deduplication, and analytics — all with zero external dependencies.
Lightweight by design yet powerful in scope, Luminara enables consistent, predictable network behavior across all environments — browsers (React, Vue, Angular, Svelte, vanilla JS) and Node.js 18+. Its domain-driven architecture and type-safe foundation make it ideal for enterprise-grade applications that need transparent debugging, real-time visibility, and extendable control over every request.
🔗 Links
- 🎨 Interactive Sandbox And Documentation Website: luminara.website
- 📦 npm Package: npmjs.com/package/luminara
- 🐙 GitHub Repository: github.com/miller-28/luminara
- ⚡ Performance Benchmarks: luminara.website/benchmark
✨ Features
Core Architecture
- ⚡ Built on modern native
fetch- Zero external dependencies - 🌐 Universal compatibility - Browsers + Node.js 18+ with native fetch
- 🏗️ Framework-agnostic - Works with React, Vue, Angular, Svelte, vanilla JS, and Node.js
- 🏗️ Domain-driven architecture - Feature-based modular structure
- 📦 Dual export support - ESM/CJS compatibility with auto-detection
- 🚗 Extensible driver architecture - Custom drivers via forking
- 💎 Ultra-compact footprint
- 🪶 Zero dependencies - Truly standalone
- 🔄 Same API everywhere - Identical behavior in all environments
Request Lifecycle (Orchestration Layer)
- 🔌 Enhanced interceptor architecture - Deterministic order, mutable context, retry-aware
- 🍪 Plugin system - Extensible architecture with official plugins (cookie-jar)
- 📊 Comprehensive stats system - Real-time metrics, analytics, and query interface
- 📝 Verbose logging system - Detailed debugging and request tracing
Pre-Flight Features (Request Dispatcher - Phase 1)
- 🔄 Request deduplication - Automatic in-flight duplicate request prevention
- ⏱️ Request debouncing - Intelligent request delay with automatic cancellation
- 🚦 Advanced rate limiting - Token bucket algorithm with global, domain, and endpoint scoping
In-Flight Features (Request Execution - Phase 2)
- ⏱️ Configurable timeouts - Request timeouts and abort controller support
- 🔄 Comprehensive retry system - 6 backoff strategies (exponential, fibonacci, jitter, etc.)
- 🏎️ Request hedging - Race and cancel-and-retry policies for latency optimization
Post-Flight Features (Response Handlers - Phase 3)
- 🎯 Response type handling - JSON, text, form data, binary support
- 🛡️ Robust error handling - Comprehensive error categorization and handling
Developer Experience
- 🎯 Fully promise-based with TypeScript support
✅ Battle-Tested Reliability
Luminara is validated by a comprehensive test suite covering all features and edge cases:
- ✅ 241 tests across 17 test suites (100% passing)
- 🎯 Programmatic validation - Tests actual behavior, not just API contracts
- 🧪 Framework simulation - React, Vue, Angular usage patterns
- ⏱️ Timing accuracy - Backoff strategies validated to millisecond precision
- 🛡️ Error scenarios - Comprehensive failure case coverage
- 🔄 Integration testing - Feature combinations (retry + timeout + hedging)
- 📊 Real package testing - Tests built distribution, not source files
Test Categories:
- Basic HTTP Operations (8) • Retry Logic (23) • Backoff Strategies (17)
- Request Hedging (24) • Interceptors (12) • Stats System (23)
- Rate Limiting (7) • Debouncing (16) • Deduplication (17)
- Error Handling (21) • Timeouts (11) • Response Types (7)
- Custom Drivers (10) • Edge Cases (15) • Framework Patterns (8)
- Plugins (7)
📋 View Test Documentation • Run Tests Locally
📦 Installation
NPM/Yarn (All Frameworks)
# npm
npm install luminara
# yarn
yarn add luminara
# pnpm
pnpm add luminara
CDN (Vanilla JavaScript)
<!-- ES Modules via CDN -->
<script type="module">
import { createLuminara } from 'https://cdn.skypack.dev/luminara';
// Your code here
</script>
Framework-Specific Imports
React, Vue, Angular, Svelte (Browser)
import { createLuminara } from 'luminara';
Node.js (ESM)
import { createLuminara } from 'luminara';
const api = createLuminara({
baseURL: 'https://api.example.com',
retry: 3,
timeout: 5000
});
const data = await api.getJson('/users');
console.log(data);
Node.js (CommonJS)
const { createLuminara } = require('luminara');
const api = createLuminara({
baseURL: 'https://api.example.com'
});
api.getJson('/users')
.then(data => console.log(data))
.catch(err => console.error(err));
Vanilla JavaScript (Browser)
import { createLuminara } from 'luminara';
🚀 Quick Start
Basic Usage
import { createLuminara } from "luminara";
const api = createLuminara();
// GET JSON
const response = await api.getJson("https://api.example.com/users");
console.log(response.data);
// POST JSON
await api.postJson("https://api.example.com/posts", {
title: "Hello Luminara",
content: "A beautiful HTTP client"
});
// GET Text
const textResponse = await api.getText("https://example.com");
// POST Form Data
await api.postForm("https://api.example.com/upload", {
name: "John",
email: "john@example.com"
});
// PUT/PATCH with JSON
await api.putJson("https://api.example.com/users/1", { name: "Updated" });
await api.patchJson("https://api.example.com/users/1", { email: "new@example.com" });
// GET XML/HTML/Binary
const xmlResponse = await api.getXml("https://api.example.com/feed.xml");
const htmlResponse = await api.getHtml("https://example.com");
const blobResponse = await api.getBlob("https://api.example.com/file.pdf");
const bufferResponse = await api.getArrayBuffer("https://api.example.com/data.bin");
// NDJSON (Newline Delimited JSON)
const ndjsonResponse = await api.getNDJSON("https://api.example.com/stream");
// Multipart form data
const formData = new FormData();
formData.append('file', fileBlob);
await api.postMultipart("https://api.example.com/upload", formData);
// SOAP requests
await api.postSoap("https://api.example.com/soap", xmlPayload, {
soapVersion: '1.1' // or '1.2'
});
Configuration
const api = createLuminara({
baseURL: "https://api.example.com",
timeout: 10000,
retry: 3,
retryDelay: 1000,
backoffType: "exponential",
backoffMaxDelay: 30000,
retryStatusCodes: [408, 429, 500, 502, 503, 504],
headers: {
"Authorization": "Bearer YOUR_TOKEN"
},
verbose: true, // Enable detailed logging
statsEnabled: true, // Enable request statistics (default: true)
ignoreResponseError: false, // Throw on HTTP errors (default: false)
responseType: "auto", // Auto-detect response type
query: { // Default query parameters
"api_version": "v1"
}
});
Rate Limiting
Luminara includes advanced rate limiting with token bucket algorithm and flexible scoping:
const api = createLuminara({
baseURL: "https://api.example.com",
rateLimit: {
rps: 10, // 10 requests per second
burst: 20, // Allow burst of 20 requests
scope: 'domain' // Rate limit per domain
}
});
// Different scoping options
const globalLimiter = createLuminara({
rateLimit: {
rps: 100,
scope: 'global' // Single rate limit across all requests
}
});
const endpointLimiter = createLuminara({
rateLimit: {
rps: 5,
scope: 'endpoint', // Rate limit per unique endpoint
include: ['/api/users/*'], // Only apply to specific patterns
exclude: ['/api/health'] // Exclude certain endpoints
}
});
// Get rate limiting stats
const rateLimitStats = api.getRateLimitStats();
console.log(rateLimitStats);
// Reset rate limiting stats
api.resetRateLimitStats();
📤 Exports & Advanced Usage
Luminara provides multiple export options for different use cases:
Simple Factory (Recommended)
import { createLuminara } from "luminara";
// Creates client with NativeFetchDriver by default
const api = createLuminara({
baseURL: "https://api.example.com",
retry: 3,
backoffType: "exponential"
});
Direct Client & Driver Access
import {
LuminaraClient,
NativeFetchDriver
} from "luminara";
// Use native fetch driver (default and only driver)
const driver = NativeFetchDriver({
timeout: 10000,
retry: 5
});
const api = new LuminaraClient(driver);
Feature Utilities & Constants
import {
backoffStrategies,
createBackoffHandler,
defaultRetryPolicy,
createRetryPolicy,
parseRetryAfter,
isIdempotentMethod,
IDEMPOTENT_METHODS,
DEFAULT_RETRY_STATUS_CODES,
StatsHub,
METRIC_TYPES,
GROUP_BY_DIMENSIONS,
TIME_WINDOWS
} from "luminara";
// Use backoff strategies directly
const exponentialDelay = backoffStrategies.exponential(3, 1000); // 4000ms
// Create custom retry policy
const customPolicy = createRetryPolicy({
maxRetries: 5,
statusCodes: [408, 429, 500, 502, 503],
methods: ['GET', 'POST', 'PUT']
});
// Check if method is idempotent
if (isIdempotentMethod('GET')) {
console.log('Safe to retry GET requests');
}
// Create standalone stats instance
const stats = new StatsHub();
Build System Support
Luminara supports both ESM and CommonJS with automatic format detection:
// ES Modules (modern bundlers, browsers)
import { createLuminara } from "luminara";
// CommonJS (legacy environments)
const { createLuminara } = require("luminara");
Build Requirements for Development:
# Required before testing sandbox/examples - generates dist files
npm run build # Production build
npm run dev # Development with watch mode
npm run build:watch # Alternative watch mode command
Note: The dist files (dist/index.mjs and dist/index.cjs) are generated during build and required for the package to work properly. Always run npm run build after making changes to src/ files.
🔄 Retry & Backoff Strategies
Luminara includes 6 built-in backoff strategies for intelligent retry handling:
Linear Backoff
Fixed delay between retries.
const api = createLuminara({
retry: 5,
retryDelay: 1000,
backoffType: 'linear'
});
Exponential Backoff
Delays grow exponentially (base × 2^n).
const api = createLuminara({
retry: 5,
retryDelay: 200,
backoffType: 'exponential'
});
// Delays: 200ms, 400ms, 800ms, 1600ms, 3200ms
Exponential Capped
Exponential growth with a maximum delay cap.
const api = createLuminara({
retry: 5,
retryDelay: 300,
backoffType: 'exponentialCapped',
backoffMaxDelay: 3000
});
Fibonacci Backoff
Delays follow the Fibonacci sequence.
const api = createLuminara({
retry: 8,
retryDelay: 200,
backoffType: 'fibonacci'
});
// Delays: 200ms, 200ms, 400ms, 600ms, 1000ms, 1600ms...
Jitter Backoff
Randomized delays to prevent thundering herd.
const api = createLuminara({
retry: 3,
retryDelay: 500,
backoffType: 'jitter'
});
Exponential Jitter
Combines exponential growth with randomization.
const api = createLuminara({
retry: 4,
retryDelay: 300,
backoffType: 'exponentialJitter',
backoffMaxDelay: 5000
});
Custom Retry Handler
For full control, provide a custom retry function:
const api = createLuminara({
retry: 4,
retryDelay: (context) => {
const attempt = context.options.retry || 0;
console.log(`Retry attempt ${attempt}`);
return 150; // Custom delay in milliseconds
}
});
Retry on Specific Status Codes
const api = createLuminara({
retry: 3,
retryDelay: 500,
retryStatusCodes: [408, 429, 500, 502, 503]
});
🏎️ Request Hedging
Request hedging sends multiple concurrent or sequential requests to reduce latency by racing against slow responses. This is particularly effective for high-latency scenarios where P99 tail latencies impact user experience.
When to Use Hedging
Use hedging when:
- High P99 latencies are impacting user experience
- Idempotent read operations (GET, HEAD, OPTIONS)
- Server-side variability is high (cloud, microservices)
- Cost of duplicate requests is acceptable
Don't use hedging when:
- Non-idempotent operations (POST, PUT, DELETE)
- Bandwidth is severely constrained
- Server capacity is limited
- Operations have side effects
Basic Race Policy
Race policy sends multiple concurrent requests and uses the first successful response:
const api = createLuminara({
hedging: {
policy: 'race',
hedgeDelay: 1000, // Wait 1s before sending hedge
maxHedges: 2 // Up to 2 hedge requests
}
});
// Timeline:
// T+0ms: Primary request sent
// T+1000ms: Hedge #1 sent (if primary not complete)
// T+2000ms: Hedge #2 sent (if neither complete)
// First successful response wins, others cancelled
await api.get('/api/data');
Cancel-and-Retry Policy
Cancel-and-retry policy cancels slow requests and retries sequentially:
const api = createLuminara({
hedging: {
policy: 'cancel-and-retry',
hedgeDelay: 1500, // Wait 1.5s before cancelling
maxHedges: 2 // Up to 2 hedge attempts
}
});
// Timeline:
// T+0ms: Primary request sent
// T+1500ms: Cancel primary, send hedge #1
// T+3000ms: Cancel hedge #1, send hedge #2
// Only one request active at a time
await api.get('/api/data');
Exponential Backoff & Jitter
Increase hedge delays exponentially with randomization to prevent thundering herd:
const api = createLuminara({
hedging: {
policy: 'race',
hedgeDelay: 500, // Base delay: 500ms
maxHedges: 3,
exponentialBackoff: true, // Enable exponential backoff
backoffMultiplier: 2, // 2x each time
jitter: true, // Add randomness
jitterRange: 0.3 // ±30% jitter
}
});
// Hedge timing with backoff:
// - Primary: 0ms
// - Hedge 1: ~500ms (500 ±30%)
// - Hedge 2: ~1000ms (1000 ±30%)
// - Hedge 3: ~2000ms (2000 ±30%)
HTTP Method Whitelist
By default, only idempotent methods are hedged:
// Default whitelist: ['GET', 'HEAD', 'OPTIONS']
const api = createLuminara({
hedging: {
policy: 'race',
hedgeDelay: 1000,
maxHedges: 2,
includeHttpMethods: ['GET', 'HEAD', 'OPTIONS', 'POST'] // Custom whitelist
}
});
await api.get('/users'); // ✅ Hedged (in whitelist)
await api.post('/data', {}); // ✅ Hedged (added to whitelist)
await api.put('/users/1', {}); // ❌ Not hedged (not in whitelist)
Per-Request Configuration (Bidirectional Override)
Override hedging settings for specific requests:
// Scenario 1: Global enabled → disable per-request
const client = createLuminara({
hedging: { policy: 'race', hedgeDelay: 1000 }
});
await client.get('/critical', {
hedging: { enabled: false } // Disable for this request
});
// Scenario 2: Global disabled → enable per-request
const client2 = createLuminara({ /* no hedging */ });
await client2.get('/slow-endpoint', {
hedging: { // Enable for this request
policy: 'race',
hedgeDelay: 500,
maxHedges: 1
}
});
Server Rotation
Distribute hedge requests across multiple servers:
const api = createLuminara({
hedging: {
policy: 'race',
hedgeDelay: 1000,
maxHedges: 2,
servers: [
'https://api1.example.com',
'https://api2.example.com',
'https://api3.example.com'
]
}
});
// Each hedge uses a different server:
// - Primary: api1.example.com/data
// - Hedge 1: api2.example.com/data
// - Hedge 2: api3.example.com/data
Hedging vs Retry
Hedging and Retry serve different purposes and can be used together:
| Feature | Hedging | Retry |
|---|---|---|
| Purpose | Reduce latency | Handle failures |
| Trigger | Slow response | Error response |
| Requests | Concurrent/Sequential proactive | Sequential reactive |
| Cost | Higher (multiple requests) | Lower (on error only) |
| Use Case | P99 optimization | Reliability |
// Combined: Hedging for latency + Retry for reliability
const api = createLuminara({
retry: false, // Disable retry (can use false or 0)
hedging: {
policy: 'race',
hedgeDelay: 1000,
maxHedges: 1
}
});
Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
enabled |
boolean |
implicit | Explicit enable/disable (implicit if config present) |
policy |
string |
'race' |
'race' or 'cancel-and-retry' |
hedgeDelay |
number |
- | Base delay before hedge (ms) |
maxHedges |
number |
1 |
Maximum hedge requests |
exponentialBackoff |
boolean |
false |
Enable exponential backoff |
backoffMultiplier |
number |
2 |
Backoff multiplier |
jitter |
boolean |
false |
Add randomness to delays |
jitterRange |
number |
0.3 |
Jitter range (±30%) |
includeHttpMethods |
string[] |
['GET', 'HEAD', 'OPTIONS'] |
Hedged HTTP methods |
servers |
string[] |
[] |
Server rotation URLs |
Performance Implications
Bandwidth: Hedging increases bandwidth usage by sending multiple requests. For a maxHedges: 2 configuration:
- Best case: 1 request (primary succeeds quickly)
- Worst case: 3 requests (primary + 2 hedges)
- Average: ~1.5-2 requests depending on latency
Latency Reduction: Typical P99 improvements:
- Race policy: 30-60% reduction in tail latencies
- Cancel-and-retry: 20-40% reduction with lower bandwidth cost
🚦 Rate Limiting
Luminara's rate limiting system uses a token bucket algorithm with flexible scoping to control request flow and prevent API abuse.
Token Bucket Algorithm
The rate limiter maintains token buckets that refill at a steady rate:
const api = createLuminara({
rateLimit: {
rps: 10, // Refill rate: 10 tokens per second
burst: 20 // Bucket capacity: 20 tokens max
}
});
// Allows bursts of 20 requests, then sustained 10 req/sec
await api.getJson('/api/data'); // Uses 1 token
Scoping Strategies
Control rate limiting granularity with different scoping options:
Global Scoping
Single rate limit across all requests:
const api = createLuminara({
rateLimit: {
rps: 100,
scope: 'global' // One bucket for everything
}
});
Domain Scoping
Separate rate limits per domain:
const api = createLuminara({
rateLimit: {
rps: 50,
scope: 'domain' // api.example.com vs api2.example.com
}
});
Endpoint Scoping
Individual rate limits per unique endpoint:
const api = createLuminara({
rateLimit: {
rps: 5,
scope: 'endpoint' // /api/users vs /api/posts
}
});
Pattern Matching
Fine-tune rate limiting with include/exclude patterns:
const api = createLuminara({
rateLimit: {
rps: 10,
scope: 'endpoint',
include: [
'/api/users/*', // Rate limit user endpoints
'/api/posts/*' // Rate limit post endpoints
],
exclude: [
'/api/health', // Exclude health checks
'/api/status' // Exclude status checks
]
}
});
Real-time Statistics
Monitor rate limiting performance:
const api = createLuminara({
rateLimit: { rps: 10,
