npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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

  1. Parallel Execution: Aggregation runs concurrently, taking approximately the time of the slowest task rather than the sum of all tasks.
  2. Type Inference: TypeScript automatically infers the return type of each task directly from its fetch function.
  3. Required vs Optional Tasks:
    • required: true (default): If the task fails or times out, the entire aggregator rejects immediately with AggregatorError.
    • required: false: If the task fails or times out, it is replaced with its fallback value without aborting the other tasks.
  4. AbortSignal Propagation: Tasks receive an AbortSignal that triggers automatically when timeoutMs expires.
  5. Direct Circuit Breaker Coupling: Attach a CircuitBreaker instance 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 an OPEN breaker without a fallback.
  • CircuitBreakerTimeoutError: Thrown when execution through the breaker exceeds timeoutMs.
  • AggregatorError: Thrown by composeAggregator if any task with required: true fails or times out.
  • TaskTimeoutError: Thrown when a task in composeAggregator exceeds its configured timeoutMs.

📄 License

MIT © Argos-JS