LogoPly
Middleware

Rate Limit

In-memory token bucket rate limiting per client.

Rate Limit

middleware.RateLimit limits requests per client with a token bucket.

app.Use(middleware.RateLimit(100, time.Minute))

The example allows a burst of 100 requests per minute. The bucket refills continuously at limit / window tokens per second.

Options

app.Use(middleware.RateLimit(20, 10*time.Second, middleware.RateLimitOptions{
	TrustForwarded: true,
}))
OptionDefaultDescription
TrustForwardedfalseRead the client IP from the first X-Forwarded-For value

When the limit is exceeded, the response is:

HTTP/1.1 429 Too Many Requests
Retry-After: 60

The body is rate limit exceeded.

Client identity

By default the limiter uses the TCP peer address from RemoteIP(). Set TrustForwarded only when Ply runs behind a proxy you control that overwrites X-Forwarded-For:

app.Use(middleware.RateLimit(100, time.Minute, middleware.RateLimitOptions{
	TrustForwarded: true,
}))

If clients can reach the server directly, they can spoof X-Forwarded-For and bypass the limit.

Scope and limits

  • State lives in memory in the current process.
  • Each instance has its own counters. A load-balanced deployment enforces the limit per instance, not globally.
  • Old buckets are removed during request handling after one window of inactivity.
  • Use a shared store such as Redis when a global limit is required.
  • The limiter is keyed only by IP. For per-user limits, wrap it with a custom handler that checks c.GetSession after authentication, or use a different middleware.

Ordering

Place the limiter before expensive handlers and before authentication when you want to limit unauthenticated traffic too:

app.Use(
	middleware.RequestID(),
	middleware.RateLimit(60, time.Minute),
	middleware.Logger(),
)