Articles / Go

  • go
  • rate-limiting
  • security
  • denial-of-service
  • maps
  • networking

Why Your Go Rate Limiter Map Grows Forever Under a Spoofed-IP Flood

A per-IP rate limiter is meant to protect your service, but the map holding the limiters can be the thing that kills it. Every new key allocates an entry, nothing ever removes it, and the attacker chooses the keys. Send one packet each from a million different source addresses and you now hold a million limiters.

The usual code

This is the pattern in most tutorials, and I have written it myself:

type Limiter struct {
	mu  sync.Mutex
	m   map[netip.Addr]*rate.Limiter
	rps rate.Limit
	b   int
}

func (l *Limiter) Allow(ip netip.Addr) bool {
	l.mu.Lock()
	defer l.mu.Unlock()
	lim, ok := l.m[ip]
	if !ok {
		lim = rate.NewLimiter(l.rps, l.b)
		l.m[ip] = lim
	}
	return lim.Allow()
}

It is correct for honest clients. The flaw is that the map has no upper bound and no expiry. A client who has gone away still costs you memory until the process restarts.

Where the attacker gets unlimited keys

Spoofing a TCP source address is hard, because the handshake needs the reply. So where does the flood come from?

  • UDP services (DNS-like protocols, syslog receivers, game servers, anything QUIC-adjacent), where the source address is just a field in the packet.
  • An HTTP service that trusts X-Forwarded-For from anyone. The attacker writes a fresh "client IP" into every request.
  • IPv6, where no spoofing is needed. One ordinary customer is typically handed a /64, which is 2^64 genuine addresses.

The header case is the most common in practice. If you take the leftmost X-Forwarded-For value without checking that the request came from your own proxy, the key is entirely attacker-controlled.

Quick detour: deleting from a Go map does not give memory back

Hang on, why not just delete idle entries and be done? Because a Go map does not shrink when you delete from it. Deleting frees the slot for reuse and lets the garbage collector reclaim the values you pointed to, but the table itself keeps its size.

So after a flood the limiter structs go away, yet the map's backing storage stays at its high-water mark. If that matters, the fix is to build a fresh map and copy the survivors across, or to cap the size so the high-water mark is acceptable in the first place. Capping is the better habit.

A bounded version

Three changes: record when each entry was last seen, sweep out old ones, and refuse to grow past a hard cap.

type entry struct {
	lim  *rate.Limiter
	seen time.Time
}

type Limiter struct {
	mu       sync.Mutex
	m        map[netip.Addr]*entry
	overflow *rate.Limiter
	max      int
	rps      rate.Limit
	b        int
}

func New(rps rate.Limit, burst, max int) *Limiter {
	return &Limiter{
		m:        make(map[netip.Addr]*entry),
		overflow: rate.NewLimiter(rps*100, burst*100),
		max:      max,
		rps:      rps,
		b:        burst,
	}
}

func key(ip netip.Addr) netip.Addr {
	ip = ip.Unmap()
	if ip.Is6() {
		p, _ := ip.Prefix(64)
		return p.Addr()
	}
	return ip
}

func (l *Limiter) Allow(ip netip.Addr) bool {
	k := key(ip)
	now := time.Now()
	l.mu.Lock()
	defer l.mu.Unlock()
	e, ok := l.m[k]
	if !ok {
		if len(l.m) >= l.max {
			return l.overflow.Allow()
		}
		e = &entry{lim: rate.NewLimiter(l.rps, l.b)}
		l.m[k] = e
	}
	e.seen = now
	return e.lim.Allow()
}

func (l *Limiter) Sweep(idle time.Duration) {
	cutoff := time.Now().Add(-idle)
	l.mu.Lock()
	defer l.mu.Unlock()
	for k, e := range l.m {
		if e.seen.Before(cutoff) {
			delete(l.m, k)
		}
	}
}

Run Sweep from a ticker goroutine every minute or so, with an idle time of a few minutes. Deleting from a map while ranging over it is explicitly allowed by the Go spec.

What each piece is doing

  • The cap turns unbounded growth into a fixed worst case. You can now work out the memory ceiling: entries times a few hundred bytes, which you should measure with a benchmark rather than trust my guess.
  • The overflow limiter is the fallback when the map is full. New keys share one bucket instead of getting their own. It is generous per key but tight in total, so a flood cannot push work through unchecked.
  • The /64 mask stops one IPv6 customer from minting 2^64 keys. Treating a /64 as one client is a policy choice; some networks hand out smaller prefixes, so adjust to your users.
  • The sweep removes honest clients who left, so normal traffic never reaches the cap.

The trade-off you are accepting

When the cap is hit during an attack, genuine new visitors land in the shared overflow bucket and may be throttled alongside the attacker. That is a degraded service, but it is still a running one, which beats an out-of-memory kill that takes everybody down.

Also, the sweep holds the mutex while it walks the whole map. With millions of entries that is a noticeable pause. If you expect that scale, shard the map by hashing the key into, say, 64 independent mutex-and-map pairs, and sweep one shard at a time.

Fix the key source first

All of this is damage limitation. The better fix for the header case is to stop trusting it: only read X-Forwarded-For when RemoteAddr is one of your own proxies, and take the entry your proxy appended, not the leftmost one. For UDP there is no such option, so the cap is the real defence.

A quick test: feed Allow a few million distinct addresses in a loop, then check that len(l.m) stays at max and that heap use plateaus. If it keeps climbing, something is still keying on attacker input.