Skip to content
Visual explainer 2h to learn 3 steps

API gateways & rate limiting

Explain token bucket and sliding window limits and where to enforce them.

By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.

Topic 9 of 33

In short

An API gateway is the single front door that handles auth, routing, rate limiting and logging for many services. Rate limiting protects services from abuse and overload using algorithms like token bucket or sliding window.

Think of it like this: A token bucket is a ticket dispenser that refills at a steady rate.

Explained simply

As a company grows from one service to dozens, each would need its own login checks, logging and traffic limits. An API gateway is a single front door that handles these shared chores once, so each service can focus on its real job.

Think of a hotel reception desk. It checks your booking, tells you which floor to go to and stops a crowd from rushing the lifts. The rooms themselves do not need to check IDs; reception already did.

Rate limiting caps how many requests one client can make in a period, for example 100 per minute. It protects you from buggy apps stuck in a loop, from scrapers and password guessers, and it keeps things fair so one customer cannot starve the rest.

When a client goes over its limit, the server replies with status 429, "Too Many Requests", and says when to try again. Well-behaved clients wait and retry. The servers stay healthy for everyone else.

Press Play on a diagram to walk through it one step at a time.

LayersAPI gateway responsibilities
  1. 1
    TLS and authentication

    Verify tokens or API keys once at the edge

  2. 2
    Rate limiting

    Reject excess requests with HTTP 429

  3. 3
    Routing

    Map paths to backend services

  4. 4
    Transformation

    Aggregate responses, translate protocols

  5. 5
    Observability

    Request logs, metrics and trace IDs

CompareRate limiting algorithms
Token bucket
  • Tokens refill at fixed rate
  • Each request spends one token
  • Allows short bursts
  • Used by AWS and Stripe
Fixed window
  • Counter per minute window
  • Very simple
  • Bursts at window edges
  • Can allow 2x limit
Sliding window
  • Counts last N seconds
  • Smooth and accurate
  • Log or weighted counter
  • More memory or math
LayersWhere limits are enforced, from the outside in
  1. 1
    CDN / WAF

    Block floods and bad IPs before they reach you

  2. 2
    API gateway

    Per-key quotas and paid tiers

  3. 3
    Service

    Per-endpoint limits on expensive operations

  4. 4
    Outbound calls

    Respect partner limits, e.g. SMS 10 per second

SequenceA client hits its limit and backs off
Client
Gateway
Counter store
Orders service
  1. 1GET /orders (key k1)
    Client to Gateway: GET /orders (key k1)
  2. 2Count request for k1
    Gateway to Counter store: Count request for k1
  3. 3101 this minute (limit 100)
    Counter store to Gateway: 101 this minute (limit 100)
  4. 4429 + Retry-After: 20
    Gateway to Client: 429 + Retry-After: 20
  5. 5Retry 20 s later
    Client to Gateway: Retry 20 s later
  6. 6Count for k1: 1 in new window
    Gateway to Counter store: Count for k1: 1 in new window
  7. 7Forward request
    Gateway to Orders service: Forward request
  8. 8200 orders
    Orders service to Gateway: 200 orders

In depth

What belongs in a gateway, and what does not

A gateway should do jobs that are the same for every service and that should happen before a request reaches one. Business rules do not belong there. Once a gateway starts querying databases and making product decisions, every team has to change it, and it becomes a slow, risky bottleneck.

A related pattern is the backend for frontend (BFF): a small gateway per client type, such as one for the mobile app and one for the website, that combines several backend calls into the exact shape each screen needs. Popular gateways include Kong, AWS API Gateway, Envoy-based gateways and Apigee.

  • Verify tokens and API keys
  • Route paths to services; send 5% to a canary version
  • Enforce rate limits and request size limits
  • Add a request ID for tracing; log every call
  • Handle CORS and TLS

The sliding window counter trick

A true sliding window log stores a timestamp for every request, which uses a lot of memory. The sliding window counter gets close with just two numbers per client: the count for the current fixed window and the count for the previous one.

It assumes the previous window's requests were spread evenly and counts only the part still inside the sliding window. Estimate = current count + previous count × (fraction of the previous window still in view). With a limit of 100 per minute, 80 requests last minute, 30 so far this minute, and 15 seconds into this minute, 45 of the previous 60 seconds are still in view: 30 + 80 × 0.75 = 90, so the request is allowed. Cloudflare has described using this approach.

FlowSliding window counter, worked through
  1. 1
    Limit

    100 requests per minute

  2. 2
    Counts

    Previous minute 80, this minute 30

  3. 3
    Position

    15 s into the minute: 75% of previous still in view

  4. 4
    Estimate

    30 + 80 x 0.75 = 90

  5. 5
    Decision

    90 is under 100: allowed

Leaky bucket vs token bucket

A token bucket lets a client burst: if it saved up tokens, it can spend them quickly. That suits user-facing APIs, where short bursts are normal.

A leaky bucket instead puts requests into a queue that drains at a fixed rate, like water dripping from a hole. Output is perfectly smooth, but requests may wait. It is ideal in front of something fragile, such as an SMS provider that allows exactly 10 messages per second. NGINX's limit_req is a leaky bucket; its burst setting lets some requests queue up instead of being rejected, and nodelay serves those queued requests immediately.

CompareToken bucket vs leaky bucket
Token bucket
  • Saved tokens allow bursts
  • Suits user-facing APIs
  • No tokens left: rejected
Leaky bucket
  • Requests queue, drain at a fixed rate
  • Perfectly smooth output
  • Requests may wait
  • NGINX limit_req works this way

Choosing what to limit by

The key you count against matters as much as the algorithm. For logged-in traffic, limit by user ID or API key, which is fair and hard to dodge. For anonymous traffic, IP address is all you have, but many people can share one IP behind an office or mobile network, and with IPv6 one person may control a huge range, so limit by the /64 block.

Most real systems stack several limits: a generous overall limit per key, tighter limits on sensitive endpoints such as login, and a global limit that protects a fragile backend no matter who calls it.

  • Per user or API key: fair quotas and paid tiers
  • Per IP: anonymous traffic and floods
  • Per endpoint: login, sign-up, password reset
  • Global: protect a backend's total capacity

Telling clients about their limits

Good APIs make limits visible so clients can slow down before hitting them. Always send Retry-After with a 429. Many APIs also send headers such as X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset, and an IETF draft standardises RateLimit headers. GitHub, for example, allows 5,000 requests per hour for authenticated REST API users and reports what is left on every response.

When introducing a new limit, run it in shadow mode first: log who would have been blocked without blocking anyone. This catches limits that would hurt real customers before they cause an incident.

Learn it in 3 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Explain token bucket and sliding window~40m
  2. 2
    Decide where to enforce limits~40m
  3. 3
    List API gateway responsibilities~40m

Key points

  • Enforce limits at the gateway so bad traffic never reaches services.
  • Limit per user, API key or IP depending on the threat.
  • Return 429 with a Retry-After header so clients back off.
  • Distributed limits need a shared counter store like Redis.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
def allow(bucket, now, rate=10, capacity=20):
    # refill tokens based on elapsed time
    elapsed = now - bucket.last
    bucket.tokens = min(capacity, bucket.tokens + elapsed * rate)
    bucket.last = now
    if bucket.tokens >= 1:
        bucket.tokens -= 1
        return True   # allow
    return False      # reject with 429

Token bucket: 10 requests/second, bursts up to 20.

Sliding window counter in a few lines

This function estimates the requests in the last 60 seconds from two counters. The previous window's count is weighted by how much of it still overlaps the sliding window. Run it for three situations: early in a minute with modest traffic (allowed), early in a minute with heavy traffic (blocked), and late in a minute when the previous window barely counts (allowed).

python
def allowed(prev_count, curr_count, secs_into_window, limit=100, window=60):
    overlap = (window - secs_into_window) / window
    estimate = curr_count + prev_count * overlap
    return estimate < limit

print(allowed(80, 30, 15))  # 30 + 80*0.75 = 90.0  -> True
print(allowed(80, 50, 15))  # 50 + 80*0.75 = 110.0 -> False
print(allowed(80, 50, 45))  # 50 + 80*0.25 = 70.0  -> True

Designing limits for a public API

Step 1, tiers per API key: free gets 60 requests per minute, pro gets 1,000. Step 2, sensitive endpoints: login allows 5 attempts per 15 minutes per account and IP, which stops password guessing without hurting real users. Step 3, expensive endpoints: data export allows 10 per hour per key. Step 4, a global guard: the gateway caps total traffic to the search service at 20,000 per second to protect its cluster. Step 5, every response includes remaining-quota headers and every 429 includes Retry-After. Step 6, run all new limits in log-only mode for a week first.

Quick reference

  • Sliding window counter ≈ current + previous × share of previous window still in view
  • Token bucket allows bursts; leaky bucket gives a smooth, fixed output rate
  • Limit logged-in users by user or key; anonymous users by IP (IPv6: by /64)
  • Tight limits on login and password reset, e.g. 5 per 15 minutes
  • Always return 429 with Retry-After; expose remaining quota in headers
  • Test new limits in shadow (log-only) mode first
  • Gateways do shared chores; business logic stays in services

Common mistakes

  • Using per-server counters, so the real limit becomes limit times servers.
  • Rate limiting only by IP, punishing users behind shared NAT.
  • Making the gateway hold business logic and become a bottleneck.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Limit is 100 per minute. Last minute had 60 requests, this minute has 70, and we are 30 seconds in. Using a sliding window counter, is the next request allowed?

Question 2

2Which algorithm best protects a partner API that accepts exactly 10 calls per second?

Question 3

3Why is limiting only by IP address risky?

Question 4

4What should a gateway NOT do?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Limit: 10 requests per minute. The previous minute had 8 requests, this minute has 4 so far, and we are 30 seconds in. Is the next request allowed with a sliding window counter?

  2. Exercise 2medium

    Configure NGINX to allow each client IP 10 requests per second on /api/, with bursts of up to 20 served immediately, and return 429 when the limit is exceeded.

  3. Exercise 3hard

    Your gateway runs 30 instances in 3 regions and serves 50,000 API customers with per-key limits. Design rate limiting that stays fast (under 1 ms added) and survives the counter store failing.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is an API gateway the same as a load balancer?
No, though they overlap. A load balancer spreads traffic across copies of a service; a gateway also authenticates, rate limits and routes requests to many different services.
What if the rate limiter's data store goes down?
Most teams fail open and let traffic through, because blocking every customer is worse than briefly allowing extra requests. Local per-server limits can act as a rough backup.
Do I need a gateway if I only have one service?
Usually not. A reverse proxy or your framework's middleware can handle auth and rate limits. Gateways pay off once several services share these concerns.
ShareXLinkedInWhatsApp