Anteparos e limitação de taxa para resiliência
Isole falhas e proteja serviços downstream usando isolamento por anteparos e o filtro RequestRateLimiter do gateway.
Anteparos e limitação de taxa para resiliência é uma aula grátis de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Containing the Blast Radius
Circuit breakers stop calls to a broken service, but a flood of traffic to one route can still starve others. Bulkheads and rate limiting keep one busy route from sinking the whole gateway.
The Bulkhead Pattern
Named after a ship's watertight compartments, a bulkhead caps how many concurrent calls a route may have. If one service slows down, only its compartment fills, sparing the rest.
Resilience4j Bulkhead Config
Resilience4j offers a bulkhead that limits concurrent calls per instance.
resilience4j:
bulkhead:
instances:
orders:
maxConcurrentCalls: 20Why Rate Limiting Differs
A bulkhead caps concurrency; a rate limiter caps requests over time. Together they protect both fast bursts and sustained load.
The RequestRateLimiter Filter
Spring Cloud Gateway ships a RequestRateLimiter filter backed by a Redis token bucket. It rejects excess requests with HTTP 429.
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20Replenish Rate and Burst
replenishRate is the steady tokens per second; burstCapacity is the most that can be spent in a spike. Burst should be greater than or equal to replenish.
Choosing a KeyResolver
A KeyResolver decides what to limit by, such as user, API key, or IP. Here we limit per user from a header.
@Bean
KeyResolver userKeyResolver() {
return exchange -> Mono.just(
exchange.getRequest().getHeaders()
.getFirst("X-User-Id"));
}Redis Backing Store
The limiter needs Redis so counts are shared across gateway instances. Add the reactive Redis starter.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>Combining Patterns
Stack resilience filters on a route: circuit breaker first, then rate limiter, so traffic is shaped before reaching a possibly fragile backend.
filters:
- name: CircuitBreaker
args:
name: ordersCB
fallbackUri: forward:/fallback/orders
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20Graceful Rejection
When the limit is exceeded the client gets 429. You can customize the status, but always return a clear, retryable response so clients can back off.
args:
redis-rate-limiter.replenishRate: 5
statusCode: TOO_MANY_REQUESTSObserving the Limits
Watch metrics for 429 counts and bulkhead rejections. Tune the numbers based on real downstream capacity, not guesses.
Quick Check
What is the core difference between a bulkhead and a rate limiter?
Recap
You added two more resilience tools:
- Bulkheads cap concurrent calls per route
RequestRateLimiteruses a Redis token bucketreplenishRateandburstCapacityshape traffic- A
KeyResolverdefines the limiting key
Combined with circuit breakers, retries, and fallbacks, your gateway degrades gracefully under stress.
Perguntas Frequentes
A aula “Anteparos e limitação de taxa para resiliência” é grátis?
Sim — o texto completo de “Anteparos e limitação de taxa para resiliência” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway), atualize para CoddyKit PRO. O curso de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) inclui 4 aulas no total.
O que vou aprender em “Anteparos e limitação de taxa para resiliência”?
Isole falhas e proteja serviços downstream usando isolamento por anteparos e o filtro RequestRateLimiter do gateway. Você pratica API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)?
Nenhuma experiência prévia é necessária. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Anteparos e limitação de taxa para resiliência”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)?
Sim. Cada aula de API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Disjuntores com Resilience4j
- Configuração de Repetições e Tempos Limite
- Tratamento de Erros e Mecanismos Alternativos
- Anteparos e limitação de taxa para resiliência