1
---
2
name: rate-limiting-implementation
3
description: >
4
Implement rate limiting, throttling, API quotas, and backpressure mechanisms
5
to protect services from abuse and ensure fair resource usage. Use when
6
building APIs, preventing DOS attacks, or managing system load.
7
---
8
9
# Rate Limiting Implementation
10
11
## Table of Contents
12
13
- [Overview](#overview)
14
- [When to Use](#when-to-use)
15
- [Quick Start](#quick-start)
16
- [Reference Guides](#reference-guides)
17
- [Best Practices](#best-practices)
18
19
## Overview
20
21
Implement rate limiting and throttling mechanisms to protect your services from abuse, ensure fair resource allocation, and maintain system stability under load.
22
23
## When to Use
24
25
- Protecting public APIs from abuse
26
- Preventing DOS/DDOS attacks
27
- Ensuring fair resource usage across users
28
- Implementing API quotas and billing tiers
29
- Managing system load and backpressure
30
- Enforcing SLA limits
31
- Controlling third-party API usage
32
- Database connection management
33
34
## Quick Start
35
36
Minimal working example:
37
38
```typescript
39
interface TokenBucketConfig {
40
capacity: number;
41
refillRate: number; // tokens per second
42
refillInterval: number; // milliseconds
43
}
44
45
class TokenBucket {
46
private tokens: number;
47
private lastRefill: number;
48
private readonly capacity: number;
49
private readonly refillRate: number;
50
private readonly refillInterval: number;
51
private refillTimer?: NodeJS.Timeout;
52
53
constructor(config: TokenBucketConfig) {
54
this.capacity = config.capacity;
55
this.tokens = config.capacity;
56
this.refillRate = config.refillRate;
57
this.refillInterval = config.refillInterval;
58
this.lastRefill = Date.now();
59
60
this.startRefill();
61
}
62
63
private startRefill(): void {
64
// ... (see reference guides for full implementation)
65
```
66
67
## Reference Guides
68
69
Detailed implementations in the `references/` directory:
70
71
| Guide | Contents |
72
|---|---|
73
| [Token Bucket Algorithm (TypeScript)](references/token-bucket-algorithm-typescript.md) | Token Bucket Algorithm (TypeScript) |
74
| [Redis-Based Distributed Rate Limiter](references/redis-based-distributed-rate-limiter.md) | Redis-Based Distributed Rate Limiter |
75
| [Express Middleware](references/express-middleware.md) | Express Middleware |
76
| [Sliding Window Algorithm (Python)](references/sliding-window-algorithm-python.md) | Sliding Window Algorithm (Python) |
77
| [Tiered Rate Limiting](references/tiered-rate-limiting.md) | Tiered Rate Limiting |
78
| [Adaptive Rate Limiting](references/adaptive-rate-limiting.md) | Adaptive Rate Limiting |
79
80
## Best Practices
81
82
### ✅ DO
83
84
- Use distributed rate limiting for multi-server deployments
85
- Implement multiple rate limit tiers (per second, minute, hour, day)
86
- Return proper HTTP status codes (429 Too Many Requests)
87
- Include Retry-After header in responses
88
- Log rate limit violations for monitoring
89
- Implement graceful degradation
90
- Use Redis or similar for persistence
91
- Consider cost-based rate limiting (expensive operations cost more)
92
- Implement burst allowances for legitimate traffic spikes
93
- Provide clear API documentation about limits
94
95
### ❌ DON'T
96
97
- Store rate limit data in application memory for distributed systems
98
- Use fixed window counters without considering edge cases
99
- Forget to clean up expired data
100
- Block all requests from an IP due to one bad actor
101
- Set limits too restrictive for legitimate use
102
- Ignore the impact of rate limiting on user experience
103
- Fail closed (deny all) when rate limiter fails
104