Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท Authentication and Security

Rate Limiting and Input Safety in Gin

Protect a Gin API from abuse: a token-bucket rate limiter middleware, request body size limits, timeouts, safe validation and the rules that keep untrusted input harmless.

Authentication answers "who are you?". It does not stop a client, friendly or hostile, from calling your login endpoint ten thousand times a minute, uploading a 4 GB JSON body, or sending strings designed to break your queries. This lesson covers the cheap, high-value defenses every public Gin service needs: rate limiting, size and time limits, and disciplined handling of untrusted input.

As elsewhere in this chapter, Gin is not available in the in-page runner. The Gin code is read-only. The runnable examples implement the same ideas with net/http, httptest and a fake clock so the output is deterministic.

Why rate limit

A rate limiter caps how many requests one client may make in a period. It protects login and password-reset routes from guessing attacks, keeps one noisy client from starving others, and limits the bill when each request costs money (email, SMS, a paid API). Return 429 Too Many Requests and, ideally, a Retry-After header.

The token bucket

The most common algorithm is the token bucket. Each client owns a bucket that holds up to burst tokens and refills at rate tokens per second. Every request takes one token; when the bucket is empty, the request is rejected. Bursts are allowed (a full bucket), but the long-run average cannot exceed the refill rate.

flowchart LR
  R["Refill: rate tokens per second"] --> B["Bucket<br/>capacity = burst"]
  Q["Request"] --> C{"Token available?"}
  B --> C
  C -- "yes: take one" --> OK["200 OK"]
  C -- "no" --> NO["429 + Retry-After"]
Go A token bucket with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first three requests pass, the next two are rejected, and half a second later exactly one token is back. After a quiet period the bucket refills to the burst size, never beyond.

A per-client middleware

Real limiters keep one bucket per client, usually keyed by IP address (or by user ID or API key after authentication). Store them in a map protected by a mutex, and remove idle ones so the map cannot grow forever.

Go Per-IP rate limiting middleware with httptest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Alice is limited, Bob is not affected, and Alice recovers after the clock moves forward. In production the key is c.ClientIP(). Be careful with it: behind a proxy or load balancer, the real client address arrives in X-Forwarded-For, and you must tell Gin which proxies to trust with r.SetTrustedProxies([]string{"10.0.0.0/8"}). Otherwise either everyone shares the proxy's address or clients can spoof the header and dodge your limit.

The Gin version

With the real libraries the middleware is short. golang.org/x/time/rate provides the token bucket; you keep a map of limiters.

Go
func RateLimit(r rate.Limit, burst int) gin.HandlerFunc {
	var mu sync.Mutex
	limiters := map[string]*rate.Limiter{}

	return func(c *gin.Context) {
		ip := c.ClientIP()
		mu.Lock()
		l, ok := limiters[ip]
		if !ok {
			l = rate.NewLimiter(r, burst)
			limiters[ip] = l
		}
		mu.Unlock()

		if !l.Allow() {
			c.Header("Retry-After", "1")
			c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "too many requests"})
			return
		}
		c.Next()
	}
}

// Stricter limit just for login:
auth := r.Group("/auth", RateLimit(rate.Every(12*time.Second), 5))

Apply a generous global limit and a much stricter one on /login, /register and /password/reset. An in-memory limiter only protects a single instance; with several servers, keep counters in Redis or enforce limits at the edge (a CDN, API gateway or reverse proxy). See Middleware in Gin for how middleware is chained and aborted.

Limit body size and time

Limit what a client can make you read and how long you wait.

Go
// Cap every request body at 1 MiB
r.Use(func(c *gin.Context) {
	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 1<<20)
	c.Next()
})

// Multipart forms: memory before spilling to disk (default 32 MiB)
r.MaxMultipartMemory = 8 << 20

srv := &http.Server{
	Addr:              ":8080",
	Handler:           r,
	ReadHeaderTimeout: 5 * time.Second,
	ReadTimeout:       15 * time.Second,
	WriteTimeout:      30 * time.Second,
	IdleTimeout:       60 * time.Second,
	MaxHeaderBytes:    1 << 20,
}

ReadHeaderTimeout defeats "slowloris" clients that open connections and dribble bytes. r.Run uses an http.Server with no timeouts at all, so for public services create the server yourself, as above.

Go MaxBytesReader rejects oversized bodies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Treat all input as hostile

  • Validate shape and size with binding tags (binding:"required,email,max=254"), as in the Binding and Validation chapter. Bound every string, slice and number.
  • Use allow-lists. For sort columns, filter names and enum values, map the input to a known set instead of pasting it into SQL (see GORM Queries).
  • Parameterize queries. db.Where("email = ?", email) is safe; db.Where("email = '" + email + "'") is SQL injection.
  • Escape on output and let html/template do it. Never build HTML with string concatenation.
  • Do not trust files. Check size, sniff the content type with http.DetectContentType, generate your own filenames (see File Uploads and Downloads).
  • Fail quietly and generically. Login errors should say "invalid email or password", not which half was wrong, and errors must not leak stack traces or SQL.
  • Log, but never log secrets. Mask passwords, tokens and card numbers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a token bucket, what does the burst size control?

    The burst is the bucket capacity. The refill rate sets the long-run average.
  2. 2. Which status code should a rate limited request receive?

    429 is made for this, and it can be paired with a Retry-After header.
  3. 3. Why must you configure trusted proxies before keying a limiter on c.ClientIP()?

    ClientIP depends on knowing which hops to believe.
  4. 4. What does http.MaxBytesReader do when the body is bigger than the limit?

    Reads fail once the limit is exceeded, so you can answer 413.
  5. 5. Which is safe?

    Placeholders send the value separately from the SQL text, so it cannot change the query.

Summary

  • Rate limit with a token bucket per client, return 429 with Retry-After, and use strict limits on login and reset routes.
  • Configure trusted proxies so c.ClientIP() is trustworthy; use Redis or the edge when you run several instances.
  • Cap body sizes with MaxBytesReader and set http.Server timeouts; r.Run has none.
  • Validate with allow-lists, parameterize queries, escape output and never leak internals in errors.

Next: Testing Gin Handlers