Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 61
Rate Limiting
Rate limiting protects your service from abuse, runaway clients, and the occasional internal bug-loop.
Course progress0%
Focus
2 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
Rate limiting protects your service from abuse, runaway clients, and the occasional internal bug-loop. The simplest viable algorithm: token bucket in Redis.
Informative example
Bucket4j + Redis (in-app fallback when no gateway):
ts
@Component @RequiredArgsConstructorpublic class RateLimitFilter extends OncePerRequestFilter {private final ProxyManager<String> buckets;protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)throws IOException, ServletException {String key = req.getHeader("X-Api-Key");Bucket bucket = buckets.builder().build(key,() -> BucketConfiguration.builder().addLimit(Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(1)))).build());if (bucket.tryConsume(1)) {chain.doFilter(req, res);} else {res.setStatus(429);res.getWriter().write("{\"error\":\"rate_limited\"}");}}}
Ready to mark this lesson complete?Track your journey across the entire course.