Rate Limiter
Rate Limiter
Section titled “Rate Limiter”go-zero provides a token-bucket rate limiter that works both in HTTP middleware and standalone.
HTTP Service Configuration
Section titled “HTTP Service Configuration”MaxConns: 10000 # max concurrent connectionsAdd the rate-limit middleware in the API spec:
@server ( middleware: RateLimit)service api { @handler CreateOrder post /orders (OrderReq) returns (OrderResp)}Standalone Rate Limiter
Section titled “Standalone Rate Limiter”import "github.com/zeromicro/go-zero/core/limit"
// Token bucket: 100 requests per second, burst of 200limiter := limit.NewTokenLimiter(100, 200, store, "api:rate")
if limiter.Allow() { // process request} else { httpx.Error(w, errorx.NewCodeError(429, "too many requests"))}Period Limiter (Fixed Window)
Section titled “Period Limiter (Fixed Window)”// 1000 requests per hour per userlimiter := limit.NewPeriodLimit(3600, 1000, store, "user:rate:")
code, err := limiter.Take("user:42")switch code {case limit.Allowed: // processcase limit.HitQuota: // last allowed request; warn usercase limit.OverQuota: // rejected}