API throttling with custom Redis-based limiter

8246
0

While Rack::Attack handles basic rate limiting, custom throttling logic gives fine-grained control over quotas, burst allowances, and per-feature limits. I implement a token bucket algorithm in Redis using sorted sets to track request timestamps per user/IP. Each request checks if the bucket has capacity and adds a timestamp; old timestamps beyond the window are pruned. This approach supports burst tolerance—users can make several requests rapidly as long as their average rate stays within limits. I expose remaining quota and reset time in response headers (X-RateLimit-Remaining, X-RateLimit-Reset) so clients can self-regulate. Different endpoints or subscription tiers get different bucket sizes.