java
37 lines · 7 steps
Building a Spring Boot rate-limiter auto-config
A Spring Boot auto-configuration wires up a token-bucket rate limiter and registers it as a web interceptor, all conditionally.
Explained by
highlit
1@AutoConfiguration
2@EnableConfigurationProperties(RateLimiterProperties.class)
3@ConditionalOnClass(RateLimiter.class)
4public class RateLimiterAutoConfiguration {
5
6 @Bean
7 @ConditionalOnMissingBean
8 public RateLimiter rateLimiter(RateLimiterProperties properties, ObjectProvider<MeterRegistry> meterRegistry) {
9 TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(
10 properties.getCapacity(),
11 properties.getRefillTokens(),
12 properties.getRefillPeriod());
13 meterRegistry.ifAvailable(limiter::bindMetrics);
14 return limiter;
15 }
16
17 @Bean
18 @ConditionalOnMissingBean
19 @ConditionalOnProperty(prefix = "app.rate-limiter", name = "enabled", havingValue = "true", matchIfMissing = true)
20 public RateLimitInterceptor rateLimitInterceptor(RateLimiter rateLimiter, RateLimiterProperties properties) {
21 return new RateLimitInterceptor(rateLimiter, properties.getKeyResolver());
22 }
23
24 @Bean
25 @ConditionalOnMissingBean
26 @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
27 public WebMvcConfigurer rateLimiterWebMvcConfigurer(RateLimitInterceptor interceptor, RateLimiterProperties properties) {
28 return new WebMvcConfigurer() {
29 @Override
30 public void addInterceptors(InterceptorRegistry registry) {
31 registry.addInterceptor(interceptor)
32 .addPathPatterns(properties.getPathPatterns())
33 .order(Ordered.HIGHEST_PRECEDENCE);
34 }
35 };
36 }
37}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Auto-configuration classes let a library contribute beans that back off gracefully when the app already defines its own.
- 2Layered @Conditional annotations make wiring depend on classpath, properties, and application type rather than hard assumptions.
- 3ObjectProvider lets you consume an optional dependency without forcing it to exist.
Related explainers
php
final class Container { private array $bindings = []; private array $instances = [];
Building a DI container with reflection in PHP
dependency-injection
reflection
autowiring
Advanced
9 steps
java
import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Currency;
A safe Money value type in Java
immutability
bigdecimal
value-object
Intermediate
10 steps
java
public class RequestCoalescer<K, V> { private final ConcurrentHashMap<K, CompletableFuture<V>> inFlight = new ConcurrentHashMap<>(); private final Function<K, V> loader;
Coalescing duplicate requests in Java
concurrency
caching
completablefuture
Advanced
6 steps
java
public final class NaturalOrderComparator implements Comparator<String> { public static final NaturalOrderComparator INSTANCE = new NaturalOrderComparator();
Natural-order string sorting in Java
comparator
natural-sort
string-parsing
Intermediate
9 steps
java
package com.example.validation; import java.util.List; import java.util.stream.Collectors;
Validating JSON payloads against a schema in Java
json-schema
validation
recursion
Intermediate
8 steps
php
<?php namespace App\RateLimiting;
Sliding-window rate limiting with Redis sorted sets
rate-limiting
redis
sorted-sets
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-spring-boot-rate-limiter-auto-config-explained-java-1b2f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.