@argos-js/bff
v0.1.2
Published
API Composition, Data Aggregation, and Resilience (Circuit Breaker & Scatter-Gather) for Argos-JS
Readme
@argos-js/bff
Ultra-fast, resilient API Composition, Scatter-Gather Data Aggregation, and Circuit Breaker pattern designed for Backend-for-Frontend (BFF) architectures in Argos-JS.
⚡ Overview
In modern microservices and distributed backends, BFF (Backend-For-Frontend) layers often need to query multiple upstream services simultaneously, combine their payloads, handle timeouts, and gracefully degrade when downstream dependencies fail.
@argos-js/bff delivers:
- Resilient Scatter-Gather Aggregator (
composeAggregator): Execute multiple async requests in parallel with strictly typed output mapping. - Circuit Breaker (
CircuitBreaker/createCircuitBreaker): Protects failing downstream systems, fast-failing in 0ms without hitting the network when OPEN. - Graceful Fallbacks & Partial Failures: Distinguish between critical (
required: true) and non-critical (required: false) dependencies. - Native AbortSignal & Timeouts: Cancel slow network requests automatically with
AbortController.
📦 Installation
pnpm add @argos-js/bff🛡️ Circuit Breaker
The Circuit Breaker pattern prevents recurring cascading failures across microservices.
[Success]
┌───────────────┐
│ CLOSED │◄───────────────────┐
└───────┬───────┘ │
│ [failureThreshold exceeded]│ [halfOpenSuccessThreshold met]
▼ │
┌───────────────┐ ┌───────┴───────┐
│ OPEN │───────────►│ HALF_OPEN │
└───────────────┘ └───────────────┘
(0ms fail-fast) [resetTimeoutMs elapsed]Usage
import { createCircuitBreaker, CircuitBreakerOpenError } from '@argos-js/bff';
// 1. Create a circuit breaker
const paymentBreaker = createCircuitBreaker({
name: 'stripe-gateway',
failureThreshold: 5, // Trip to OPEN after 5 consecutive failures
resetTimeoutMs: 10000, // Wait 10s before testing with a canary request
halfOpenSuccessThreshold: 2,// 2 consecutive successful canary probes to close
timeoutMs: 3000, // 3s timeout for each execution
onStateChange: (from, to) => {
console.warn(`[CircuitBreaker] stripe-gateway transitioned: ${from} -> ${to}`);
},
});
// 2. Execute protected requests
try {
const result = await paymentBreaker.execute(
async (signal) => {
const response = await fetch('https://api.stripe.com/v1/charges', { signal });
return await response.json();
},
// Optional fallback (value or factory function)
{ status: 'queued_offline' }
);
} catch (error) {
if (error instanceof CircuitBreakerOpenError) {
console.error('Circuit is OPEN! Short-circuited without network overhead.');
}
}🔀 Concurrency Orchestrator: composeAggregator
composeAggregator implements the scatter-gather pattern using Promise.allSettled, executing multiple upstream calls concurrently while managing individual timeouts and resilience fallbacks.
Features
- Parallel Execution: Aggregation runs concurrently, taking approximately the time of the slowest task rather than the sum of all tasks.
- Type Inference: TypeScript automatically infers the return type of each task directly from its
fetchfunction. - Required vs Optional Tasks:
required: true(default): If the task fails or times out, the entire aggregator rejects immediately withAggregatorError.required: false: If the task fails or times out, it is replaced with itsfallbackvalue without aborting the other tasks.
- AbortSignal Propagation: Tasks receive an
AbortSignalthat triggers automatically whentimeoutMsexpires. - Direct Circuit Breaker Coupling: Attach a
CircuitBreakerinstance directly to any task.
💡 Practical Example: BFF Controller
Here is how you can build a high-performance Dashboard BFF endpoint in Argos-JS:
import { ArgosApp } from '@argos-js/core';
import { composeAggregator, createCircuitBreaker } from '@argos-js/bff';
const app = new ArgosApp();
// Circuit breaker for external/unstable recommendation engine
const recommendationsBreaker = createCircuitBreaker({
name: 'ai-recs-engine',
failureThreshold: 3,
resetTimeoutMs: 15000,
});
app.get('/api/bff/home-screen', async (ctx) => {
const userId = ctx.req.headers['x-user-id'] as string;
try {
const dashboardData = await composeAggregator({
// Critical task: Must succeed or the entire screen cannot be displayed
userProfile: {
required: true,
timeoutMs: 2000,
fetch: async (signal) => {
const res = await fetch(`http://users-service/users/${userId}`, { signal });
return (await res.json()) as { id: string; name: string; email: string };
},
},
// Critical task: Orders list
recentOrders: {
required: true,
timeoutMs: 2500,
fetch: async (signal) => {
const res = await fetch(`http://orders-service/orders?userId=${userId}`, { signal });
return (await res.json()) as Array<{ id: string; total: number }>;
},
},
// Non-critical task with Circuit Breaker and Fallback
recommendations: {
required: false,
timeoutMs: 1500,
circuitBreaker: recommendationsBreaker,
fallback: { items: [], source: 'fallback_popular_items' },
fetch: async (signal) => {
const res = await fetch(`http://recommendations-service/recs/${userId}`, { signal });
return (await res.json()) as { items: string[]; source: string };
},
},
// Non-critical promotional banner
promotions: {
required: false,
timeoutMs: 1000,
fallback: [],
fetch: async (signal) => {
const res = await fetch('http://cms-service/active-promos', { signal });
return (await res.json()) as Array<{ bannerUrl: string }>;
},
},
});
// All types are 100% strictly inferred:
// dashboardData.userProfile -> { id: string; name: string; email: string }
// dashboardData.recentOrders -> Array<{ id: string; total: number }>
// dashboardData.recommendations -> { items: string[]; source: string }
// dashboardData.promotions -> Array<{ bannerUrl: string }>
return ctx.json({
success: true,
data: dashboardData,
});
} catch (error) {
return ctx.status(502).json({
success: false,
message: 'Failed to aggregate core dashboard data',
error: error instanceof Error ? error.message : String(error),
});
}
});📚 API Reference
CircuitBreaker
class CircuitBreaker {
readonly name: string;
readonly failureThreshold: number;
readonly resetTimeoutMs: number;
readonly halfOpenSuccessThreshold: number;
readonly timeoutMs?: number;
get state(): 'CLOSED' | 'OPEN' | 'HALF_OPEN';
get failures(): number;
get lastStateChange(): number;
isOpen(): boolean;
isClosed(): boolean;
isHalfOpen(): boolean;
reset(): void;
trip(): void;
execute<T>(
fn: (signal?: AbortSignal) => Promise<T>,
fallback?: T | (() => Promise<T> | T)
): Promise<T>;
}composeAggregator
function composeAggregator<TTasks extends TaskDefinitions>(
tasks: TTasks
): Promise<AggregatedResult<TTasks>>;Errors
CircuitBreakerOpenError: Thrown when a call is attempted on anOPENbreaker without a fallback.CircuitBreakerTimeoutError: Thrown when execution through the breaker exceedstimeoutMs.AggregatorError: Thrown bycomposeAggregatorif any task withrequired: truefails or times out.TaskTimeoutError: Thrown when a task incomposeAggregatorexceeds its configuredtimeoutMs.
📄 License
MIT © Argos-JS
