@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/throttlerDependencies
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 windowX-RateLimit-Remaining: Remaining requests in current windowX-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 neededRate 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
- Request Received: Guard intercepts incoming request
- IP Extraction: Client IP address is identified and tracked
- Counter Increment: Request counter is incremented for the IP
- Limit Check: Current count is compared against configured limit
- Response Headers: Rate limit information is added to response
- Block/Allow: Request is either allowed or blocked with appropriate headers
Blocking Mechanism
- Requests exceeding limits are immediately blocked
Retry-Afterheader 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=120TypeScript 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
Storage Selection:
- Use Redis storage for production and distributed systems
- Use in-memory storage for development and single-instance applications
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
Redis Configuration:
- Use connection pooling for high-traffic applications
- Configure appropriate TTL values for Redis keys
- Use Redis clustering for high availability
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
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:coverageThe 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.
