8. Handling Rate Limit Exceeded (429 Too Many Requests)
Example: Respond with 429 Too Many Requests
res.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());res.setContentType("application/problem+json");res.getWriter().write(""" {"type":"https://example.com/rate-limit","title":"Too Many Requests","status":429} """);
9. Implementing Sliding Window Algorithm
Algorithm
Pros / Cons
Fixed window
Simple; burst at edges
Sliding log
Precise; high memory
Sliding window counter
Approximate; low memory (good default)
Token bucket
Allows bursts up to capacity
Leaky bucket
Smooth output rate
10. Testing Rate Limiting Logic
Example: Test rate limit exceeded
@Test void exceedsLimit() throws Exception { for (int i = 0; i < 100; i++) mvc.perform(get("/api/data")).andExpect(status().isOk()); mvc.perform(get("/api/data")) .andExpect(status().isTooManyRequests()) .andExpect(header().exists("Retry-After"));}