0Pricing
API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) · Урок

Изоляция отказов и ограничение частоты запросов

Изолируйте сбои и защищайте нижестоящие сервисы с помощью изоляции типа bulkhead и фильтра RequestRateLimiter шлюза.

«Изоляция отказов и ограничение частоты запросов» — бесплатный урок API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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: 20

Why 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: 20

Replenish 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: 20

Graceful 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_REQUESTS

Observing 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
  • RequestRateLimiter uses a Redis token bucket
  • replenishRate and burstCapacity shape traffic
  • A KeyResolver defines the limiting key

Combined with circuit breakers, retries, and fallbacks, your gateway degrades gracefully under stress.

Часто задаваемые вопросы

Урок «Изоляция отказов и ограничение частоты запросов» бесплатный?

Да — полный текст урока «Изоляция отказов и ограничение частоты запросов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway), подпишись на CoddyKit PRO. Курс API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) содержит 4 уроков всего.

Чему я научусь в уроке «Изоляция отказов и ограничение частоты запросов»?

Изолируйте сбои и защищайте нижестоящие сервисы с помощью изоляции типа bulkhead и фильтра RequestRateLimiter шлюза. Ты практикуешь API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)?

Предыдущий опыт не требуется. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Изоляция отказов и ограничение частоты запросов»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)?

Да. Каждый урок API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Размыкатели цепи с Resilience4j
  2. Настройка повторных попыток и тайм-аутов
  3. Обработка ошибок и резервные варианты
  4. Изоляция отказов и ограничение частоты запросов
← Назад к API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)