Skip to content

Latest commit

 

History

History
88 lines (65 loc) · 2.07 KB

File metadata and controls

88 lines (65 loc) · 2.07 KB

ThrottleGate

A TypeScript middleware library for intelligent API rate limiting with adaptive thresholds that automatically adjusts based on endpoint usage patterns and server load.

Installation

npm install throttlegate

Usage

Basic Rate Limiting

import express from 'express';
import { createThrottleGate } from 'throttlegate';

const app = express();

// Apply rate limiting: 100 requests per 15 minutes
const rateLimiter = createThrottleGate({
  rateLimit: 100,
  windowMs: 15 * 60 * 1000 // 15 minutes
});

app.use('/api', rateLimiter);

app.listen(3000);

Adaptive Rate Limiting

import { ThrottleGate } from 'throttlegate';

const throttle = new ThrottleGate({
  rateLimit: 1000,
  windowMs: 60 * 1000, // 1 minute
  adaptive: true, // Automatically adjust limits based on load
  analytics: true, // Enable usage tracking
  algorithm: 'sliding-window'
});

app.use('/api', throttle.middleware());

// Monitor analytics
setInterval(() => {
  const stats = throttle.getAnalytics()();
  console.log('API Stats:', stats);
}, 30000);

Custom Limit Handler

const rateLimiter = createThrottleGate({
  rateLimit: 50,
  windowMs: 10 * 60 * 1000,
  onLimitReached: (req, res) => {
    res.status(429).json({
      error: 'Rate limit exceeded',
      retryAfter: 600
    });
  }
});

Configuration Options

  • rateLimit: Maximum requests per window
  • windowMs: Time window in milliseconds
  • algorithm: 'fixed-window' | 'sliding-window' | 'token-bucket' (default: 'fixed-window')
  • adaptive: Enable adaptive rate limiting (default: false)
  • analytics: Enable usage analytics (default: false)
  • onLimitReached: Custom handler for rate limit exceeded

Features

  • Adaptive Thresholds: Automatically adjusts rate limits based on server load
  • Multiple Algorithms: Support for different throttling strategies
  • Real-time Analytics: Track request patterns and performance metrics
  • TypeScript Support: Full type safety and IntelliSense
  • Express Integration: Easy middleware integration

License

MIT