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

http-service-pool

v1.0.2

Published

Load balanced HTTP service pool with health checks and circuit breaker

Readme

service-pool

Load balanced HTTP service pool with health checks and circuit breaker.

Bu paket, birden fazla HTTP servisini tek bir pool altında toplayıp:

  • Health check (periyodik sağlık kontrolü)
  • Circuit breaker (otomatik aç/kapa, half-open)
  • Load balancing stratejileri
    • round-robin
    • least-connections
    • fastest
  • Retry mekanizması (belirli sayıda tekrar deneme)
  • Basit metrikler (response time, success rate vb.)

sağlayan küçük bir yardımcı kütüphanedir.


Kurulum

npm install service-pool
# veya
yarn add service-pool

Node 16+ gerektirir ve ESM ("type": "module") yapısını kullanır.


Temel Kullanım

import { ServicePool } from 'service-pool';

async function main() {
  const pool = new ServicePool(
    [
      { url: 'http://service-1.internal:8080', name: 'service-1' },
      { url: 'http://service-2.internal:8080', name: 'service-2' }
    ],
    {
      strategy: 'round-robin', // 'round-robin' | 'least-connections' | 'fastest'
      healthCheckPath: '/health',
      requestTimeout: 30000,
      healthTimeout: 5000,
      healthCheckInterval: 10000,
      maxConsecutiveFailures: 3,
      retryAttempts: 2,
      retryDelay: 1000,
      headers: {}
    }
  );

  // Örnek event dinleyicileri
  pool.on('health:changed', (status) => {
    console.log('Health changed:', status);
  });

  try {
    const response = await pool.send('/api/example');
    console.log('Response:', response);
  } catch (error) {
    console.error('Request failed:', error.message);
  }
}

main();

Daha detaylı bir örnek için examples/basic-usage.js dosyasına bakabilirsiniz.


API

ServicePool

new ServicePool(servicesConfig, options?)

  • servicesConfig: Array<{ url: string; name?: string; headers?: object; ... }>

    • url (zorunlu): Servisin base URL'i
    • name (opsiyonel): Log ve event’lerde görünecek isim
    • requestTimeout (opsiyonel): Servis özelinde request timeout
    • healthTimeout (opsiyonel): Servis özelinde health check timeout
    • healthCheckPath (opsiyonel): Servis özelinde health path
    • healthCheckValidStatus (opsiyonel): Health check için geçerli status fonksiyonu
    • maxConsecutiveFailures (opsiyonel): Servis özelinde max ardışık hata sayısı
    • headers (opsiyonel): Servise özel header’lar
  • options: Global ayarlar

    • strategy: 'round-robin' | 'least-connections' | 'fastest' (varsayılan: round-robin)
    • requestTimeout: Varsayılan request timeout (ms)
    • healthTimeout: Varsayılan health check timeout (ms)
    • healthCheckPath: Varsayılan health endpoint (örn. /health)
    • healthCheckInterval: Periyodik health check aralığı (ms) (varsayılan: 10000)
    • maxConsecutiveFailures: Bir servis için art arda max hata sayısı
    • retryAttempts: Başarısız istekte kaç kere tekrar deneneceği (ekstra deneme sayısı)
    • retryDelay: Retry denemeleri arasındaki bekleme süresi (ms)
    • headers: Tüm servislere uygulanacak global header’lar
    • autoStartHealthCheck: true/false (varsayılan: true)

Metodlar

  • pool.request(path, options?)Promise<any>

    • path: Servis base URL’ine eklenecek path (örn. /api/users)
    • options.method: HTTP metodu (varsayılan: GET)
    • options.data: Body (POST/PUT vb. için)
    • options.timeout: Bu request’e özel timeout
    • options.headers: Bu request’e özel header’lar
    • options.retryAttempts: Bu request’e özel retry sayısı
    • options.retryDelay: Bu request’e özel retry bekleme süresi
  • pool.send(path, options?)Promise<any>

    • request için basit bir alias.
  • pool.getHealthyServices()Service[]

    • Şu an sağlıklı olan servisleri döner.
  • pool.getHealthStatus(){ total, healthy, unhealthy, percentage }

    • Pool’un genel sağlık özetini verir.
  • pool.getStatus()

    • Tüm servislerin detaylı durumunu, metriklerini ve seçili stratejiyi döner.
  • pool.startHealthCheck() / pool.stopHealthCheck()

    • Periyodik health check’i başlatır / durdurur.
  • pool.resetMetrics()

    • Tüm servis metriklerini ve load balancer state’ini sıfırlar.
  • pool.destroy()

    • Health check timer’ını durdurur, listener’ları temizler.
  • pool.logStatus()

    • Pool durumunu konsola okunabilir şekilde loglar.

Event’ler

ServicePool, EventEmitter’ı genişlettiği için klasik .on(event, handler) ile dinleyebilirsiniz.

  • 'service:up'

    • Bir servis tekrar sağlıklı olduğunda tetiklenir.
    • Payload örneği: { service, url, checkDuration }
  • 'service:down'

    • Bir servis art arda belirlenen sayıda hata aldığında veya istekler sırasında başarısız olduğunda tetiklenir.
    • Payload örneği: { service, url, consecutiveFailures, reason }
  • 'health:changed'

    • Genel pool health durumu değiştiğinde tetiklenir.
    • Payload: pool.getHealthStatus() çıktısı.
  • 'health:check:completed'

    • Her health check turu sonunda tetiklenir.
    • Payload: { timestamp, results: [{ service, success }] }
  • 'request:success'

    • Bir istek başarılı olduğunda tetiklenir.
    • Payload: { service, url, duration, status }
  • 'request:failed'

    • Bir istek hata aldığında tetiklenir.
    • Payload: { service, url, duration, error }
  • 'request:retry'

    • Retry mekanizması devreye girdiğinde tetiklenir.
    • Payload: { attempt, maxAttempts, error, nextRetryIn }
  • 'request:failed:all'

    • Tüm retry denemeleri başarısız olduğunda tetiklenir.
    • Payload: { attempts, lastError }
  • 'metrics:reset'

    • Metrikler sıfırlandığında tetiklenir.

Load Balancing Stratejileri

Ayrı ayrı da import edebilirsiniz:

import { RoundRobin, LeastConnections, Fastest } from 'service-pool';

Ancak pratikte genelde sadece ServicePool kullanmanız yeterli olur; strategy opsiyonu ile hangisinin kullanılacağını belirtirsiniz.

  • round-robin

    • Sırayla servis seçer. En basit ve deterministik strateji.
  • least-connections

    • Toplam istek sayısı en az olan servisi tercih eder.
  • fastest

    • Ortalama response time’ı en düşük olan, yani tarihsel olarak en hızlı cevabı veren servisi seçer.

Service sınıfı

Normalde doğrudan kullanmanız gerekmez; ServicePool bu sınıfı içerde kullanır. Yine de referans olarak:

  • Her servis için sağlık durumunu (isHealthy, circuitState) ve metriklerini tutar.
  • checkHealth() ve request() metodları üzerinden HTTP çağrılarını gerçekleştirir.
  • up, down, request:success, request:failed, metrics:reset gibi event’ler üretir.

Geliştirme

Repo içinde sadece bu paketi çalıştırmak için:

cd packages/service-pool

# Örnek script
yarn example

# Lint
yarn lint

# Formatter
yarn format

Lisans

MIT