@hsuite/throttler

A powerful and flexible rate limiting library for NestJS applications, providing robust protection against abuse and ensuring optimal resource utilization.

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

  • 🔌 Easy Integration: Seamless integration with NestJS applications

  • 🎯 Custom Rules: Support for dynamic rate limiting rules

  • 📊 Response Headers: Automatic rate limit information in response headers

Installation

npm install @hsuite/throttler

Peer Dependencies

  • @nestjs/common: ^10.4.2

  • @nestjs/core: ^10.4.2

Quick Start

Basic Module Setup

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

@Module({
  imports: [
    SecurityThrottlerModule.forRootAsync({
      useFactory: () => ({
        enabled: true,
        storage: 'memory', // or 'redis'
        settings: {
          ttl: 60,
          limit: 100
        }
      })
    })
  ]
})
export class AppModule {}

Using Redis Storage

SecurityThrottlerModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: (config: ConfigService) => ({
    enabled: true,
    storage: 'redis',
    settings: {
      ttl: 60,
      limit: 100
    },
    redis: {
      username: 'user',
      password: 'pass',
      socket: {
        host: 'localhost',
        port: 6379
      },
      database: 0
    }
  }),
  inject: [ConfigService]
})

Protecting Routes

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

Module Options

Option
Type
Description

enabled

boolean

Enable/disable throttling

storage

'redis' | 'memory'

Storage backend type

settings

ThrottlerSettings

Rate limiting settings

redis?

RedisOptions

Redis connection options

ThrottlerSettings

Option
Type
Description

ttl

number

Time window in seconds

limit

number

Maximum requests per window

Response Headers

The module automatically sets the following response headers:

  • X-RateLimit-Limit: Maximum requests allowed

  • X-RateLimit-Remaining: Remaining requests in current window

  • X-RateLimit-Reset: Time until window reset (in seconds)

  • Retry-After: When rate limit is exceeded

Advanced Usage

Custom Request Handling

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

@Injectable()
export class MyCustomGuard extends CustomThrottlerGuard {
  async handleCustomRequest(context, limit, ttl) {
    // Custom rate limiting logic
    return super.handleCustomRequest(context, limit, ttl);
  }
}

Service Integration

import { SecurityThrottlerService } from '@hsuite/throttler';
import { Injectable } from '@nestjs/common';

@Injectable()
export class MyService {
  constructor(private throttlerService: SecurityThrottlerService) {}

  async someMethod() {
    // Access throttler service functionality
  }
}

Best Practices

  1. Storage Selection:

    • Use Redis storage for distributed systems

    • Use memory storage for single-instance applications

  2. Rate Limit Configuration:

    • Set appropriate limits based on endpoint resource usage

    • Consider different limits for authenticated vs unauthenticated users

  3. Error Handling:

    • Implement proper error handling for rate limit exceptions

    • Provide clear feedback to clients when limits are exceeded

Contributing

Please read our contributing guidelines before submitting pull requests.

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.


Built with ❤️ by the HbarSuite Team Copyright © 2024 HbarSuite. All rights reserved.

Last updated