# How do you rate-limit without running out of memory?

By Vishal Kumar · Published 2026-05-07 · Updated 2026-11-13
Source: https://fungyaan.com/p/token-bucket-rate-limiting
Tags: data-structures, rate-limiting, security, go

**Short answer:** the verdict, which we'll earn line by line: use a token bucket per key with lazy refill (no timers). Treat the map of buckets as attacker-controlled: cap its size, sweep buckets that have fully refilled (they hold no information), and evict at random when it's still full rather than refusing new keys. Key by network (IPv4 address or IPv6 /64), and by email *plus* network for logins, so nobody can lock out someone else's account.

*Data structures in production, part 1.* I enjoy this case because it's a small piece of code with a surprising amount of thinking packed into it.

Every explanation of the token bucket covers the same thing: a bucket holds up to *N* tokens, refills at a steady rate, and each request spends one. That part is ten lines of code, and it isn't where the danger lies. The mystery is everything around it, because a rate limiter is a map keyed by attacker-controlled input. If you get the key or the memory bound wrong, the thing meant to protect you becomes the way in: a guard that can be talked into locking out the people it serves, or fed until it collapses.

This post walks through the limiter in the blogging platform I run. It's about 80 lines of Go with no dependencies, and it guards signup and login.

> **Case file**
>
> | | |
> |---|---|
> | **The case** | A rate limiter is a map keyed by attacker-controlled input |
> | **Suspects** | Token bucket, fixed window, sliding log, sliding window counter |
> | **Culprit** | The key and the unbounded map, not the bucket arithmetic |
> | **The fix** | Key by network (IPv6 /64), email + network for logins, cap at 100,000 keys, sweep full buckets, evict at random |
> | **Evidence** | About 80 lines of Go guarding signup and login on the blogging platform I run |

## The suspects: token bucket vs the alternatives

| | Token bucket | Fixed window | Sliding log | Sliding window counter |
|---|---|---|---|---|
| **Memory per key** | Two numbers | A counter and a window start | One timestamp per request in the window | Two counters |
| **Bursts** | Up to the bucket size, then the steady rate | Up to twice the limit across a window boundary | None beyond the limit: exact | Approximate; smooths the boundary |
| **Pick it when** | User-facing limits that should forgive a quick retry | Simple quotas (per day, per month) | Low limits where exactness matters | Per-second limits at a gateway |

## The bucket

```go
type bucket struct {
	tokens float64
	last   time.Time
}

// New allows n events per interval per key, with bursts of up to n.
func New(n int, interval time.Duration) *Limiter {
	return &Limiter{
		rate:    float64(n) / interval.Seconds(),
		burst:   float64(n),
		buckets: make(map[string]*bucket),
		now:     time.Now,
	}
}
```

There's no background goroutine refilling tokens. Each bucket stores its token count and when it was last touched, and the refill is computed lazily on the next request:

```go
b.tokens = min(l.burst, b.tokens+now.Sub(b.last).Seconds()*l.rate)
b.last = now
if b.tokens < 1 {
	return false
}
b.tokens--
return true
```

Pause on this, because it's the first elegant move. Lazy refill is what makes the token bucket cheap: an idle key costs nothing per second, only memory. It also gives you the two knobs you actually want. The rate limits sustained abuse; the burst lets a real person retry a typo three times in a row without being blocked.

`now` is a field, not a call to `time.Now()`, so tests can move the clock:

```go
now := time.Unix(0, 0)
l := New(3, time.Minute)
l.now = func() time.Time { return now }
// three allowed, the fourth denied ...
now = now.Add(20 * time.Second) // refills exactly one token
if !l.Allow("ip") || l.Allow("ip") {
	t.Fatal("refill is wrong")
}
```

## The first clue: choosing the key is the real design decision

The platform uses three limiters:

| Limiter | Limit | Key |
|---|---|---|
| Signup | 5 per hour | client network |
| Login, overall | 10 per minute | client network |
| Login, per account | 10 per 15 minutes | email + client network |

**"Network", not "IP address".** For IPv4 the key is the address. For IPv6 it's the /64 prefix, because one home or phone subscriber is normally given a whole /64. That is 2⁶⁴ addresses, so keying by address lets anyone rotate to a fresh, empty bucket for every request:

```go
if v4 := ip.To4(); v4 != nil {
	return v4.String()
}
return ip.Mask(net.CIDRMask(64, 128)).String() + "/64"
```

**Email *plus* network, not email alone.** Here's the false lead. A per-email limit sounds like the obvious defence against password guessing. But if the key is the email alone, anyone who knows your email can lock you out of your own account by failing ten logins. Adding the network means an attacker exhausts *their* bucket for your account, not yours. It's a small change to a string, and I find it a very satisfying one: the same limit now protects you instead of being used against you. The per-network limit still caps how fast one source can guess overall.

A third trap is where the client address comes from. Behind a reverse proxy every request arrives from the proxy, so a limiter keyed on `RemoteAddr` puts all users in one bucket. Trusting `X-Forwarded-For` blindly is worse: clients can write whatever they like in it. The platform reads only the last entry, the one its own proxy appended, and only when a `TRUST_PROXY` setting says a proxy is there.

## The second clue: bounding memory, the part most implementations skip

Every new key adds a map entry. An attacker with many addresses (or one IPv4 user cycling through emails, for the per-account limiter) can add entries faster than they expire. A limiter with no bound is a memory leak with a public API.

The limiter caps the table at 100,000 keys and does two kinds of cleanup.

**Sweep, once a minute.** A bucket that has fully refilled carries no information: a new bucket for that key would start at exactly the same state. So it can be deleted, and cleanup never loses anything: the forgotten bucket and a fresh one are indistinguishable. This is my favourite part of the whole limiter. Forgetting is free, because there's nothing to remember.

```go
// sweep drops buckets that have refilled completely (they carry no state).
func (l *Limiter) sweep(now time.Time) {
	for k, b := range l.buckets {
		if b.tokens+now.Sub(b.last).Seconds()*l.rate >= l.burst {
			delete(l.buckets, k)
		}
	}
}
```

**Evict, only when still full.** If a sweep doesn't free space, the limiter deletes 10% of the entries at random. Go randomises map iteration order, so "the first N keys from a range loop" is good enough for a random sample:

```go
if len(l.buckets) >= maxKeys {
	l.sweep(now)
	if len(l.buckets) >= maxKeys {
		l.evict(maxKeys / 10)
	}
}
```

```mermaid
flowchart TD
  R["Request with a key"] --> F{"Table at the key cap?"}
  F -- no --> B["Find or create the bucket"]
  F -- yes --> S["Sweep fully refilled buckets"]
  S --> F2{"Still full?"}
  F2 -- yes --> E["Evict 10% at random"]
  F2 -- no --> B
  E --> B
  B --> L["Refill lazily from elapsed time"]
  L --> T{"At least one token?"}
  T -- yes --> A["Allow, spend a token"]
  T -- no --> D["Deny"]
```

## The dilemma: fail open or fail closed?

When the table is full there are two choices. You can refuse every *new* key, which keeps existing limits exact but locks out every real user who arrives during an attack. Or you can evict, which lets a few attackers get a fresh bucket early but keeps the site usable.

For a login form I chose eviction. Refusing new keys turns a flood of junk keys into a global lockout, which is exactly the denial of service the attacker wanted. The strict-sounding option is the trap. The limiter is one layer; the expensive operation behind it has its own bound (below), so a few early resets don't open anything up.

That choice gets its own test, so nobody "fixes" it later:

```go
func TestLimiterStaysBoundedAndOpen(t *testing.T) {
	l := New(1, time.Hour)
	// ... fixed clock ...
	for i := 0; i < maxKeys+500; i++ {
		l.Allow(strconv.Itoa(i))
	}
	if len(l.buckets) > maxKeys {
		t.Fatalf("table grew to %d", len(l.buckets))
	}
	if !l.Allow("brand-new-user") {
		t.Fatal("a full table locked out a new key")
	}
}
```

## The accomplice: rate limits are not the only bound

Password hashing (argon2) is deliberately slow and memory-hungry, which makes the login endpoint an amplifier: cheap request in, expensive work out. Rate limits reduce how often that happens per client, but many clients together can still queue up hashing work. So the platform also caps concurrent hashes with a small number of slots and a short wait (the [password storage post](/p/storing-passwords) has the settings); when they're all busy, it returns 503 instead of queueing without limit. Bound the work as well as the requests.

## What I'd use instead at larger scale

This limiter is per process. With one app instance that's fine. With several behind a load balancer, each has its own buckets and the effective limit multiplies by the instance count. The options then are:

- a shared store with an atomic token-bucket operation (Redis with a small Lua script is the common one),
- rate limiting at the edge proxy or API gateway, where the client address is known first-hand (the [API scaling post](/p/scale-an-api) covers edge limits),
- or both: coarse limits at the edge, per-account limits in the app, where the email is known.

The data structure stays the same. What changes is where the map lives and who owns its memory.

> **Remember this**
> - The token bucket is trivial; the key is the real design decision.
> - Never key a limit so one user can lock out another.
> - Bound the map, and prefer fail-open eviction when it's full.

## Case closed: takeaways

- The token bucket itself is trivial. Spend the design time on the **key**: network rather than address, and never a key that lets one user lock out another.
- A rate limiter is a map keyed by attacker input. **Bound it**, and decide in advance what happens when it's full.
- **Prefer fail-open eviction** for user-facing limits, and pin that decision with a test.
- Bound the expensive work behind the limiter too.

Eighty lines, no dependencies, and every one of them earning its place. That's what I find so rewarding about small infrastructure code: when you think carefully about who controls the input, even a humble map deserves careful engineering.
