Documentation

Rate Limiting

Token-bucket rate limiting with per-IP tracking, path-based rules, automatic cleanup, and bandwidth limiting.

Overview

ALOS provides a high-performance rate limiting system based on fixed-window counters per client IP. Rate limits are enforced per client IP with support for path-based rules, automatic blocking, custom limit responses, and dynamic rule management. The system supports two levels of custom responses: per-rule callbacks via OnLimit on individual rules, and a global fallback via s.OnRateLimit().

Fixed Window

Each client gets a request counter that resets when the window expires. Bandwidth limiting uses token buckets separately.

Per-IP Tracking

Limits tracked per source IP with sharded concurrent maps. Integrates with Real IP middleware for proxy-aware resolution.

Auto Cleanup

Expired buckets are automatically pruned. Blocked IPs auto-unblock after the configured duration.

Two-Level Handlers

Per-rule OnLimit callbacks for route-specific responses plus a global s.OnRateLimit() fallback for all rules.

Pattern Matching

Three pattern types: exact paths, prefix with /* wildcard, and regex with ~ prefix. Most specific match wins.

Bandwidth Control

Separate bandwidth limiting with per-connection and global throttling for upload and download.

Basic Setup

Enable rate limiting by adding rules to your server. Each rule specifies a path pattern, a request limit, a time window, and how long to block offending IPs:

go
s := core.New(core.Config{Addr: ":443"})

s.SetRateLimitRules([]core.RateLimitRule{
    {
        Path:     "/api/*",
        MaxReqs:  100,
        Window:   60 * time.Second,
        BlockFor: 5 * time.Minute,
    },
})

When a client at a given IP exceeds 100 requests to any path under /api/ within a 60-second window, they are blocked for 5 minutes. During the block, all requests from that IP matching the rule are rejected with a 429 status.

go
s.SetRateLimitRules([]core.RateLimitRule{
    {
        Path:     "/api/*",
        MaxReqs:  100,
        Window:   60 * time.Second,
        BlockFor: 5 * time.Minute,
    },
    {
        Path:     "/health",
        MaxReqs:  1000,
        Window:   60 * time.Second,
        BlockFor: 30 * time.Second,
    },
    {
        Path:     "/*",
        MaxReqs:  300,
        Window:   60 * time.Second,
        BlockFor: 2 * time.Minute,
    },
})

Rules are matched by specificity: the most specific path wins. An exact match like /health takes priority over a prefix match like /*. This means you can set a generous limit for health checks while keeping a tighter global limit.

Per-IP Connection Limit

Separate from request rate limiting, MaxConnsPerIP caps how many concurrent connections a single client IP may hold open. It is a server Config option (not part of the rate-limit engine) and defaults to 20 per IP. Connections beyond the limit are refused with 429 Too Many Connections and closed.

go
s := core.New(core.Config{
    ProxyMode:     true,
    MaxConnsPerIP: 20,
})

The limit is keyed by client IP the same way the rate limiter is: when ProxyMode (or TrustedProxies) is set it uses the real client IP from X-Forwarded-For / X-Real-IP after the proxy rewrite; otherwise it uses the socket peer IP checked at accept time. Tracking uses lock-free ALOS typed maps (pre-allocated for 128 IPs). Set 0 to keep the default of 20, or a negative value to disable it.

Behind Cloudflare or another connection-reusing proxy, a single upstream connection can carry requests from many clients, so the per-IP connection limit is attributed by the connection's first real client IP. For fine-grained abuse control behind such a proxy, pair it with per-IP request rate limiting and MaxRequestsPerIP.

Rate Limit Rules

The RateLimitRule struct defines a rate limit:

FieldTypeDescription
PathstringPath pattern to match: exact /login, prefix /api/*, or regex ~^/users/\d+$
MaxReqsint64Maximum number of requests allowed within the time window
Windowtime.DurationTime window for counting requests (e.g. 60 * time.Second)
BlockFortime.DurationHow long to block the IP after exceeding the limit (e.g. 5 * time.Minute)
OnLimitRateLimitFuncPer-rule callback when this specific rule triggers. Signature: func(event RateLimitEvent, req *Request, resp *Response) bool. Return true if handled.
go
type RateLimitRule struct {
    Path     string
    MaxReqs  int64
    Window   time.Duration
    BlockFor time.Duration
    OnLimit  RateLimitFunc
}

type RateLimitFunc func(event RateLimitEvent, req *Request, resp *Response) bool

Path Patterns

Three matching modes are supported. The engine picks the most specific match for each request:

TypeSyntaxExampleMatches
ExactFull path, no wildcard/loginOnly /login (highest priority)
ExactFull path/healthOnly /health
PrefixPath with /*/api/*/api/users, /api/posts/1, etc.
PrefixCatch-all/*All paths (lowest priority prefix)
RegexStarts with ~~^/users/\d+$/users/123, /users/456
RegexStarts with ~~^/api/v[0-9]+/admin/api/v1/admin, /api/v2/admin/users
go
s.SetRateLimitRules([]core.RateLimitRule{
    {Path: "/login", MaxReqs: 5, Window: 60 * time.Second, BlockFor: 10 * time.Minute},
    {Path: "/api/*", MaxReqs: 100, Window: 60 * time.Second, BlockFor: 5 * time.Minute},
    {Path: "~^/users/\\d+$", MaxReqs: 50, Window: 60 * time.Second, BlockFor: 1 * time.Minute},
    {Path: "/health", MaxReqs: 1000, Window: 60 * time.Second, BlockFor: 30 * time.Second},
    {Path: "/*", MaxReqs: 300, Window: 60 * time.Second, BlockFor: 2 * time.Minute},
})

Specificity order: Exact match > Prefix match (longer path first) > Regex match (by pattern length). A request to /health will always use the exact /health rule, never the /* catch-all.

Per-Rule Handlers (OnLimit)

Each rule can have its own OnLimit callback that fires when that specific rule is triggered. The callback receives a RateLimitEvent with full context about the violation. Return true to indicate the response was handled.

JSON API Response

go
s.SetRateLimitRules([]core.RateLimitRule{
    {
        Path:     "/api/*",
        MaxReqs:  100,
        Window:   60 * time.Second,
        BlockFor: 5 * time.Minute,
        OnLimit: func(event core.RateLimitEvent, req *core.Request, resp *core.Response) bool {
            var buf [64]byte
            b := buf[:0]
            b = append(b, `{"error":"api rate limited","retry_after":`...)
            b = strconv.AppendInt(b, int64(event.RetryAfter.Seconds())+1, 10)
            b = append(b, '}')
            resp.Status(429).JSON(b)
            return true
        },
    },
})

HTML Error Page

go
{
    Path:     "/login",
    MaxReqs:  5,
    Window:   60 * time.Second,
    BlockFor: 10 * time.Minute,
    OnLimit: func(event core.RateLimitEvent, req *core.Request, resp *core.Response) bool {
        var buf [256]byte
        b := buf[:0]
        b = append(b, `<h1>Too Many Login Attempts</h1><p>Try again in `...)
        b = strconv.AppendInt(b, int64(event.RetryAfter.Seconds())+1, 10)
        b = append(b, ` seconds.</p>`...)
        resp.Status(429).HTML(string(b))
        return true
    },
},

Logging Without Custom Body

go
{
    Path:     "~^/users/\\d+$",
    MaxReqs:  50,
    Window:   60 * time.Second,
    BlockFor: 1 * time.Minute,
    OnLimit: func(event core.RateLimitEvent, req *core.Request, resp *core.Response) bool {
        log.Printf("rate limit hit: ip=%s path=%s", event.IP, event.Path)
        return false
    },
},

Returning false from OnLimit means the response was not handled. ALOS will fall through to the global handler, or if none is set, send a default 429 response.

Global Rate Limit Handler (s.OnRateLimit)

The global handler is a catch-all that fires for any rate limit violation that hasn't been handled by a per-rule OnLimit. This is where you put logging, metrics, and default error responses. Set it once on the server:

go
s.OnRateLimit(func(event core.RateLimitEvent, req *core.Request, resp *core.Response) bool {
    log.Printf("[RATE-LIMIT] ip=%s path=%s rule=%s retry_after=%s",
        event.IP, event.Path, event.Rule.Path, event.RetryAfter)
    var buf [256]byte
    b := buf[:0]
    b = append(b, `<html><body><h1>Slow Down</h1><p>Too many requests. Try again in `...)
    b = strconv.AppendInt(b, int64(event.RetryAfter.Seconds())+1, 10)
    b = append(b, ` seconds.</p></body></html>`...)
    resp.Status(429).HTML(string(b))
    return true
})

How the Two Levels Interact

When a rate limit is triggered, ALOS follows this order:

  1. Per-rule OnLimit - If the matched rule has an OnLimit callback, it runs first. If it returns true, the request is fully handled.
  2. Global s.OnRateLimit - If the per-rule handler returned false or there is no per-rule handler, the global handler runs. If it returns true, the request is handled.
  3. Default 429 - If neither handler existed or both returned false, ALOS sends a plain 429 Too Many Requests response.

Combined Example

API routes get a JSON error, everything else falls through to the global HTML handler:

go
s.SetRateLimitRules([]core.RateLimitRule{
    {
        Path: "/api/*", MaxReqs: 100, Window: 60 * time.Second, BlockFor: 5 * time.Minute,
        OnLimit: func(event core.RateLimitEvent, req *core.Request, resp *core.Response) bool {
            var buf [64]byte
            b := buf[:0]
            b = append(b, `{"error":"api rate limited","retry_after":`...)
            b = strconv.AppendInt(b, int64(event.RetryAfter.Seconds())+1, 10)
            b = append(b, '}')
            resp.Status(429).JSON(b)
            return true
        },
    },
    {Path: "/health", MaxReqs: 1000, Window: 60 * time.Second, BlockFor: 30 * time.Second},
    {Path: "/*", MaxReqs: 300, Window: 60 * time.Second, BlockFor: 2 * time.Minute},
})

s.OnRateLimit(func(event core.RateLimitEvent, req *core.Request, resp *core.Response) bool {
    log.Printf("[RATE-LIMIT] ip=%s path=%s rule=%s retry_after=%s",
        event.IP, event.Path, event.Rule.Path, event.RetryAfter)
    var buf [256]byte
    b := buf[:0]
    b = append(b, `<html><body><h1>Slow Down</h1><p>Too many requests. Try again in `...)
    b = strconv.AppendInt(b, int64(event.RetryAfter.Seconds())+1, 10)
    b = append(b, ` seconds.</p></body></html>`...)
    resp.Status(429).HTML(string(b))
    return true
})

RateLimitEvent

Both per-rule and global handlers receive a RateLimitEvent with full context about the violation:

FieldTypeDescription
IPstringClient IP address that triggered the limit
PathstringThe actual request path (e.g. /api/users/123)
RuleRateLimitRuleThe rule that was matched. Access event.Rule.Path, event.Rule.MaxReqs, etc.
RetryAftertime.DurationHow long until the block expires. Use event.RetryAfter.Seconds() for the numeric value
go
type RateLimitEvent struct {
    IP         string
    Path       string
    Rule       RateLimitRule
    RetryAfter time.Duration
}

Using Event Fields

go
OnLimit: func(event core.RateLimitEvent, req *core.Request, resp *core.Response) bool {
    log.Printf("ip=%s hit rule=%s (max=%d/%s) path=%s retry=%s",
        event.IP,
        event.Rule.Path,
        event.Rule.MaxReqs,
        event.Rule.Window,
        event.Path,
        event.RetryAfter,
    )
    resp.Status(429).SetHeader("Retry-After", strconv.Itoa(int(event.RetryAfter.Seconds())+1))
    resp.JSON([]byte(`{"error":"rate limited"}`))
    return true
},

Engine API

Manage rules dynamically at runtime. Rules can be added, removed, or replaced while the server is running without any downtime:

MethodDescription
s.SetRateLimitRules([]RateLimitRule)Replace all rules at once (atomic swap)
s.AddRateLimitRule(RateLimitRule)Upsert a single rule (replaces any existing rule with the same path)
s.RemoveRateLimitRule(path string)Remove a rule by its path pattern
s.OnRateLimit(fn RateLimitFunc)Set the global rate limit handler (called when no per-rule handler handles the event)

Adding Rules at Runtime

go
s.AddRateLimitRule(core.RateLimitRule{
    Path:     "/webhook",
    MaxReqs:  20,
    Window:   60 * time.Second,
    BlockFor: 5 * time.Minute,
})

Removing Rules

go
s.RemoveRateLimitRule("/webhook")

Replacing All Rules

go
s.SetRateLimitRules([]core.RateLimitRule{
    {Path: "/api/*", MaxReqs: 200, Window: 60 * time.Second, BlockFor: 5 * time.Minute},
    {Path: "/*", MaxReqs: 500, Window: 60 * time.Second, BlockFor: 1 * time.Minute},
})

Admin Endpoint Pattern

You can build an admin API to manage rate limits at runtime:

go
admin := s.Router.Group("/admin", authMiddleware)

admin.POST("/rate-limit", func(req *core.Request, resp *core.Response) {
    s.AddRateLimitRule(core.RateLimitRule{
        Path:     "/api/heavy/*",
        MaxReqs:  10,
        Window:   60 * time.Second,
        BlockFor: 10 * time.Minute,
    })
    resp.Status(200).JSONString(`{"status":"rule added"}`)
})

admin.DELETE("/rate-limit/:path", func(req *core.Request, resp *core.Response) {
    s.RemoveRateLimitRule(req.ParamValue("path"))
    resp.Status(200).JSONString(`{"status":"rule removed"}`)
})

Inline Route Limiting

The simplest way to rate limit a single route. Chain .Limit() directly on the route definition. No middleware setup required:

go
s.Router.GET("/api/data", handler).Limit(100, time.Minute)

This limits the route to 100 requests per minute per client IP. When exceeded, ALOS returns a 429 Too Many Requests with a Retry-After header.

API

MethodDescription
.Limit(maxReqs int64, window time.Duration)Rate limit by client IP. Returns the route for further chaining.
.LimitByKey(maxReqs int64, window time.Duration, keyFunc func(*Request) string)Rate limit by a custom key extracted from the request.

Examples

go
s.Router.POST("/login", loginHandler).Limit(5, time.Minute)

s.Router.GET("/api/search", searchHandler).Limit(30, 10 * time.Second)

s.Router.POST("/api/upload", uploadHandler).Limit(10, 5 * time.Minute)

Custom Key

Use .LimitByKey() to rate limit by something other than client IP, for example an API key or user ID:

go
s.Router.GET("/api/data", dataHandler).LimitByKey(100, time.Minute,
    func(req *core.Request) string {
        return req.Header("X-API-Key")
    },
)

.Limit() and .LimitByKey() each create an independent limiter for that route. They use the same fixed-window engine as RateLimitMiddleware under the hood. For more control (groups, shared state, blocking duration), use server-level rules or the middleware approach below.

Per-Route Rate Limiting

The simplest way to rate limit a single route is to chain .Limit() or .LimitByKey() directly onto the route returned by GET, POST, Handle, and friends. Both return the *Route, so they chain fluently.

MethodDescription
.Limit(maxRequests int64, window time.Duration)Rate limit this single route, keyed by client IP. Falls back to 100 requests if maxRequests <= 0 and time.Minute if window <= 0. Returns the *Route for chaining.
.LimitByKey(maxRequests int64, window time.Duration, keyFunc func(*Request) string)Same as .Limit() but keys the limiter by your own function (API key, user ID, tenant, etc.) instead of client IP.
go
s.Router.GET("/api/data", dataHandler).Limit(100, time.Minute)

s.Router.POST("/login", loginHandler).Limit(5, time.Minute)

s.Router.GET("/api/user", userHandler).LimitByKey(60, time.Minute, func(req *core.Request) string {
    return req.Header("X-API-Key")
})

When the limit is exceeded, the client is blocked for a fixed 30 seconds (independent of the counting window). Every request during that cooldown gets a 429 Too Many Requests with a Retry-After header counting down the remaining seconds; after 30 seconds the counter resets and the client may try again. The 30s block does not extend on repeated hits. Each .Limit() / .LimitByKey() call attaches an independent limiter to that one route. Under the hood they are a thin wrapper over RateLimitMiddleware (below), and when the limit trips they run through your global s.OnRateLimit() handler (if one is registered) before falling back to the default 429, so route-level limits get the same custom responses as server-level rules.

Per-IP limits key on RemoteAddr, the socket peer. Behind a reverse proxy or load balancer every request would otherwise share the proxy's IP. Set ProxyMode: true in the server config (or list specific TrustedProxies) so ALOS rewrites RemoteAddr to the real client IP from X-Forwarded-For / X-Real-IP before any limiter runs.

RateLimitMiddleware (manual / per-group)

RateLimitMiddleware is a standard middleware function that creates an independent rate limiter with its own state. This is different from the server-level rate limiting configured via s.SetRateLimitRules - it can be applied per-route or per-group using Use() or Chain().

go
func RateLimitMiddleware(cfg RateLimitMiddlewareConfig) MiddlewareFunc
FieldTypeDescription
MaxRequestsint64Maximum requests allowed within the time window
Windowtime.DurationTime window for the fixed-window counter
KeyFuncfunc(*Request) stringExtracts the rate limit key from the request. Defaults to client IP from RemoteAddr if nil. (Enable ProxyMode so RemoteAddr is the real client IP behind a proxy.)
OnLimitRateLimitFuncCallback invoked when the limit is exceeded, before the default 429. Return true if it wrote the response. Route-level .Limit() / .LimitByKey() auto-wire this to your global s.OnRateLimit() handler.

Each call to RateLimitMiddleware creates an independent limiter with its own counter state. When the limit is exceeded, it invokes OnLimit (if set) and otherwise blocks the client for a fixed 30 seconds, sending a 429 Too Many Requests response with a Retry-After header for each request during the cooldown.

Server-Level vs. Middleware

AspectServer-Level (SetRateLimitRules)Middleware (RateLimitMiddleware)
ScopeCentralized, path-pattern matching across all routesPer-route or per-group, applied where you attach it
StateShared engine with sharded mapsIndependent instance per call
BlockingConfigurable BlockFor duration after exceeding limitFixed 30-second block after exceeding the limit
PatternsExact, prefix (/*), and regex (~)Applied to whatever routes the middleware is attached to

Both Approaches Together

Server-level rules provide a global safety net, while middleware instances add tighter limits on specific routes or groups:

go
s.SetRateLimitRules([]core.RateLimitRule{
    {Path: "/*", MaxReqs: 1000, Window: time.Minute},
})

api := s.Router.Group("/api")
api.Use(core.RateLimitMiddleware(core.RateLimitMiddlewareConfig{
    MaxRequests: 100,
    Window:      time.Minute,
}))

s.Router.POST("/login", core.Chain(loginHandler,
    core.RateLimitMiddleware(core.RateLimitMiddlewareConfig{
        MaxRequests: 5,
        Window:      time.Minute,
    }),
))

In this example, the server-level rule allows 1000 requests per minute globally. The /api group has its own independent 100 req/min limiter. The /login route has a strict 5 req/min limiter. A request to /api/users must pass both the server-level check and the group middleware check independently.

Custom Key Function

Override the default per-IP keying to rate limit by API key, user ID, or any other request attribute:

go
api.Use(core.RateLimitMiddleware(core.RateLimitMiddlewareConfig{
    MaxRequests: 100,
    Window:      time.Minute,
    KeyFunc: func(req *core.Request) string {
        return req.Header("X-API-Key")
    },
}))

Each RateLimitMiddleware call creates a completely independent limiter. Two groups using the same config will track their counters separately, so exceeding the limit on one does not affect the other.

Bandwidth Limiting

Separate from request rate limiting, bandwidth limiting controls the actual data transfer speed. ALOS uses BandwidthConfig for per-connection and global throttling:

FieldTypeDescription
MaxUploadRateint64Max upload speed in Mbps (0 = unlimited)
MaxDownloadRateint64Max download speed in Mbps (0 = unlimited)
BurstSizeint64Burst allowance in Mbps (token bucket max tokens)
go
s := core.New(core.Config{
    Addr: ":443",

    ConnBandwidth: core.BandwidthConfig{
        MaxUploadRate:   8,
        MaxDownloadRate: 40,
        BurstSize:       16,
    },

    GlobalBandwidth: core.BandwidthConfig{
        MaxUploadRate:   400,
        MaxDownloadRate: 1600,
        BurstSize:       800,
    },
})

This creates a server-wide ConnectionLimiter (8 Mbps up, 40 Mbps down with 16 Mbps burst) and a GlobalLimiter for server-wide throttling (400 Mbps up, 1600 Mbps down with 800 Mbps burst). Both use token-bucket algorithms internally.

Connection vs Global: Per-connection limits prevent any single client from hogging bandwidth, while the global limit ensures total server throughput stays within your infrastructure capacity.

File Download Rate Limiting

For file downloads via SendFile, you can set a per-download speed limit in megabits per second (1-250,000 Mbps):

Runtime note: SendFile runs on the custom Linux epoll backend and streams the file to the client.

go
s.Router.GET("/download/:file", func(req *core.Request, resp *core.Response) {
    resp.SendFile(
        "./files/" + req.ParamValue("file"),
        core.WithAttachment("download.zip"),
        core.WithRateLimit(50),
    )
})
OptionDescription
WithRateLimit(mbps int64)Throttle download speed. Range: 1-250,000 Mbps. Internally converts to bytes/sec (mbps * 125000).
WithRateLimitBurst(mbps, burstMbps int64)Same as WithRateLimit but with a custom burst size in Mbps. Allows initial burst before throttling kicks in.

With Custom Burst

go
resp.SendFile(
    "./files/large-archive.tar.gz",
    core.WithAttachment("large-archive.tar.gz"),
    core.WithRateLimitBurst(100, 400),
)

This allows an initial burst at 400 Mbps, then throttles to 100 Mbps for the remainder.

Production Example

A complete production rate limiting setup with multiple rules, per-rule API handler, and a global HTML fallback:

go
s.SetRateLimitRules([]core.RateLimitRule{
    {
        Path:     "/api/*",
        MaxReqs:  100,
        Window:   60 * time.Second,
        BlockFor: 5 * time.Minute,
        OnLimit: func(event core.RateLimitEvent, req *core.Request, resp *core.Response) bool {
            var buf [64]byte
            b := buf[:0]
            b = append(b, `{"error":"api rate limited","retry_after":`...)
            b = strconv.AppendInt(b, int64(event.RetryAfter.Seconds())+1, 10)
            b = append(b, '}')
            resp.Status(429).JSON(b)
            return true
        },
    },
    {
        Path:     "/health",
        MaxReqs:  1000,
        Window:   60 * time.Second,
        BlockFor: 30 * time.Second,
    },
    {
        Path:     "~^/users/\\d+$",
        MaxReqs:  50,
        Window:   60 * time.Second,
        BlockFor: 1 * time.Minute,
    },
    {
        Path:     "/*",
        MaxReqs:  300,
        Window:   60 * time.Second,
        BlockFor: 2 * time.Minute,
    },
})

s.OnRateLimit(func(event core.RateLimitEvent, req *core.Request, resp *core.Response) bool {
    log.Printf("[RATE-LIMIT] ip=%s path=%s rule=%s retry_after=%s",
        event.IP, event.Path, event.Rule.Path, event.RetryAfter)
    var buf [256]byte
    b := buf[:0]
    b = append(b, `<html><body><h1>Slow Down</h1><p>Too many requests. Try again in `...)
    b = strconv.AppendInt(b, int64(event.RetryAfter.Seconds())+1, 10)
    b = append(b, ` seconds.</p></body></html>`...)
    resp.Status(429).HTML(string(b))
    return true
})