Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 61

    Rate Limiting

    Rate limiting caps how many Orders requests a client may send in a window.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Rate limiting caps how many Orders requests a client may send in a window. Without it, a buggy mobile retry loop or a scraper's flood can starve checkout for everyone else.

    Prefer the edge: Spring Cloud Gateway, an API gateway, or a CDN. When you must protect a single Boot 3 service, use an in-app token bucket (Bucket4j + Redis) keyed by API key, principal, or IP.

    On Java 21 / Boot 3, keep the limiter non-blocking where possible, return 429 Too Many Requests with Retry-After, and never put credentials in the rate-limit key material beyond opaque ids.

    This lesson places TechLearningPRO Orders behind fair-use limits so security and observability lessons later see a healthy traffic shape.

    Purpose of this lesson

    Protect Orders with token-bucket rate limits at the gateway or in-app, returning 429 with Retry-After under Boot 3.

    Understanding the topic

    Allow N tokens per window; reject when the bucket is empty.

    • Token bucket: refill at a steady rate; burst up to capacity.
    • Key: API key, user id, tenant, or IP — never raw passwords.
    • Where: gateway first; filter/interceptor as defense in depth.
    • Response: HTTP 429 + Retry-After + problem-details body.
    • Shared state: Redis for multi-instance Orders; local map only for demos.

    Step-by-step explanation

    1. Decide keys (per API key for partners; per authenticated user for checkout).
    2. Configure gateway rate-limiter filters or add a Bucket4j filter in Orders.
    3. On deny, set status 429, Retry-After, and a stable JSON error body.
    4. Load-test with a burst and confirm healthy traffic still succeeds.

    Informative example

    In-app Bucket4j filter (fallback when no gateway). Prefer gateway limits in production.

    java
    @Component
    public class RateLimitFilter extends OncePerRequestFilter {
    private final ProxyManager<String> buckets;
    public RateLimitFilter(ProxyManager<String> buckets) {
    this.buckets = buckets;
    }
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
    throws IOException, ServletException {
    String key = Optional.ofNullable(req.getHeader("X-Api-Key")).orElse(req.getRemoteAddr());
    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);
    return;
    }
    res.setStatus(429);
    res.setHeader("Retry-After", "60");
    res.setContentType("application/json");
    res.getWriter().write("{\"error\":\"rate_limited\"}");
    }
    }

    Real-world use

    TechLearningPRO partner integrations once retried every 50ms on 5xx. Without a shared Redis bucket, three Orders pods each allowed a full local limit — 3× traffic hit Postgres. Centralizing the bucket (and later moving limits to the gateway) restored checkout latency within minutes.

    Security implications

    Rate limits are abuse control, not authentication.

    • Do not log full API keys — hash or truncate identifiers.
    • Combine with auth: unauthenticated routes get stricter quotas.
    • Never embed real partner secrets in sample configs — use placeholders.

    Best practices

    • Limit at the gateway; keep in-app limits as a safety net.
    • Expose remaining quota via response headers when partners need them.
    • Tune separate buckets for auth vs checkout vs public catalog.

    Common mistakes

    • Per-pod in-memory counters that multiply effective quota by replica count.
    • Returning 500 instead of 429 so clients keep hammering.
    • Keying only on IP behind a shared NAT and blocking entire offices.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhy prefer gateway rate limiting?+

    Answer

    One policy for many services, less app CPU, and abuse is stopped before it reaches Orders pods.
    2IntermediateQuestionWhy is Redis important for token buckets in Kubernetes?+

    Answer

    Local maps reset per pod and multiply quotas; Redis shares one counter across replicas.
    3BeginnerQuestionWhat status code signals rate limiting?+

    Answer

    429 Too Many Requests, ideally with Retry-After so clients back off cleanly.

    Hands-on exercise

    Lab. Add a Bucket4j filter with 10 req/min. Hit an Orders GET in a loop; confirm 429 and Retry-After. Then move the same policy to a Gateway RequestRateLimiter sketch and compare where you configure keys.

    Summary

    Rate limiting keeps TechLearningPRO Orders fair under burst and abuse. Next: see what the system is doing with monitoring and logging.

    Ready to mark this lesson complete?Track your journey across the entire course.