Gin in production · 5 MIN READ

Rate limiting in Gin: a token bucket per identity, a bounded map and an honest Retry-After

Limit each client with golang.org/x/time/rate, pick a key clients cannot forge, bound the limiter map and refuse with 429 and Retry-After.

A rate limiter protects shared capacity from one noisy client. Three decisions matter more than the algorithm: what identifies a client, how much memory the limiter may use, and what a refused client is told. Choose the key badly and an attacker gets a fresh bucket on every request. Forget the memory bound and the limiter becomes the leak it was meant to prevent.

gin · A MAP OF THE IDEA

  1. Resolve client key
  2. Find or create bucket
  3. Reserve at explicit time
  4. 429 + Retry-After

Useful when

  • Per-identity buckets isolate noisy clients from everyone else.
  • Explicit times make every limiter decision unit-testable.

Watch out

  • An IP key is only as good as the trusted-proxy configuration.
  • In-process limits multiply by the number of replicas.

Implementation & operation cost: One small struct per active client and a mutex on the map; a global limit additionally costs a shared store and a round trip per request.

01

Token buckets and the x/time/rate API

rate.NewLimiter(r, b) models a bucket that holds up to b tokens and refills at r tokens per second; each request takes one. The burst b absorbs short spikes, and r is the sustained rate. A Limiter is safe for concurrent use, but a map of limiters is not, so the store needs its own mutex. The methods differ in what happens when the bucket is empty. Allow reports false and nothing else. Wait blocks until a token arrives, which in an HTTP handler means holding a goroutine and a connection open for a client you meant to slow down. Reserve says how long until a token will be available, which is exactly the number Retry-After needs. AllowN and ReserveN take an explicit time.Time, so a test can drive the limiter with a fake clock instead of sleeping.

02

Key by identity, bound the store, refuse with Retry-After

The program allows one request per second with a burst of two and keeps at most three buckets. A stand-in for the auth middleware sets the subject. Anonymous callers are keyed by ClientIP, which only means something because the engine trusts exactly one proxy address. A fake clock drives every decision, so the output never depends on how fast the machine is.

go
package main

import (
	"container/list"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"golang.org/x/time/rate"
)

// Limiters keeps one token bucket per client key, at most max of them.
type Limiters struct {
	mu    sync.Mutex
	limit rate.Limit
	burst int
	max   int
	lru   *list.List // front = most recently used
	byKey map[string]*list.Element
}

type bucket struct {
	key string
	lim *rate.Limiter
}

func NewLimiters(limit rate.Limit, burst, max int) *Limiters {
	return &Limiters{limit: limit, burst: burst, max: max, lru: list.New(), byKey: map[string]*list.Element{}}
}

func (s *Limiters) get(key string) *rate.Limiter {
	s.mu.Lock()
	defer s.mu.Unlock()
	if el, ok := s.byKey[key]; ok {
		s.lru.MoveToFront(el)
		return el.Value.(*bucket).lim
	}
	if s.lru.Len() >= s.max {
		oldest := s.lru.Back()
		s.lru.Remove(oldest)
		delete(s.byKey, oldest.Value.(*bucket).key)
	}
	b := &bucket{key: key, lim: rate.NewLimiter(s.limit, s.burst)}
	s.byKey[key] = s.lru.PushFront(b)
	return b.lim
}

func (s *Limiters) Keys() []string {
	s.mu.Lock()
	defer s.mu.Unlock()
	var keys []string
	for el := s.lru.Front(); el != nil; el = el.Next() {
		keys = append(keys, el.Value.(*bucket).key)
	}
	return keys
}

type subjectKey struct{}

// fakeAuth stands in for the bearer-token middleware of the auth lesson.
func fakeAuth(c *gin.Context) {
	if c.GetHeader("Authorization") == "Bearer t-user-17" {
		c.Set(subjectKey{}, "user-17")
	}
	c.Next()
}

func clientKey(c *gin.Context) string {
	if sub, ok := c.Get(subjectKey{}); ok {
		return "user:" + sub.(string)
	}
	return "ip:" + c.ClientIP() // safe only because trusted proxies are configured
}

func rateLimit(s *Limiters, now func() time.Time) gin.HandlerFunc {
	return func(c *gin.Context) {
		t := now()
		res := s.get(clientKey(c)).ReserveN(t, 1)
		if !res.OK() {
			c.AbortWithStatus(http.StatusTooManyRequests) // burst < 1: never allowed
			return
		}
		if d := res.DelayFrom(t); d > 0 {
			res.CancelAt(t) // we will not wait, so return the reserved token
			c.Header("Retry-After", strconv.Itoa(int((d+time.Second-1)/time.Second)))
			c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "rate limited"})
			return
		}
		c.Next()
	}
}

func main() {
	gin.SetMode(gin.TestMode)
	start := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
	now := start
	limiters := NewLimiters(rate.Every(time.Second), 2, 3)

	r := gin.New()
	if err := r.SetTrustedProxies([]string{"192.0.2.1"}); err != nil {
		panic(err)
	}
	r.Use(fakeAuth, rateLimit(limiters, func() time.Time { return now }))
	r.GET("/api/search", func(c *gin.Context) { c.String(http.StatusOK, clientKey(c)) })

	send := func(label, peer, xff, auth string) {
		req := httptest.NewRequest("GET", "/api/search", nil)
		req.RemoteAddr = peer + ":40000"
		if xff != "" {
			req.Header.Set("X-Forwarded-For", xff)
		}
		if auth != "" {
			req.Header.Set("Authorization", auth)
		}
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		line := fmt.Sprintf("t=%v %s: %d %s", now.Sub(start), label, w.Code, w.Body.String())
		if ra := w.Header().Get("Retry-After"); ra != "" {
			line += " Retry-After=" + ra
		}
		fmt.Println(line)
	}

	for range 3 {
		send("user-17", "192.0.2.1", "198.51.100.7", "Bearer t-user-17")
	}
	send("anonymous via proxy", "192.0.2.1", "198.51.100.7", "")
	for _, spoof := range []string{"10.0.0.1", "10.0.0.2", "10.0.0.3"} {
		send("direct, spoofed XFF "+spoof, "203.0.113.9", spoof, "")
	}
	now = start.Add(time.Second)
	send("user-17", "192.0.2.1", "198.51.100.7", "Bearer t-user-17")
	send("new client", "192.0.2.1", "198.51.100.8", "")
	fmt.Println("buckets:", strings.Join(limiters.Keys(), " "))
}
Read the code

get moves an existing bucket to the front of the LRU list, or creates a new one and evicts the back entry when the store is full. rateLimit calls ReserveN at the fake time. A positive delay means the bucket is empty, so the middleware calls CancelAt: otherwise the refused request would still hold a future token and the client would be charged twice. The delay is then rounded up to whole seconds for Retry-After. The third request from user-17 at t=0 is refused with Retry-After=1. The direct peer 203.0.113.9 is not a trusted proxy, so ClientIP ignores its forged X-Forwarded-For values and all three requests share one bucket. At t=1s user-17 has a token again; without the CancelAt call this request would also be refused, because the dropped reservation would still hold that token. The fourth key evicts the least recently used bucket, ip:198.51.100.7.

03

Choose a key clients cannot forge

The key decides who shares a bucket. A verified subject is the best key: it survives IP changes and maps to a quota a customer can understand, so authenticate before you limit and keep that check cheap. For anonymous endpoints such as login, sign-up and public search, the client address is the only signal, and it is only as trustworthy as your proxy configuration. With SetTrustedProxies covering exactly your load balancer, ClientIP returns the forwarded address. If every peer is trusted, a client can write any address into X-Forwarded-For and get a new bucket each time, as the trusted-proxies lesson shows. Even a correct address key is coarse. Many users behind one carrier NAT or office gateway share an address, and an IPv6 client can rotate through the prefix it was assigned, often a /64, so consider keying IPv6 by prefix. A login endpoint usually needs two limits: per account to slow password guessing, and per address to slow credential stuffing across many accounts.

04

Bound the map and know what eviction costs

Every new key allocates a limiter, so an unbounded map lets anyone who can vary the key grow your heap without limit. The LRU list caps the store with constant-time updates. Eviction has a price: an evicted client comes back with a full bucket, so heavy key churn makes the limit looser, never stricter. That is the right direction to fail for availability, but it means the cap must comfortably exceed the number of clients active at once. A bucket that has been idle for burst divided by rate seconds has refilled completely and behaves exactly like a new one, so dropping those entries loses nothing; a periodic sweep of idle entries keeps the LRU from pushing out active clients. The store also lives in one process. Behind a round-robin balancer, N replicas give each client roughly N times the configured rate. A global quota needs shared state, for example Redis updated atomically, at the cost of a network round trip per request.

05

What a refused client should see

Answer 429 Too Many Requests, defined in RFC 6585, with Retry-After in whole seconds, rounded up, because a client that retries early is simply refused again. RFC 9110 allows either a number of seconds or an HTTP date; seconds avoid clock-skew problems. Keep the refusal cheap: the goal is to shed work, so do not run the handler, and at high volume count refusals per route instead of writing a full log line for each one. Well-behaved clients add jitter to their retries so they do not return in lockstep. A per-client limit is not overload protection. When the whole service is saturated, a global concurrency limit that answers 503 protects capacity even though every client is within its own quota. Test a burst followed by a refusal, a refill after the advertised Retry-After, independent buckets, forged forwarding headers, eviction at the cap, and concurrent requests under the race detector.

TAKE THIS WITH YOU

Key buckets by a verified identity, or by ClientIP only with trusted proxies configured. Bound the map and accept that eviction loosens limits, drive the limiter with explicit times, and refuse with 429 and a rounded-up Retry-After after canceling the unused reservation.

Check your understanding

The middleware calls ReserveN, sees a positive delay and answers 429 without waiting. Why should it call CancelAt on the reservation?

Go to the source

Progress stays in this browser. No account needed.