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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@hsuite/throttler

v2.1.0

Published

A powerful and flexible rate limiting library for NestJS applications, providing robust protection against abuse and ensuring optimal resource utilization with Redis-based distributed storage support.

Readme

@hsuite/throttler

A powerful and flexible rate limiting library for NestJS applications, providing robust protection against abuse and ensuring optimal resource utilization with Redis-based distributed storage support.

Features

  • 🚀 Flexible Rate Limiting: Configure custom limits and time windows per route or globally
  • 🔄 Multiple Storage Options: Support for Redis (distributed) and in-memory storage
  • 🛡️ IP-Based Protection: Track and limit requests based on IP addresses
  • High Performance: Efficient request tracking and limit enforcement with Redis backend
  • 🔌 Easy Integration: Seamless integration with NestJS applications using ThrottlerGuard
  • 🎯 Custom Rules: Support for dynamic rate limiting rules and blocking mechanisms
  • 📊 Response Headers: Automatic rate limit information in response headers
  • 🔄 Redis Integration: Native Redis support for distributed rate limiting across multiple instances
  • 🛠️ TypeScript Support: Full TypeScript integration with strict type definitions

Installation

npm install @hsuite/throttler

Dependencies

Peer Dependencies

  • @nestjs/common: ^10.4.2
  • @nestjs/core: ^10.4.2
  • @hsuite/throttler-types: ^2.0.9

Dev Dependencies

  • @compodoc/compodoc: ^1.1.23

Quick Start

Basic Module Setup

import { SecurityThrottlerModule } from '@hsuite/throttler';
import { Module } from '@nestjs/common';

@Module({
  imports: [
    SecurityThrottlerModule.forRootAsync({
      useFactory: () => ({
        enabled: true,
        storage: 'redis', // or 'memory'
        settings: {
          ttl: 60,    // Time window in seconds
          limit: 100  // Maximum requests per window
        },
        redis: {
          socket: {
            host: 'localhost',
            port: 6379
          }
        }
      })
    })
  ]
})
export class AppModule {}

Advanced Redis Configuration

import { SecurityThrottlerModule } from '@hsuite/throttler';
import { IThrottler } from '@hsuite/throttler-types';

SecurityThrottlerModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: (config: ConfigService): IThrottler.IOptions => ({
    enabled: config.get('THROTTLE_ENABLED', true),
    storage: IThrottler.IStorage.REDIS,
    settings: {
      ttl: config.get('THROTTLE_TTL', 60),
      limit: config.get('THROTTLE_LIMIT', 250)
    },
    redis: {
      socket: {
        host: config.get('REDIS_URL'),
        port: config.get('REDIS_PORT', 6379)
      },
      password: config.get('REDIS_PASSWORD'),
      username: config.get('REDIS_USERNAME', 'default'),
      database: config.get('REDIS_DATABASE', 0),
      ttl: config.get('REDIS_TTL', 120)
    }
  }),
  inject: [ConfigService]
})

Protecting Routes

The module automatically registers a global guard, but you can also use it explicitly:

import { CustomThrottlerGuard } from '@hsuite/throttler';
import { Controller, Get, UseGuards } from '@nestjs/common';

@Controller()
@UseGuards(CustomThrottlerGuard)
export class AppController {
  @Get()
  public getData() {
    return 'Rate limited endpoint';
  }
}

Configuration Options

IThrottler.IOptions Interface

| Option | Type | Required | Description | |--------|------|----------|-------------| | enabled | boolean | Yes | Enable/disable throttling globally | | storage | IThrottler.IStorage | Yes | Storage backend: 'redis' or 'default' | | settings | ThrottlerSettings | Yes | Rate limiting configuration | | redis | RedisClientOptions | No | Redis connection options (required if storage is 'redis') |

ThrottlerSettings

| Option | Type | Description | |--------|------|-------------| | ttl | number | Time window in seconds | | limit | number | Maximum requests per window |

Redis Configuration

| Option | Type | Description | |--------|------|-------------| | socket.host | string | Redis server hostname | | socket.port | number | Redis server port | | password | string | Redis authentication password | | username | string | Redis username (optional, defaults to 'default') | | database | number | Redis database number | | ttl | number | Redis key TTL in seconds |

Response Headers

The CustomThrottlerGuard automatically sets the following response headers:

  • X-RateLimit-Limit: Maximum requests allowed in the current window
  • X-RateLimit-Remaining: Remaining requests in current window
  • X-RateLimit-Reset: Time until window reset (in seconds)
  • Retry-After: Seconds to wait when rate limit is exceeded (only when blocked)

Core Components

SecurityThrottlerModule

The main module providing rate limiting functionality:

// Async configuration with factory
SecurityThrottlerModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: (config: ConfigService) => ({
    enabled: true,
    storage: IThrottler.IStorage.REDIS,
    settings: { ttl: 60, limit: 250 },
    redis: { /* Redis config */ }
  }),
  inject: [ConfigService]
})

SecurityThrottlerService

Injectable service for programmatic access to throttling functionality:

import { SecurityThrottlerService } from '@hsuite/throttler';

@Injectable()
export class MyService {
  constructor(private throttlerService: SecurityThrottlerService) {}
  
  // Access throttler service functionality
}

CustomThrottlerGuard

IP-based rate limiting guard extending NestJS ThrottlerGuard:

import { CustomThrottlerGuard } from '@hsuite/throttler';

// Automatically registered as global guard
// Can also be used explicitly on controllers/routes
@UseGuards(CustomThrottlerGuard)
export class ProtectedController {}

Advanced Usage

Custom Request Handling

The CustomThrottlerGuard provides methods for flexible rate limiting:

import { CustomThrottlerGuard } from '@hsuite/throttler';
import { Injectable, ExecutionContext } from '@nestjs/common';

@Injectable()
export class MyCustomGuard extends CustomThrottlerGuard {
  async handleCustomRequest(
    context: ExecutionContext,
    limit: number,
    ttl: number
  ): Promise<boolean> {
    // Custom rate limiting logic with dynamic limits
    return super.handleCustomRequest(context, limit, ttl);
  }
}

Storage Backend Selection

Redis Storage (Recommended for Production)

  • Distributed rate limiting across multiple server instances
  • Persistent request tracking
  • High performance with configurable connection options
storage: IThrottler.IStorage.REDIS,
redis: {
  socket: { host: 'redis-cluster.example.com', port: 6379 },
  password: 'secure-password',
  database: 1
}

In-Memory Storage (Development/Single Instance)

  • Local memory storage for single-instance applications
  • No external dependencies required
storage: IThrottler.IStorage.DEFAULT
// No redis configuration needed

Rate Limiting Implementation

IP-Based Tracking

  • Requests are tracked per IP address
  • Configurable time windows (TTL) and request limits
  • Automatic blocking with retry-after headers

Request Flow

  1. Request Received: Guard intercepts incoming request
  2. IP Extraction: Client IP address is identified and tracked
  3. Counter Increment: Request counter is incremented for the IP
  4. Limit Check: Current count is compared against configured limit
  5. Response Headers: Rate limit information is added to response
  6. Block/Allow: Request is either allowed or blocked with appropriate headers

Blocking Mechanism

  • Requests exceeding limits are immediately blocked
  • Retry-After header indicates when to retry
  • Configurable block duration support
  • Graceful error responses with rate limit information

Environment Configuration Example

# Throttling Configuration
THROTTLE_ENABLED=true
THROTTLE_TTL=60
THROTTLE_LIMIT=250

# Redis Configuration
REDIS_URL=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your-password
REDIS_USERNAME=default
REDIS_DATABASE=0
REDIS_TTL=120

TypeScript Integration

Full TypeScript support with strict typing:

import { IThrottler } from '@hsuite/throttler-types';

// Type-safe configuration
const throttlerConfig: IThrottler.IOptions = {
  enabled: true,
  storage: IThrottler.IStorage.REDIS,
  settings: {
    ttl: 60,
    limit: 100
  },
  redis: {
    socket: { host: 'localhost', port: 6379 }
  }
};

// Factory pattern support
class ThrottlerConfigFactory implements IThrottler.IOptionsFactory {
  createThrottlerOptions(): IThrottler.IOptions {
    return throttlerConfig;
  }
}

Best Practices

  1. Storage Selection:

    • Use Redis storage for production and distributed systems
    • Use in-memory storage for development and single-instance applications
  2. Rate Limit Configuration:

    • Set appropriate limits based on endpoint resource usage and expected traffic
    • Consider different limits for different types of endpoints
    • Monitor and adjust limits based on actual usage patterns
  3. Redis Configuration:

    • Use connection pooling for high-traffic applications
    • Configure appropriate TTL values for Redis keys
    • Use Redis clustering for high availability
  4. Error Handling:

    • Implement proper error handling for rate limit exceptions
    • Provide clear feedback to clients when limits are exceeded
    • Log rate limiting events for monitoring and analysis
  5. Security Considerations:

    • Consider using authenticated rate limiting for different user tiers
    • Implement IP whitelisting for trusted sources
    • Monitor for potential abuse patterns

Documentation

Generate comprehensive API documentation using Compodoc:

# Generate and serve documentation
npm run compodoc

# Generate documentation with coverage report
npm run compodoc:coverage

The documentation will be available at http://localhost:8080 and includes:

  • Complete API reference
  • Code coverage reports
  • Interactive component documentation
  • Usage examples and guides

Version History

Current version: 2.0.9

See CHANGELOG.md for detailed version history and updates.

License

This project is licensed under the terms of the license provided by HSuite.

Support

For support and questions, please refer to the HSuite documentation or contact the support team.