HbarSuite Docs
  • Welcome to HbarSuite
  • HbarSuite Developer Documentation
    • HbarSuite Smart Engine Applications
      • @hsuite/cross-chain-exchange
      • @hsuite/dao
      • @hsuite/exchange
      • @hsuite/launchpad
      • @hsuite/multisig
      • @hsuite/nft-exchange
    • HSuite Libraries
      • @hsuite/api-key
      • @hsuite/auth-types
      • @hsuite/auth
      • @hsuite/client-types
      • @hsuite/client
      • @hsuite/dkg-types
      • @hsuite/hashgraph-types
      • @hsuite/health
      • @hsuite/helpers
      • @hsuite/ipfs
      • @hsuite/smart-config
      • @hsuite/smart-network-types
      • @hsuite/smart-transaction-types
      • @hsuite/smartnode-sdk
      • @hsuite/snapshots
      • @hsuite/subscriptions-types
      • @hsuite/subscriptions
      • @hsuite/throttler-types
      • @hsuite/throttler
      • @hsuite/users-types
      • @hsuite/users
      • @hsuite/validators-types
  • General Documentation
    • Tokenomics
      • Tokenomics v1
      • Tokenomics V2
    • Smart Apps and Interaction
      • Subscription-Based Model
      • Token-Gate Model
    • The Smart Node Network
      • security-layer
        • Security Layer Integration
        • Setting Up Secure Clusters
        • Generating and Sharing Keys Collaboratively
        • Protecting Secrets with Shamir's Method
        • Managing Cluster Membership
        • Handling Node Expulsion and Replacement
        • Automating Responses to Network Changes & Key Rotation
        • Ensuring Continuous Operation and Recovery
      • Understanding Validators in Our System
        • Type of Validators Explained
    • What is a Smart Node?
  • Restful APIs Documentation
Powered by GitBook
On this page
  • Features
  • Installation
  • Peer Dependencies
  • Quick Start
  • Basic Module Setup
  • Using Redis Storage
  • Protecting Routes
  • Configuration Options
  • Module Options
  • ThrottlerSettings
  • Response Headers
  • Advanced Usage
  • Custom Request Handling
  • Service Integration
  • Best Practices
  • Contributing
  • License
  • Support
  1. HbarSuite Developer Documentation
  2. HSuite Libraries

@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.

Previous@hsuite/throttler-typesNext@hsuite/users-types

Last updated 3 months ago