grapsus-proxy 0.5.12

A security-first reverse proxy built on Pingora with sleepable ops at the edge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# Rate Limiting & Circuit Breakers

Request rate limiting and failure isolation mechanisms.

## Rate Limiting Overview

Grapsus provides multiple rate limiting backends:

| Backend | Use Case | Consistency | Performance |
|---------|----------|-------------|-------------|
| Local | Single instance | Per-instance | Fastest |
| Redis | Multi-instance | Strong | Fast |
| Memcached | Multi-instance | Eventual | Fast |

## Local Rate Limiting

In-memory token bucket rate limiting using Pingora's `pingora-limits` crate.

### Configuration

```kdl
routes {
    route "api" {
        matches {
            path-prefix "/api"
        }
        upstream "backend"

        policies {
            rate-limit {
                requests-per-second 100
                burst 20
                key "client-ip"
                on-limit "reject"
                status-code 429
            }
        }
    }
}
```

### Rate Limit Keys

| Key Type | Description | Example |
|----------|-------------|---------|
| `client-ip` | Client IP address (default) | `192.168.1.100` |
| `header` | Specific header value | `X-API-Key: abc123` |
| `path` | Request path | `/api/v1/users` |
| `route` | Route ID | `api` |
| `composite` | Multiple keys combined | `ip:header:path` |

```kdl
policies {
    rate-limit {
        // Rate limit by API key
        key "header" "X-API-Key"
    }
}

policies {
    rate-limit {
        // Rate limit by client IP + path
        key "composite" ["client-ip", "path"]
    }
}
```

### Algorithm

Token bucket with 1-second sliding window:

```
┌────────────────────────────────────────────────────────┐
│                   Token Bucket                          │
├────────────────────────────────────────────────────────┤
│                                                         │
│   Capacity: 100 tokens (requests-per-second)           │
│   Burst: 20 tokens (additional capacity)               │
│                                                         │
│   ┌─────────────────────────────────┐                  │
│   │ ●●●●●●●●●●●●●●●●●●●●●●●●●●●●●● │ ← Tokens          │
│   │ ●●●●●●●●●●●●●●●●●●●●●●●●●●●●●● │                   │
│   │ ●●●●●●●●●●●●●●●●●●●●●●●●●●●●●● │                   │
│   │ ●●●●●●●●●●                     │ ← Available: 80   │
│   └─────────────────────────────────┘                  │
│                                                         │
│   Request arrives:                                      │
│   - If tokens available → Allow, consume 1 token       │
│   - If no tokens → Reject with 429                     │
│                                                         │
│   Refill rate: 100 tokens/second                       │
│                                                         │
└────────────────────────────────────────────────────────┘
```

### Response Headers

When rate limited:

```http
HTTP/1.1 429 Too Many Requests
Retry-After: 1
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1705123456
Content-Type: application/json

{
  "error": "rate_limited",
  "message": "Too many requests",
  "retry_after": 1
}
```

## Distributed Rate Limiting (Redis)

Redis-backed sliding window rate limiting for multi-instance deployments.

### Prerequisites

Enable the feature:

```toml
[features]
distributed-rate-limit = ["redis", "deadpool-redis"]
```

### Configuration

```kdl
rate-limit-backend {
    type "redis"
    address "redis://localhost:6379"
    pool-size 10
    connection-timeout-ms 1000
}

routes {
    route "api" {
        policies {
            rate-limit {
                requests-per-second 100
                burst 20
                backend "distributed"
            }
        }
    }
}
```

### Algorithm

Sliding window log using Redis sorted sets:

```
┌────────────────────────────────────────────────────────┐
│              Redis Sliding Window                       │
├────────────────────────────────────────────────────────┤
│                                                         │
│   Key: "ratelimit:api:192.168.1.100"                   │
│   Type: Sorted Set                                      │
│                                                         │
│   ┌─────────────────────────────────────────────────┐  │
│   │  Timestamp (score)  │  Request ID (member)      │  │
│   ├─────────────────────┼───────────────────────────┤  │
│   │  1705123456.001     │  req_abc123               │  │
│   │  1705123456.015     │  req_def456               │  │
│   │  1705123456.032     │  req_ghi789               │  │
│   │  ...                │  ...                      │  │
│   └─────────────────────┴───────────────────────────┘  │
│                                                         │
│   On request:                                           │
│   1. ZREMRANGEBYSCORE - Remove entries > 1 sec old     │
│   2. ZCARD - Count remaining entries                   │
│   3. If count < limit → ZADD timestamp, return ALLOW   │
│   4. If count >= limit → return REJECT                 │
│                                                         │
│   All in single MULTI/EXEC transaction                 │
│                                                         │
└────────────────────────────────────────────────────────┘
```

### Fallback

On Redis error, falls back to local rate limiting:

```rust
match redis_limiter.check(key, max_rps).await {
    Ok(result) => result,
    Err(e) => {
        log::warn!("Redis rate limit failed, using local: {}", e);
        local_limiter.check(key, max_rps)
    }
}
```

## Distributed Rate Limiting (Memcached)

Memcached-backed fixed window rate limiting.

### Prerequisites

Enable the feature:

```toml
[features]
distributed-rate-limit-memcached = ["memcached-rs"]
```

### Configuration

```kdl
rate-limit-backend {
    type "memcached"
    addresses ["memcached1:11211", "memcached2:11211"]
    pool-size 10
}
```

### Algorithm

Fixed window counter:

```
┌────────────────────────────────────────────────────────┐
│              Memcached Fixed Window                     │
├────────────────────────────────────────────────────────┤
│                                                         │
│   Key: "ratelimit:api:192.168.1.100:1705123456"        │
│   Value: Counter (integer)                              │
│   TTL: 1 second                                         │
│                                                         │
│   On request:                                           │
│   1. INCR key                                           │
│   2. If key not exists → SET key 1 with TTL            │
│   3. If count <= limit → ALLOW                         │
│   4. If count > limit → REJECT                         │
│                                                         │
│   Window resets every second (key expires)             │
│                                                         │
└────────────────────────────────────────────────────────┘
```

## Scoped Rate Limiting

Hierarchical rate limits with inheritance.

### Scope Hierarchy

```
┌─────────────────────────────────────────────────────────┐
│                    Scope Hierarchy                       │
├─────────────────────────────────────────────────────────┤
│                                                          │
│   Global (default: 10000 rps)                           │
│       │                                                  │
│       ├── Namespace: production (5000 rps)              │
│       │       │                                          │
│       │       ├── Service: api (1000 rps)               │
│       │       │       └── Route: /users (100 rps)       │
│       │       │                                          │
│       │       └── Service: web (2000 rps)               │
│       │                                                  │
│       └── Namespace: staging (1000 rps)                 │
│               │                                          │
│               └── Service: api (500 rps)                │
│                                                          │
│   Inheritance: Most specific limit applies              │
│   Fallback: Service → Namespace → Global                │
│                                                          │
└─────────────────────────────────────────────────────────┘
```

### Configuration

```kdl
scopes {
    scope "production" {
        rate-limit {
            requests-per-second 5000
        }

        scope "api" {
            rate-limit {
                requests-per-second 1000
            }
        }

        scope "web" {
            rate-limit {
                requests-per-second 2000
            }
        }
    }

    scope "staging" {
        rate-limit {
            requests-per-second 1000
        }
    }
}
```

## Circuit Breakers

Failure isolation to prevent cascade failures.

### States

```
┌────────────────────────────────────────────────────────┐
│                 Circuit Breaker FSM                     │
├────────────────────────────────────────────────────────┤
│                                                         │
│      ┌──────────────────────────────────────────┐      │
│      │                                          │      │
│      ▼                                          │      │
│  ┌────────┐                              ┌────────┐   │
│  │ CLOSED │─── failures >= threshold ───▶│  OPEN  │   │
│  │        │                              │        │   │
│  │ Normal │                              │ Reject │   │
│  │ traffic│                              │  all   │   │
│  └────────┘                              └────────┘   │
│      ▲                                       │        │
│      │                                       │        │
│      │                              timeout  │        │
│      │                                       ▼        │
│      │                               ┌────────────┐   │
│      │                               │ HALF-OPEN  │   │
│      │                               │            │   │
│      │                               │   Test     │   │
│      │                               │  traffic   │   │
│      │                               └────────────┘   │
│      │                                       │        │
│      │                          ┌────────────┴───┐    │
│      │                          │                │    │
│      │                       success          failure │
│      │                      threshold           │     │
│      │                          │               │     │
│      └──────────────────────────┘               │     │
│                                                 │     │
│                          Back to OPEN ◀─────────┘     │
│                                                       │
└───────────────────────────────────────────────────────┘
```

### Configuration

```kdl
upstreams {
    upstream "backend" {
        target "10.0.0.1:8080"
        target "10.0.0.2:8080"

        circuit-breaker {
            // Consecutive failures to open circuit
            failure-threshold 5

            // Consecutive successes to close circuit
            success-threshold 2

            // Time in open state before half-open
            timeout-secs 30

            // What counts as failure
            failure-statuses [500, 502, 503, 504]
            failure-on-timeout true
        }
    }
}
```

### Per-Scope Circuit Breakers

Different circuit breaker settings per scope:

```kdl
scopes {
    scope "production" {
        circuit-breaker {
            failure-threshold 10
            timeout-secs 60
        }
    }

    scope "staging" {
        circuit-breaker {
            failure-threshold 3
            timeout-secs 10
        }
    }
}
```

### Response When Open

```http
HTTP/1.1 503 Service Unavailable
Retry-After: 30
Content-Type: application/json

{
  "error": "circuit_open",
  "message": "Service temporarily unavailable",
  "upstream": "backend",
  "retry_after": 30
}
```

## Metrics

### Rate Limiting Metrics

```
# Request counts
grapsus_rate_limit_allowed_total{route="api", key="client-ip"} 100000
grapsus_rate_limit_limited_total{route="api", key="client-ip"} 500

# Current state
grapsus_rate_limit_current_requests{route="api"} 75

# Backend health (for distributed)
grapsus_rate_limit_backend_errors_total{backend="redis"} 5
grapsus_rate_limit_backend_latency_ms{backend="redis", quantile="0.99"} 2.5
```

### Circuit Breaker Metrics

```
# State (0=closed, 1=open, 2=half-open)
grapsus_circuit_breaker_state{upstream="backend", scope="production"} 0

# Transitions
grapsus_circuit_breaker_opens_total{upstream="backend"} 3
grapsus_circuit_breaker_closes_total{upstream="backend"} 2

# Current counts
grapsus_circuit_breaker_failures{upstream="backend"} 2
grapsus_circuit_breaker_successes{upstream="backend"} 5
```

## Best Practices

### 1. Layer Rate Limits

Apply rate limits at multiple levels:

```kdl
// Global rate limit
limits {
    max-requests-per-second 10000
}

// Per-namespace
scopes {
    scope "production" {
        rate-limit {
            requests-per-second 5000
        }
    }
}

// Per-route
routes {
    route "expensive-api" {
        policies {
            rate-limit {
                requests-per-second 100
            }
        }
    }
}
```

### 2. Use Appropriate Keys

Choose rate limit keys based on use case:

```kdl
// Public API - limit by client IP
route "public-api" {
    policies {
        rate-limit {
            key "client-ip"
        }
    }
}

// Authenticated API - limit by API key
route "authenticated-api" {
    policies {
        rate-limit {
            key "header" "Authorization"
        }
    }
}

// Premium tier - higher limits
route "premium-api" {
    policies {
        rate-limit {
            key "header" "X-API-Tier"
            // Different limits based on tier value
        }
    }
}
```

### 3. Set Reasonable Bursts

Allow some burst capacity for legitimate traffic spikes:

```kdl
policies {
    rate-limit {
        requests-per-second 100
        burst 20  // 20% burst capacity
    }
}
```

### 4. Configure Circuit Breakers Conservatively

Avoid false positives with appropriate thresholds:

```kdl
circuit-breaker {
    // Require multiple failures before opening
    failure-threshold 5

    // Give service time to recover
    timeout-secs 30

    // Require multiple successes before closing
    success-threshold 2

    // Only count real errors
    failure-statuses [502, 503, 504]
    // Don't count 500 (app errors) or 429 (rate limited)
}
```

### 5. Monitor and Alert

Set up alerts on rate limiting and circuit breaker events:

```yaml
# Example Prometheus alerting rules
groups:
  - name: rate_limiting
    rules:
      - alert: HighRateLimitRejections
        expr: rate(grapsus_rate_limit_limited_total[5m]) > 100
        for: 5m
        annotations:
          summary: "High rate limit rejections"

      - alert: CircuitBreakerOpen
        expr: grapsus_circuit_breaker_state == 1
        for: 1m
        annotations:
          summary: "Circuit breaker open"
```

## Comparison with Other Proxies

| Feature | Grapsus | Nginx | Envoy | HAProxy |
|---------|----------|-------|-------|---------|
| Local rate limit | Yes | Yes | Yes | Yes |
| Distributed (Redis) | Yes | No | Yes | No |
| Token bucket | Yes | Yes | Yes | Yes |
| Sliding window | Yes | No | Yes | No |
| Scoped limits | Yes | No | Partial | No |
| Circuit breaker | Yes | No | Yes | No |
| Per-agent isolation | Yes | N/A | No | N/A |