Generate Rate Limiting Test Scenarios for an API
Returns rate-limiting test cases verifying X-RateLimit-* headers, behavior at the limit boundary, burst handling, reset window semantics, per-authentication-level limits, and concurrent request behavior across multiple workers.
When to use it
- Verifying a newly implemented rate limiter.
- Auditing existing rate limits after a denial-of-service incident.
- Documenting rate limit behavior for API consumers (rate limit page).
- Validating that public, authenticated, and admin tiers have correctly differentiated limits.
The prompt
<role>You are an API testing specialist. You know that 'rate limiting works' is meaningless: you have to verify SPECIFIC behaviors: header semantics, boundary precision, concurrency handling, reset rules.</role> <context>Common rate-limit algorithms: fixed window, sliding window, token bucket, leaky bucket. Each has different boundary behavior and burst characteristics. Headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset (or Retry-After on 429). Limits often differ per auth tier (anonymous / authenticated / admin / partner).</context> <task>For the endpoint and limit configuration below, generate:1. Header validation tests: X-RateLimit-* headers present and accurate2. Boundary behavior tests: exact request count where 429 starts3. Burst handling tests: N requests in 1 second4. Reset semantics tests: request after window expiry5. Per-auth-level tests: anon / authenticated / admin limits differ6. Concurrency tests: N parallel requests at boundary</task> <input>Endpoint: {endpoint}Limit configuration (limit + window + algorithm): {config}Auth tiers and their limits: {tiers}</input> <constraints>- Each test specifies: name, request count + timing, expected status, expected headers.- Boundary tests target EXACT counts (e.g., request 100 of 100 = 200; request 101 = 429).- Burst tests differ from boundary tests: burst is "many requests fast", boundary is "exactly at the limit".- Concurrency tests must verify the limiter is correct under parallel load (some implementations are off-by-N).- Include at least one negative test where bypassing is attempted (varying User-Agent, IP spoofing if possible).</constraints> <output_format>Three sections:1. **Test scenarios table**: Scenario | Setup | Request pattern | Expected status | Expected headers | Notes2. **Implementation sketch**: pseudocode for the most complex scenario (concurrency test)3. **Documentation snippet**: text suitable for an API docs "Rate Limits" section</output_format> <approach>Before writing, identify which algorithm the config implies (fixed window vs sliding vs token bucket).</approach>## RoleAPI testing specialist. 'Rate limiting works' is meaningless: verify SPECIFIC behaviors. ## ContextAlgorithms: fixed window, sliding window, token bucket, leaky bucket. Headers: X-RateLimit-Limit/Remaining/Reset or Retry-After on 429. Per-auth tiers (anon / authenticated / admin / partner). ## Task1. Header validation tests.2. Boundary behavior tests (exact count).3. Burst handling tests (N reqs in 1s).4. Reset semantics tests (after window expiry).5. Per-auth-level tests.6. Concurrency tests (parallel reqs at boundary). ## Input- Endpoint: {endpoint}- Limit config (limit + window + algorithm): {config}- Auth tiers and limits: {tiers} ## Constraints- Each test: name, request count + timing, expected status, expected headers.- Boundary tests = EXACT counts.- Burst ≠ boundary.- Concurrency tests verify under parallel load.- Include 1 negative test (bypass attempt). ## Output format3 sections: Test scenarios table | Implementation sketch for concurrency test | Documentation snippet. ## ApproachIdentify the algorithm from config first.Example
Input
Endpoint: POST /api/orders Limit configuration: 100 requests per minute per API key (token bucket with burst of 20) Auth tiers: - Anonymous: 5 req/min - Authenticated: 100 req/min - Partner: 1000 req/min
Output
## 1. Test scenarios table
| Scenario | Setup | Request pattern | Expected status | Expected headers | Notes |
|----------|-------|-----------------|-----------------|------------------|-------|
| Header presence on success | Authenticated user | Single request to /api/orders | 200 | X-RateLimit-Limit: 100, X-RateLimit-Remaining: 99, X-RateLimit-Reset: <epoch> | Validates header schema |
| Header decrement | Authenticated user | 3 sequential requests | 200, 200, 200 | Remaining: 99 → 98 → 97 | Monotonic decrement |
| Boundary: 100th request | Authenticated user, fresh window | Request #100 within 1 min | 200 | Remaining: 0 | Last allowed request |
| Boundary: 101st request | Authenticated user, fresh window | Request #101 within 1 min | 429 | Retry-After: <seconds>, X-RateLimit-Limit: 100, Remaining: 0 | First blocked request |
| Burst: 20 simultaneous | Authenticated user (token bucket allows burst of 20) | 20 parallel requests | All 200 | Remaining: 80 after burst | Validates burst bucket |
| Burst: 21 simultaneous | Authenticated user | 21 parallel requests | 20 × 200, 1 × 429 | Mixed | Bucket overflows |
| Reset after window | Authenticated user, after hitting 429 | Wait until Retry-After + 1s, send 1 request | 200 | Remaining: 99 (or 100, depends on algorithm) | Window resets correctly |
| Anonymous limit | No auth header | 6 requests in 1 min | 5 × 200, 1 × 429 | Limit: 5 in headers | Per-auth-tier differentiation |
| Partner limit | Partner API key | 1001 requests in 1 min | 1000 × 200, 1 × 429 | Limit: 1000 in headers | Partner tier verified |
| Cross-tier isolation | User A (auth) + User B (anon) on same IP | A: 100 reqs, B: 5 reqs in same minute | All succeed; both at their limit | Limits independent per identity, not per IP | Validates limiter keying |
| Concurrent at boundary | 50 parallel workers, each sending until limit | All workers reach own boundary | Total requests = 100 across workers, then 429s | Limiter is correct under parallelism (no off-by-N) | Most algorithms have off-by-1 here |
| Bypass attempt: vary User-Agent | Authenticated user | 100 requests with random UA per request | After 100, returns 429 regardless of UA | UA does not factor into rate-limit keying | Negative test |
| Bypass attempt: IP rotation | Same API key, rotating Forwarded-For headers | After 100 requests, 429 regardless of Forwarded-For | Server uses API key for keying, not Forwarded-For | Validates server-side identity |
| 429 includes well-formed Retry-After | Hit limit | Send 101st request, inspect headers | 429 with Retry-After: <integer seconds 1-60> | Integer Retry-After, not date | Standard compliance |
## 2. Implementation sketch (concurrency test)
```typescript
import { test, expect } from '@playwright/test';
test('rate limiter is correct under 50 parallel workers', async ({ playwright }) => {
const api = await playwright.request.newContext({
baseURL: 'https://api.staging.example.com',
extraHTTPHeaders: { Authorization: `Bearer ${process.env.TEST_BEARER}` },
});
// Reset window: assume the test starts in a fresh minute window
// 50 workers × 3 requests each = 150 total attempts, limit is 100
const workerCount = 50;
const reqsPerWorker = 3;
const workerResults = await Promise.all(
Array.from({ length: workerCount }, async () => {
const statuses: number[] = [];
for (let i = 0; i < reqsPerWorker; i++) {
const res = await api.post('/api/orders', {
data: { /* minimal valid body */ },
});
statuses.push(res.status());
}
return statuses;
}),
);
const allStatuses = workerResults.flat();
const successes = allStatuses.filter((s) => s === 200).length;
const rateLimited = allStatuses.filter((s) => s === 429).length;
// Expectation: exactly 100 successes (the limit); 50 × 3 - 100 = 50 should be 429
expect(successes).toBe(100);
expect(rateLimited).toBe(50);
// No status other than 200 or 429
expect(allStatuses.every((s) => s === 200 || s === 429)).toBe(true);
await api.dispose();
});
```
## 3. Documentation snippet
```
## Rate Limits
The API enforces rate limits to protect availability for all consumers:
| Tier | Limit | Burst |
|------|-------|-------|
| Anonymous | 5 requests per minute | 5 |
| Authenticated | 100 requests per minute | 20 |
| Partner | 1000 requests per minute | 100 |
### Response headers
Every API response includes:
- `X-RateLimit-Limit`: your tier's limit
- `X-RateLimit-Remaining`: requests remaining in the current window
- `X-RateLimit-Reset`: epoch seconds when the window resets
When the limit is exceeded, the API returns `429 Too Many Requests` with a `Retry-After` header indicating seconds to wait before retrying.
### Bursting
Authenticated users can send up to 20 requests in a 1-second burst before triggering the per-minute limit. Limits are token-bucket-based, so burst capacity refills over time.
### Identification
Rate limits are applied per API key (for authenticated and partner tiers) or per IP address (for anonymous). IP-only identification does not apply to authenticated requests.
```Common pitfalls
- Model conflates boundary and burst: they're different tests. Force separate scenarios.
- Concurrency test gets omitted; that's where most limiters break. Always include.
- Per-tier tests get glossed if input is single-tier; if your API only has one auth level, ASK for the planned tiers and test them.
- Bypass tests treated as 'attempts to attack' instead of validation of identity keying. Frame as 'verify identification is correct'.
Tips
- Run concurrency test in CI weekly; race conditions in limiters often surface only at scale.
- Use real-clock waits for reset semantics: mocking time often hides real bugs.
- Validate Retry-After is a SMALL integer, not 0 or huge. Some limiters return 0 (meaning 'retry immediately') incorrectly.
- Pair with `auth-bypass-test-cases`: rate limiting often a defense against credential stuffing.
FAQ
429 vs 503: when to use which?
429 = identified consumer is over their limit (specific to identity). 503 = server overloaded for everyone. They have different meanings to consumers. Use 429 for rate limits, 503 for capacity issues.
Leaky bucket vs token bucket: what's the difference?
Token bucket allows bursts up to bucket size, then drains at the configured rate. Leaky bucket smooths bursts to a constant rate. Token bucket is more permissive; most API gateways use it.
What about distributed rate-limiter race conditions?
Distributed limiters using Redis or similar often have off-by-N errors at high concurrency. Test specifically by running 100+ parallel workers against the limit boundary: surface 'should fail' vs 'did fail' delta.
Should I test rate limits in production?
Only in synthetic test paths designed for it. Real-traffic limits should be tested in staging with realistic traffic patterns. Production rate-limit testing risks impacting real customers.