You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Advanced Middleware: Rate Limiting, Caching, and Deduplication
2
+
3
+
As your API grows, you'll need to protect it from abuse and optimize performance. RustAPI provides a suite of advanced middleware in `rustapi-extras` to handle these concerns efficiently.
4
+
5
+
These patterns are essential for the "Enterprise Platform" learning path and high-traffic services.
6
+
7
+
## Prerequisites
8
+
9
+
Add the `rustapi-extras` crate with the necessary features to your `Cargo.toml`.
10
+
11
+
```toml
12
+
[dependencies]
13
+
rustapi-rs = { version = "0.1.335", features = ["full"] }
14
+
# OR cherry-pick features
15
+
# rustapi-extras = { version = "0.1.335", features = ["rate-limit", "dedup", "cache"] }
16
+
```
17
+
18
+
## Rate Limiting
19
+
20
+
Rate limiting protects your API from being overwhelmed by too many requests from a single client. It uses a "Token Bucket" or "Fixed Window" algorithm to enforce limits.
21
+
22
+
### How it works
23
+
The `RateLimitLayer` tracks request counts per IP address. When a limit is exceeded, it returns `429 Too Many Requests` with a `Retry-After` header.
24
+
25
+
### Usage
26
+
27
+
```rust
28
+
userustapi_rs::prelude::*;
29
+
userustapi_extras::rate_limit::RateLimitLayer;
30
+
usestd::time::Duration;
31
+
32
+
fnmain() {
33
+
letapp=RustApi::new()
34
+
.layer(
35
+
RateLimitLayer::new(100, Duration::from_secs(60)) // 100 requests per minute
36
+
)
37
+
.route("/", get(handler));
38
+
39
+
// ... run app
40
+
}
41
+
```
42
+
43
+
The middleware automatically adds standard headers to responses:
44
+
-`X-RateLimit-Limit`: The maximum number of requests allowed.
45
+
-`X-RateLimit-Remaining`: The number of requests remaining in the current window.
46
+
-`X-RateLimit-Reset`: The timestamp when the window resets.
47
+
48
+
## Request Deduplication
49
+
50
+
In distributed systems, clients may retry requests that have already been processed (e.g., due to network timeouts). Deduplication ensures that non-idempotent operations (like payments) are processed only once.
51
+
52
+
### How it works
53
+
The `DedupLayer` checks for an `Idempotency-Key` header. If a request with the same key is seen within the TTL window, it returns `409 Conflict`.
54
+
55
+
### Usage
56
+
57
+
```rust
58
+
userustapi_rs::prelude::*;
59
+
userustapi_extras::dedup::DedupLayer;
60
+
usestd::time::Duration;
61
+
62
+
fnmain() {
63
+
letapp=RustApi::new()
64
+
.layer(
65
+
DedupLayer::new()
66
+
.header_name("X-Idempotency-Key") // Optional: Custom header name
67
+
.ttl(Duration::from_secs(300)) // 5 minutes TTL
68
+
)
69
+
.route("/payments", post(payment_handler));
70
+
71
+
// ... run app
72
+
}
73
+
```
74
+
75
+
Clients should generate a unique UUID for each operation and send it in the `Idempotency-Key` header.
76
+
77
+
## Response Caching
78
+
79
+
Caching can significantly reduce load on your servers by serving stored responses for identical requests.
80
+
81
+
### How it works
82
+
The `CacheLayer` stores successful responses in memory based on the request method and URI. Subsequent requests are served from the cache until the TTL expires.
83
+
84
+
### Usage
85
+
86
+
```rust
87
+
userustapi_rs::prelude::*;
88
+
userustapi_extras::cache::CacheLayer;
89
+
usestd::time::Duration;
90
+
91
+
fnmain() {
92
+
letapp=RustApi::new()
93
+
.layer(
94
+
CacheLayer::new()
95
+
.ttl(Duration::from_secs(60)) // Cache for 60 seconds
96
+
.add_method("GET") // Cache GET requests
97
+
.add_method("HEAD") // Cache HEAD requests
98
+
)
99
+
.route("/heavy-computation", get(heavy_handler));
100
+
101
+
// ... run app
102
+
}
103
+
```
104
+
105
+
Cached responses include an `X-Cache: HIT` header. Original responses have `X-Cache: MISS`.
106
+
107
+
## Combining Middleware
108
+
109
+
You can combine these layers to create a robust defense-in-depth strategy.
110
+
111
+
```rust
112
+
letapp=RustApi::new()
113
+
// 1. Rate Limit (Outer): Reject excessive traffic first
0 commit comments