Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Spring Boot
  • Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
  • A Plain Spring Project, No Boot: Your First Bean With spring-context
  • Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
  • Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
  • Spring Autowiring: Spring Fills the Constructor, and When @Autowired Is Needed
  • Two Beans, One Type: Spring @Primary and @Qualifier
  • Spring Bean Scopes: Singleton vs Prototype, One Shared Object or a Fresh One
  • Spring Stereotypes: @Service, @Repository and @Controller Are @Component With a Job Name
  • The Spring Bean Lifecycle: @PostConstruct and @PreDestroy
  • The Mini Blog Wired by Spring: Plain Java vs Spring, Side by Side
  • Spring MVC and SQLite Without Spring Boot: the Mini Blog in the Browser
  • Your First Spring Boot 4 Project: Create It in IntelliJ, Run It, and the Four Files That Matter
  • What Is Spring Boot? Spring Framework 7 With the Decisions Already Made
  • The Project Context File: AGENTS.md and CLAUDE.md for a Spring Boot Project
  • Plan Before Code: a Five-Part Brief, Plan Mode and /goal for a Spring Boot Feature
  • From Design Frames to Thymeleaf Pages: Briefing an AI Agent for a Spring Boot Blog
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Profile Page and Photo Upload in Spring Boot: Check the File, Shrink It, Keep Your Own Name
  • Building a Feature With an AI Agent, End to End: Comments on a Spring Boot Blog
  • Containerising Spring Boot: a Layered Dockerfile vs Buildpacks
  • GraalVM Native Image and Spring AOT: When It Pays, and What It Costs
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Scheduled Jobs in Spring Boot: fixedRate, fixedDelay, cron, and ShedLock for Many Instances
  • Redis in Spring Boot: a Cache, a Rate-Limit Counter and a Job Status Hash
  • Actuator and Micrometer in Spring Boot: Health, Your Own Metrics, and the Four Numbers That Matter
  • Structured Logging and Correlation IDs in Spring Boot: JSON Lines, a Filter and the MDC
  • Dashboards and Alerts for a Spring Boot App: Prometheus, Grafana and One Real Incident
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • A GitHub Actions Workflow for a Maven Project: Cache, a Java Matrix and Test Reports That Survive a Red Run
  • The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
  • Attachments in S3 from Spring Boot: Pre-signed Uploads, a 302 to a Pre-signed Download, and Links That Expire
  • CloudWatch for a Spring Boot App: JSON Logs, Micrometer Metrics From Your Own Code, and an Alarm That Reaches a Person
  • Automated Deploy, Smoke Test and Rollback for a Spring Boot App: Green Tests Are Not a Working Deploy
  • Environments, Secrets and Approvals in GitHub Actions: One Image From Staging to Production
  • Distributed Tracing Across Spring Boot Services and Kafka: One Trace ID From the Gateway to the Last Reader, Even Through an Outbox
  • Thymeleaf and htmx in Spring Boot: Live Search and One-Row Updates From Server-Rendered Fragments, With No JavaScript Framework
  • Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
  • Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
  • Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
  • Entities and H2 in Spring Boot: a Post Class Becomes a Table
  • Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
  • Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
  • Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
  • JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table
  • Spring Data Query Methods: Derived Queries, @Query and Projections
  • The N+1 Problem in JPA: Fetch Types, Join Fetch and Entity Graphs
  • Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
  • Flyway Migrations in Spring Boot: Numbered SQL Files, Seed Data and the History Table
  • Spring Data JPA Auditing and Soft Deletes: Who Changed It, When, and Hiding Instead of Deleting
  • Optimistic Locking with @Version: Two Agents, One Ticket, No Lost Update
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • Caching With Spring and Redis: Cache-Aside, a TTL per Kind of Data, Eviction on Edit and Stopping the Stampede
  • A PostgreSQL Read Replica in Spring Boot: Route readOnly Transactions, Size the Pool, Find the Index, Read Your Own Writes
  • A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
  • Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
  • Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
  • Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
  • Fixing the Access Bugs: a Rule per Role and an Ownership Check in Spring Security
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Remember Me and Forgot Password by Email in Spring Boot: a Signed Cookie and a One-Time Link
  • Spring Boot Security Defaults: What One Dependency Gives You for Free
  • The Spring Security Filter Chain and Your Own Rules: 401, 403 and Rule Order
  • Stateless JWT Authentication in Spring Security: Sign Once, Check Every Request
  • Users in the Database with Spring Security: Register, BCrypt and Log In
  • Method Security in Spring: @PreAuthorize, Roles and Who Owns This Ticket
  • CORS and CSRF in Spring Security: Why the Browser Blocks Your SPA, and When CSRF Can Be Off
  • Reviewing AI-Written Spring Code for Security: Four Questions for Every Diff
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • An API Gateway With Spring Cloud Gateway: Check the JWT Once at the Edge, Pass the Caller Inward, and Know What the Network Now Trusts
  • Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
  • Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
  • The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
  • Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
  • Spring Boot Test Slices: @WebMvcTest with MockMvc and @DataJpaTest
  • Integration Tests with Testcontainers: A Real PostgreSQL for Every Spring Boot Test Run
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • Test-First with a Coding Agent: Spec, Red Tests, Then the Code
  • Quality and Security Gates for a Maven Project: JaCoCo Coverage, PMD, an SBOM and a Trivy Scan
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • What Spring AI 2 Is, and Why a Java Team Wants It
  • Spring AI ChatClient: One API for Any Model, and the Model Is a Property
  • Spring AI Prompt Templates: Placeholders, Few-Shot Messages and Versioned Prompt Files
  • Spring AI Structured Output: From Model JSON to a Java Record, and a Real Ticket Triage Feature
  • Streaming Spring AI Answers to the Browser: stream(), a Flux of Server-Sent Events and the Cancel
  • Local Models With Ollama in Spring AI: Profiles, Per-Call Options and What a Smaller Model Costs
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • Embeddings and pgvector in Spring AI: EmbeddingModel, VectorStore, Distance Operators and the HNSW Index
  • RAG Ingestion in Spring AI: Parse Markdown, Chunk by Section, Embed Into pgvector With Stable Ids
  • Tuning Retrieval in Spring AI: Top-k, a Minimum Score, a Tenant Filter Inside the Query, Hybrid Search and a Reranker
  • Tool Calling in Spring AI 2: @Tool Methods, the ToolCallingAdvisor Loop and a Tool-Call Limit
  • Chat Memory in Spring AI: MessageChatMemoryAdvisor, a Conversation Id, a Window, a Summary and Where the State Lives
  • Building an MCP Server in Java With Spring AI: @McpTool, Stateless Streamable HTTP and Least-Privilege Tools
  • Consuming MCP Servers From Spring AI: a stdio Child Process and a Remote Streamable HTTP Server, Compared
  • A Supervisor and Specialist Agents in Spring AI: Own Prompts, Own Tools, Explicit State and a Menu Checked in Code
  • Choosing a JVM Agent Framework: the Same Two-Step Triage in Spring AI, LangChain4j Agentic and Embabel
  • Observability for Spring AI Calls: a Span per Feature, Token and Spend Counters, Jaeger Traces and Two Prometheus Alerts
  • Evals and Cost Control for a Java Subtitle Service: A Golden Set Scored by Word Error Rate in CI, and the Cost of One Hour of Audio From Micrometer Meters
  1. Blog
  2. /
  3. Spring Boot
  4. /
  5. REST APIs

Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work

Three gates in a small Spring Boot service, RateGate. A Bucket4j bucket per tenant and endpoint in Redis lets 5 calls through and answers the rest with 429 and Retry-After: 5. Four workers and a line of eight answer 12 of 20 calls and refuse 8 at once. Shedding AI summaries takes ticket calls from 6% to 100% success under a spike.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026REST APIs

What you will learn

  • Rate limit per tenant and endpoint with a Bucket4j token bucket kept in Redis
  • Answer a refused call with 429 and a Retry-After the client can act on
  • Bound the work queue with a ThreadPoolExecutor and turn a full line into 503 busy
  • Shed low-priority work at the door and measure the effect under a k6 spike

Before you start

  • Spring Boot REST controllers
  • Servlet filters
  • Redis basics

When too much arrives at once, a service can say no early and clearly, or it can say yes and fall over slowly. This article builds three gates into a small Spring Boot service called RateGate: a token bucket per tenant kept in Redis, a bounded line of work, and a rule that drops low-priority work first. Then it measures them under a spike. The idea of a per-team budget, applied to model tokens, is in token rate limits per team.

Every request walks the same path through three gates. The rate limit protects everyone from one noisy tenant and answers 429 Too Many Requests. The load shed protects the workers from low-priority work and answers 503 shed. The worker pool bounds the line and answers 503 busy. What gets through reaches the handler. 1. Rate limitone noisy tenant 2. Load shedlow priority first 3. Worker pool4 workers, line of 8 Handlerwork we can finish 429 + Retry-After 503 shed 503 busy
Three gates, three reasons, and each says no in a way the client can act on.

Gate one: a token bucket per tenant

Think of a ride at a theme park with a basket of five tickets. Five guests walk through. The sixth is told to come back in five seconds, and every five seconds one new ticket drops into the basket. That is a token bucket: a burst up to the capacity, then the refill rate. RateGate uses Bucket4j, with one bucket shape per endpoint:

/** One bucket shape per endpoint. Every tenant gets its own bucket of that shape. */
final class Limits {
    private Limits() {
    }

    static BucketConfiguration forEndpoint(String path) {
        if (path.startsWith("/api/summaries")) {
            // AI summaries are costly: a burst of 2, then one every 10 seconds
            return BucketConfiguration.builder()
                    .addLimit(limit -> limit
                            .capacity(2)
                            .refillGreedy(1, Duration.ofSeconds(10)))
                    .build();
        }
        // ticket reads are cheap: a burst of 5, then one every 5 seconds
        return BucketConfiguration.builder()
                .addLimit(limit -> limit
                        .capacity(5)
                        .refillGreedy(1, Duration.ofSeconds(5)))
                .build();
    }
}

Greedy refill adds tokens a little at a time instead of all at once. The filter that uses it runs first in the chain:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class RateLimitFilter extends OncePerRequestFilter {
    ...
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String tenant = request.getHeader("X-Tenant");
        if (tenant == null) {
            tenant = "anonymous";
        }
        String path = request.getRequestURI();
        String key = "rl:" + tenant + ":" + path;
        var bucket = buckets.getProxy(key, () -> Limits.forEndpoint(path));
        ConsumptionProbe probe = bucket.tryConsumeAndReturnRemaining(1);
        if (probe.isConsumed()) {
            long left = probe.getRemainingTokens();
            response.setHeader("X-RateLimit-Remaining", String.valueOf(left));
            chain.doFilter(request, response);
            return;
        }
        long nanos = probe.getNanosToWaitForRefill();
        long seconds = TimeUnit.NANOSECONDS.toSeconds(nanos) + 1;
        response.setStatus(429);
        response.setHeader("Retry-After", String.valueOf(seconds));
        response.setContentType("application/json");
        response.getWriter().write("{\"error\":\"rate limit\"}");
    }
}

The key is the tenant plus the path, so each tenant gets one bucket per endpoint. tryConsumeAndReturnRemaining(1) takes one token and reports whether it worked and how long until the next one. A refused client gets a number of seconds to wait instead of having to guess.

$ for i in 1 2 3 4 5 6 7 8; do curl -s -o /dev/null -w "%{http_code} " -H "X-Tenant: acme" localhost:18310/api/tickets; done; echo
200 200 200 200 200 429 429 429

$ curl -si -H "X-Tenant: acme" localhost:18310/api/tickets | grep -iE "^(HTTP|Retry-After)"
HTTP/1.1 429
Retry-After: 5

$ curl -s -o /dev/null -w "%{http_code}\n" -H "X-Tenant: globex" localhost:18310/api/tickets
200

$ curl -s -o /dev/null -w "%{http_code}\n" -H "X-Tenant: acme" localhost:18310/api/summaries
200

Five pass, then three get 429. Globex, and acme's summaries, are other buckets, so they still get 200.

The buckets live in Redis

The service runs as more than one copy. If each copy counted on its own, two copies with five tokens each would let ten through. So the count lives in one shared place:

@Configuration
class BucketStore {

    /** The buckets live in Redis, so every app copy counts against the same tokens. */
    @Bean
    ProxyManager<String> buckets(GateSettings settings) {
        var connection = RedisClient.create(settings.redisUrl())
                .connect(RedisCodec.of(StringCodec.UTF8, ByteArrayCodec.INSTANCE));
        return LettuceBasedProxyManager.builderFor(connection)
                .withExpirationStrategy(ExpirationAfterWriteStrategy
                        .basedOnTimeForRefillingBucketUpToMax(Duration.ofMinutes(1)))
                .build();
    }
}

The proxy manager reads and updates each bucket in Redis in one atomic step, and a bucket that has refilled and sat idle expires.

$ docker compose exec redis redis-cli --scan --pattern "rl:*" | sort
rl:acme:/api/summaries
rl:acme:/api/tickets
rl:globex:/api/tickets

Gate three: a bounded line pushes back

Backpressure means the line in front of the workers has a fixed length. Why not a long one? Each summary takes 300 ms. The last request in a line of eight waits 8 × 0.3 / 4 workers, which is 0.6 seconds. With a thousand waiting, it is 75 seconds, and by then the user has given up.

/** The scarce resource: 4 workers and a waiting line of 8. */
@Component
class WorkPool {
    private final ThreadPoolExecutor workers = new ThreadPoolExecutor(
            4, 4, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(8),                      // bounded: a full line says no
            new ThreadPoolExecutor.AbortPolicy());

    <T> T run(Callable<T> job) throws Exception {
        return workers.submit(job).get();
    }
}

When the line is full, AbortPolicy throws RejectedExecutionException instead of growing the line, and the controller turns that into an answer:

} catch (RejectedExecutionException lineIsFull) {
    return ResponseEntity.status(503).header("Retry-After", "1").body(Map.of("error", "busy"));
}

Twenty calls at once, each from its own tenant so the limiter stays out of the way:

$ seq 1 20 | xargs -P 20 -I{} curl -s -o /dev/null -w "%{http_code}\n" -H "X-Tenant: t{}" localhost:18310/api/summaries | sort | uniq -c
     12 200
      8 503

Four running plus eight waiting is twelve answered. The other eight get 503 with Retry-After: 1 right away, and none of the twenty waited forever. Swap in new LinkedBlockingQueue<>() and the line has no limit, so the line and every wait keep growing until memory runs out.

Gate two: drop the work that can wait

Not all work is equal, and the order is decided before the load arrives. AI summaries are slow and can wait, so they go first. Ticket lists and replies keep their workers.

/** Under pressure, drop the work that can wait (AI summaries) so tickets keep their workers. */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
class LoadShedFilter extends OncePerRequestFilter {
    private static final String SHED_BODY = "{\"error\":\"shed\",\"priority\":\"low\"}";
    private final AtomicInteger summariesInFlight = new AtomicInteger();
    ...
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            int running = summariesInFlight.incrementAndGet();
            if (running > settings.shedSummaryLimit()) {
                response.setStatus(503);
                response.setHeader("Retry-After", "2");
                response.setContentType("application/json");
                response.getWriter().write(SHED_BODY);
                return;
            }
            chain.doFilter(request, response);
        } finally {
            summariesInFlight.decrementAndGet();
        }
    }
}

The filter only looks at /api/summaries and allows at most two in flight. Over the limit, the call is dropped at the door and the worker never starts. A k6 spike runs twice with the limiter off: 30 summary clients and 5 ticket clients for 8 seconds.

$ LIMITER=false docker compose up -d app

$ docker compose --profile load run --rm --no-deps k6
tickets    6% ok   p95 640 ms
summaries  8% ok   shed 0

$ LIMITER=false SHED=true docker compose up -d app

$ docker compose --profile load run --rm --no-deps k6
tickets    100% ok  p95 47 ms
summaries  2% ok    shed 2127

Without shedding, the summaries fill the workers and only 6 percent of ticket calls succeed. With shedding, every ticket call succeeds with a p95 of 47 ms, and 2,127 summary calls were dropped.

Recap

GateProtectsSaysMeasured
Token bucket in RedisEveryone, from one noisy tenant429, Retry-After: 55 of 8 quick calls pass
Load shedThe workers, from low-priority work503 shed, Retry-After: 2Tickets 6% to 100% ok
Bounded poolMemory and waiting time503 busy, Retry-After: 112 of 20 answered, 8 refused at once

A fast no is kinder than a slow maybe. What a caller should do with that no, and with a slow dependency, is the next article: timeouts, retries, circuit breakers and bulkheads.

Keep going in Spring Boot · 39 of 99

Previous
Thymeleaf and htmx in Spring Boot: Live Search and One-Row Updates From Server-Rendered Fragments, With No JavaScript Framework
Next post
Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency

Toxiproxy adds 3,000 ms to billing, and a ticket list that never calls billing gets a p95 of 8,931 ms because all 10 threads are waiting. A 500 ms timeout, a bulkhead of three, a breaker over ten calls and one retry bring it to 6 ms, with 2,292 plan calls answered by the fallback. Remove the delay and the breaker closes by itself.

On this page

  • Gate one: a token bucket per tenant
  • The buckets live in Redis
  • Gate three: a bounded line pushes back
  • Gate two: drop the work that can wait
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.