Skip to content

Rate Limiting

Azizul Hakim edited this page Nov 2, 2024 · 5 revisions

Overview

The nestjs-xsecurity module implements a token-based rate limiting system that protects your API from abuse by limiting the number of failed authentication attempts from a single IP address.

How It Works

graph TD
    A[Request] --> B{Check IP in Store}
    B -->|Not Found| C[Process Request]
    B -->|Found| D{Check Attempt Count}
    D -->|Under Limit| C
    D -->|Over Limit| E{Check Reset Time}
    E -->|Not Expired| F[Rate Limited]
    E -->|Expired| G[Clear Rate Limit]
    G --> C
    C -->|Success| H[Clear Rate Limit]
    C -->|Failure| I[Increment Counter]
Loading

Configuration

Basic Configuration

XSecurityModule.register({
  rateLimit: {
    enabled: true,        // default true
    maxAttempts: 5,       // Maximum failed attempts
    decayMinutes: 1,      // Time before rate limit reset
    cleanupInterval: 5,   // Store cleanup interval
    storeLimit: 10000,    // Maximum number of entries in rate limit store
  }
});

Configuration Options

Option Type Default Description
enabled boolean true Enable/Disable rate limiting
maxAttempts number 5 Maximum number of failed attempts before rate limiting
decayMinutes number 1 Time in minutes before rate limit reset
cleanupInterval number 5 Cleanup interval in minutes for rate limit store
storeLimit number 10000 Maximum number of entries in rate limit store

Performance Considerations

  1. Memory Usage

    • Each rate limit entry uses approximately:
      • IP address string (variable)
      • Two numbers (16 bytes)
    • Total memory = entries × (IP length + 16 bytes)
  2. Cleanup Impact

    • More frequent cleanup = Lower memory usage
    • More frequent cleanup = Higher CPU usage
  3. Scaling

    • In-memory store limits horizontal scaling
    • Built-in limit store is good for small or medium apps
    • Redis support incoming

Related Topics