Video in progress

How do you do rate limiting at an API gateway, and why must the limit counter live in a shared place?

Usually a token bucket algorithm is used: for each key (user, API key, IP) there's a "bucket" that refills at a set rate. The gateway runs in several instances, so the counter has to be in a shared place like Redis.

📖 Answer

A token bucket is simple: the bucket holds at most burst tokens, rate tokens are added every second, and each request takes one token. If no token is left, you get 429 Too Many Requests. It allows short bursts but limits the average rate.

Spring Cloud Gateway has a ready-made filter:

spring:
  cloud:
    gateway:
      routes:
        - id: public-api
          uri: http://catalog-service:8080
          predicates:
            - Path=/api/catalog/**
          filters:
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 20
                redis-rate-limiter.burstCapacity: 40
                key-resolver: "#{@apiKeyResolver}"

If the counter lives in each instance's memory, then with 4 gateway pods the limit is effectively 4 times bigger, and the result varies depending on which pod a request lands on. In Redis the counting is atomic with a Lua script.

Choosing the key correctly matters. A limit by IP treats a whole office behind NAT as one user. For an authenticated API, the user ID or API key is better.

What happens if Redis itself goes down: fail open or fail closed? That's a deliberate decision too. Usually it's left open, otherwise a Redis failure takes down the whole API.