Implementing Rate Limiting Logic

1. Implementing Token Bucket Algorithm

PropertyDetail
CapacityMax burst
Refill rateTokens per second
Allow ifTokens ≥ cost; else deny
UsePermits bursts

Example: Bucket4j

Bucket bucket = Bucket.builder()
    .addLimit(Bandwidth.simple(100, Duration.ofMinutes(1)))
    .build();
if (!bucket.tryConsume(1)) throw new TooManyRequestsException();

2. Implementing Leaky Bucket Algorithm

PropertyDetail
QueueFIFO with fixed rate drain
OverflowReject when full
UseSmooths bursts to constant rate

3. Implementing Fixed Window Counter

PropertyDetail
Windowe.g., per-minute counter
ResetAt window boundary
ProSimple, low memory
ConBurst at boundary (2x limit possible)

4. Implementing Sliding Window Log

PropertyDetail
StorageSorted set of timestamps per key
On requestRemove old entries; check size
ProAccurate
ConMemory grows with traffic

5. Implementing Rate Limit Scopes

ScopeKey
Per IPClient IP
Per userAuthenticated user ID
Per API keyAPI key hash
Per tenantTenant ID
Per endpointMethod + path pattern
GlobalService-wide

6. Implementing Rate Limit Storage

BackendUse
In-memory (Caffeine)Single instance
RedisDistributed; INCR + EXPIRE
HazelcastEmbedded distributed
DynamoDBServerless scale

7. Implementing Rate Limit Headers (X-RateLimit-*)

HeaderValue
X-RateLimit-LimitMax in window
X-RateLimit-RemainingRemaining in current window
X-RateLimit-ResetEpoch seconds when window resets
Retry-AfterOn 429: seconds to wait

8. Implementing Rate Limit Exceeded Handler

Example: 429 response

HTTP/1.1 429 Too Many Requests
Retry-After: 30
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1717000060
Content-Type: application/problem+json

{ "type":"https://api.acme.com/errors/rate-limit",
  "title":"Too many requests","status":429,
  "detail":"Rate limit exceeded; retry after 30s" }

9. Implementing Dynamic Rate Limits

SourceDetail
Per-tier plansFree vs Pro vs Enterprise
Customer overridesPer-account custom limits
AdaptiveTighten under high load
Feature flagToggle limits in real time

10. Implementing Rate Limit Bypass Logic

BypassFor
Internal servicesShared secret / mTLS
Health checksExcluded paths
Premium tierHigher caps
Warning: Audit bypass usage; misconfigurations are a common DoS vector.

11. Implementing Sliding Window Counter

PropertyDetail
ApproachTwo adjacent windows weighted by overlap
ProLess memory than log; smoother than fixed
Trade-offApproximate

12. Implementing Distributed Rate Limiting

Example: Redis token bucket (atomic Lua)

// KEYS[1] = bucket key, ARGV = capacity, refillRate, now, requested
String lua = """
  local tokens = tonumber(redis.call('hget', KEYS[1], 'tokens') or ARGV[1])
  local last   = tonumber(redis.call('hget', KEYS[1], 'last')   or ARGV[3])
  local delta  = math.max(0, ARGV[3] - last) * ARGV[2]
  tokens = math.min(ARGV[1], tokens + delta)
  if tokens < ARGV[4] then return 0 end
  tokens = tokens - ARGV[4]
  redis.call('hset', KEYS[1], 'tokens', tokens, 'last', ARGV[3])
  redis.call('pexpire', KEYS[1], 60000)
  return 1
""";