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.
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.
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
| Gate | Protects | Says | Measured |
|---|---|---|---|
| Token bucket in Redis | Everyone, from one noisy tenant | 429, Retry-After: 5 | 5 of 8 quick calls pass |
| Load shed | The workers, from low-priority work | 503 shed, Retry-After: 2 | Tickets 6% to 100% ok |
| Bounded pool | Memory and waiting time | 503 busy, Retry-After: 1 | 12 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.
StudyEasy AI Community
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
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)