Your API gateway allows five requests every ten seconds. A client sends five at 9.9 seconds and another five at 10.1 seconds. All ten reach the backend.

Wait, how did that pass?

It depends on what you meant by every ten seconds. If you’re counting in blocks, the requests landed in two different blocks. If you meant any ten-second stretch, the second batch should have been rejected. And if you just want to allow a small burst without letting the client keep hammering the backend, you probably want a different rule altogether.

Fixed window: the obvious one

Split time into blocks: [0s, 10s), [10s, 20s), and so on. Keep a counter per client. When a request arrives in a new window, reset the counter. If there’s room, increment it and let the request through.

          9.9s     10s     10.1s
        5 requests  |  5 requests
       [0s, 10s)    |    [10s, 20s)

The limiter did exactly what we told it to do. The backend still got ten requests in 200 ms.

For a quota like “1,000 requests per UTC day,” I’d use this. The reset is part of the rule, and a counter plus a window ID is cheap. If the goal is to keep a small upstream from getting slammed, the reset is a problem.

Sliding window: look back from now

Instead of resetting at the clock boundary, keep the timestamps of requests you let through. On each request:

  1. Remove timestamps at or before now - 10s.
  2. If five timestamps remain, reject the request.
  3. Otherwise, append now and let it through.

At 10.1s, all five requests from 9.9s are still in the log. The second batch gets a 429 if the gateway rejects excess requests immediately. With a queue, each timestamp is added and removed once, so the work is amortized constant time. The part that grows is memory: a 1,000-request limit can mean 1,000 timestamps per client.

Can we keep just two counters? Yes, if an estimate is good enough. A sliding window counter keeps one count for the current window and another for the previous one. If you’re 15 seconds into a minute, 45 seconds of the previous minute are still inside your rolling window:

previous minute: 80 requests
current minute:  25 requests
estimated usage: 25 + 80 × (45 / 60) = 85 requests

This assumes last minute’s traffic was spread evenly. If all 80 arrived at the end of the minute, the real count is 105. If they all arrived at the beginning, it’s 25. Two counters save memory, but I wouldn’t use them to promise an exact rolling quota.

Token bucket: how big a burst can I afford?

Say your gateway config looks like this:

rate_limit:
  rate: 10
  burst: 50

Start with 50 tokens. Every request spends one. The bucket earns ten tokens per second, up to a maximum of 50. An idle client can send 50 requests immediately. If it spends all 50, it earns one more after 100 ms and refills completely after five seconds with no more requests.

That gives you two knobs: rate is what a client can sustain, and burst is what it can spend at once. It also explains why setting a refill rate of 100 per minute doesn’t promise “at most 100 in any minute.” A client can spend the tokens it started the minute with, too.

A tiny implementation in Go

The obvious implementation would run a ticker to refill the bucket. But nothing needs to happen while nobody is asking for tokens. We can calculate the refill when the next request arrives.

package ratelimit

import (
	"math"
	"sync"
	"time"
)

type Bucket struct {
	mu       sync.Mutex
	rate     float64
	capacity float64
	tokens   float64
	last     time.Time
}

// newBucket assumes a finite, positive rate and a positive burst.
func newBucket(rate float64, burst int) *Bucket {
	return &Bucket{
		rate:     rate,
		capacity: float64(burst),
		tokens:   float64(burst),
		last:     time.Now(),
	}
}

func (b *Bucket) Allow() bool {
	b.mu.Lock()
	defer b.mu.Unlock()

	now := time.Now()
	elapsed := now.Sub(b.last).Seconds()
	b.tokens = math.Min(b.capacity, b.tokens+elapsed*b.rate)
	b.last = now

	if b.tokens < 1 {
		return false
	}

	b.tokens--
	return true
}

The mutex covers the whole decision. If two goroutines arrive with one token left, only one gets it. For a real gateway, I’d use golang.org/x/time/rate and call Allow() in the middleware. Use AllowN with explicit timestamps to test the burst and refill without sleeping.

If the caller hits its limit, return 429 Too Many Requests. Add Retry-After if you have a useful estimate. Another request can still take the next token before the original caller retries.

Leaky bucket: what if the backend wants a steady pace?

A token bucket can let a burst go straight through. The queue-based leaky bucket puts requests into a bounded queue and releases them at a fixed rate. If 50 jobs arrive at once and the queue drains at five per second, dispatching them takes about ten seconds. If the queue is full, reject new arrivals.

I’d use this for a worker that calls a downstream API or sends webhooks at a steady pace. In an HTTP gateway, holding requests open is a real cost. If you queue them, cap the queue and give them a deadline.

GCRA: keep a timestamp instead of a token balance

The Generic Cell Rate Algorithm keeps a theoretical arrival time, or tat. At five requests per second, each accepted request moves that time forward by 200 ms. If the client has been idle, start the schedule from now instead of the old timestamp.

interval  = 1 / rate
tolerance = (burst - 1) × interval

if now < tat - tolerance:
    reject

tat = max(now, tat) + interval
allow

With a burst of three, the tolerance is 400 ms. From an idle state, three requests can pass at the same instant. The fourth has to wait 200 ms. You get a similar rate-and-burst policy to a token bucket, with just one changing timestamp per key.

What changes when you add replicas?

Run the 10/s, burst 50 limiter on three replicas and you now have three buckets. A client whose traffic reaches all three can get up to 150 requests through in an initial burst. That’s fine for protecting each instance. It isn’t a shared customer quota.

For a shared quota, every instance needs to make its decision against the same state. The obvious Redis version is “read the balance, subtract one, write it back.” That doesn’t work either:

Gateway A reads 1 token.
Gateway B reads 1 token.
Both let a request through and write 0.

Use an atomic read-refill-check-write, such as a short Redis script. Decide up front what happens if Redis is down. A local fallback keeps traffic moving with a looser quota. Rejecting traffic preserves the boundary but can take a route offline. Keep store errors separate from quota denials so you can tell those cases apart.

Two other decisions matter just as much as the algorithm:

  • Who shares the bucket? Use a verified tenant or API-key ID for customer quotas, and a stable route ID when the rule is per route. A bucket per raw URL can give /orders/123 and /orders/456 separate budgets and let the store grow without bound. Bound the store and expire idle entries. Evicting a bucket before it would refill can give a client a fresh burst.
  • How much work is already running? If you’re accepting 100 requests a second and each takes ten seconds, you can have about 1,000 requests in flight at steady state. Limit concurrency separately if the backend can’t handle that. If a dependency starts timing out, a circuit breaker solves a different part of that problem.

Wrap up

I’d start with an in-memory token bucket for a Go gateway. It’s easy to explain, and the rate and burst settings match how clients actually send traffic. I’d reach for a fixed window for calendar quotas, an exact sliding log for a strict rolling limit, and a leaky bucket when the downstream needs a steady pace. GCRA gives you another way to express a rate and burst when you want to store only a timestamp.

Before picking any of them, write down what should happen to those five requests at 9.9s and the next five at 10.1s. That’s the policy. The algorithm is how you get it.