Rate Limiting Documentation

This document covers the rate limiting implementation for the Universal Bookshelf platform to prevent abuse and ensure fair usage.

Overview

Rate limiting is a crucial security feature that prevents abuse of the API and web endpoints by limiting the number of requests a user or IP address can make within a specific time period.

Benefits of Rate Limiting

  • Prevents Abuse - Stops malicious users from overwhelming the system
  • Ensures Fair Usage - Gives all users equal access to resources
  • Protects Against Attacks - Mitigates DDoS and brute force attacks
  • Maintains Performance - Keeps the system responsive for legitimate users

Rate Limiting Configuration

Default Limits

The platform implements different rate limits for different types of endpoints:

  • Authentication Endpoints - 5 requests per minute
  • API Endpoints - 60 requests per minute
  • File Uploads - 10 requests per minute
  • Search Endpoints - 30 requests per minute

Configuration File

Rate limiting is configured in app/Http/Kernel.php:

protected $middlewareGroups = [
    'web' => [
        // ... other middleware
        \App\Http\Middleware\ThrottleRequests::class . ':60,1', // 60 requests per minute
    ],
    
    'api' => [
        // ... other middleware
        \App\Http\Middleware\ThrottleRequests::class . ':60,1', // 60 requests per minute
    ],
];

protected $routeMiddleware = [
    // ... other middleware
    'throttle' => \App\Http\Middleware\ThrottleRequests::class,
];

Rate Limiting Headers

When rate limiting is active, the API returns specific headers to inform clients about their usage:

Response Headers

  • X-RateLimit-Limit - Maximum requests allowed in the time window
  • X-RateLimit-Remaining - Number of requests remaining in the current window
  • X-RateLimit-Reset - Unix timestamp when the rate limit resets
  • Retry-After - Number of seconds to wait before retrying (when limit exceeded)

Example Response Headers

HTTP/1.1 200 OK
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1640995200
Content-Type: application/json

Rate Limit Exceeded Response

When a rate limit is exceeded, the API returns a 429 Too Many Requests response:

429 Response Example

HTTP/1.1 429 Too Many Requests
Retry-After: 60
Content-Type: application/json

{
    "status": false,
    "message": "Too many requests. Please try again later.",
    "retry_after": 60,
    "limit": 60,
    "window": "1 minute"
}

Custom Rate Limiting

Route-Specific Limits

You can apply custom rate limits to specific routes:

// In routes/api.php
Route::middleware('throttle:10,1')->group(function () {
    Route::post('/upload', [FileController::class, 'upload']);
    Route::post('/bulk-upload', [FileController::class, 'bulkUpload']);
});

// In routes/web.php
Route::middleware('throttle:5,1')->group(function () {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/signup', [AuthController::class, 'signup']);
});

Dynamic Rate Limiting

Apply different limits based on user authentication status:

Route::middleware('throttle:60,1')->group(function () {
    Route::get('/books', [BookController::class, 'index']);
});

Route::middleware(['auth:api', 'throttle:120,1'])->group(function () {
    Route::post('/books', [BookController::class, 'store']);
    Route::put('/books/{id}', [BookController::class, 'update']);
});

Rate Limiting by User Type

Different Limits for Different Users

Implement different rate limits based on user roles or subscription levels:

// Custom middleware for role-based rate limiting
class RoleBasedThrottle
{
    public function handle($request, Closure $next)
    {
        $user = auth()->user();
        
        if ($user && $user->hasRole('premium')) {
            return $next($request);
        }
        
        if ($user && $user->hasRole('author')) {
            return app(\App\Http\Middleware\ThrottleRequests::class)
                ->handle($request, $next, '120,1'); // 120 requests per minute
        }
        
        return app(\App\Http\Middleware\ThrottleRequests::class)
            ->handle($request, $next, '60,1'); // 60 requests per minute
    }
}

Rate Limiting Storage

Storage Drivers

Rate limiting data can be stored using different drivers:

  • Cache Driver - Uses Laravel's cache system (default)
  • Redis - High-performance in-memory storage
  • Database - Persistent storage for analytics

Redis Configuration

For better performance, configure Redis as the cache driver:

// In .env file
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

// In config/cache.php
'redis' => [
    'driver' => 'redis',
    'connection' => 'cache',
    'lock_connection' => 'default',
],

Monitoring and Analytics

Rate Limit Monitoring

Track rate limit usage and violations:

// Log rate limit violations
Log::warning('Rate limit exceeded', [
    'ip' => request()->ip(),
    'user_id' => auth()->id(),
    'endpoint' => request()->path(),
    'limit' => 60,
    'window' => '1 minute'
]);

// Track usage patterns
Cache::increment("rate_limit:{$ip}:{$endpoint}:hits");
Cache::increment("rate_limit:{$ip}:{$endpoint}:violations");

Analytics Dashboard

Create an admin dashboard to monitor rate limiting:

  • Requests per IP address
  • Rate limit violations
  • Peak usage times
  • User behavior patterns

Best Practices

Rate Limiting Best Practices

  • Set appropriate limits based on endpoint complexity and resource usage
  • Use different limits for authenticated vs unauthenticated users
  • Implement progressive rate limiting for repeated violations
  • Monitor and adjust limits based on actual usage patterns
  • Provide clear error messages when limits are exceeded
  • Consider implementing rate limiting at the load balancer level

Troubleshooting

Common Issues

  • Too Many Requests - Check if rate limits are too restrictive
  • Inconsistent Limits - Verify middleware configuration
  • Performance Issues - Consider using Redis for storage
  • Header Issues - Ensure rate limit headers are properly set

Debugging Commands

Use these commands to debug rate limiting:

# Clear rate limiting cache
php artisan cache:clear

# Check cache configuration
php artisan config:cache

# Monitor Redis (if using Redis)
redis-cli monitor

Need Help?

For additional support or questions about rate limiting, please contact our development team.

Back to Documentation