Documentation
¶
Overview ¶
Package ratelimit provides small, reusable rate-limiting primitives built on top of the standard golang.org/x/time/rate token-bucket limiter.
Rate limiting is enforced in one of two ways, and this package offers one type for each:
- Pacer shapes traffic: it delays calls so a resource with a known rate limit (e.g. an API capped at N req/s) is never called faster than that limit. Use it on calls you make to someone else.
- Cooldown polices traffic: it rejects a repeat action on the same key that arrives before its interval has elapsed. Use it on calls others make to you.
Neither type is tied to any particular transport or caller; wire them up where needed and translate the result into whatever response shape (HTTP 503/429 + Retry-After, etc.) is appropriate for that caller.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func RetryAfter ¶
RetryAfter reports whether err is (or wraps) an ErrLimited and, if so, how long the caller should wait. It lets any package translate a rate-limit failure into its own response without importing whichever package produced the error.
func RetryAfterSeconds ¶
RetryAfterSeconds converts d into whole seconds for a Retry-After header, rounding up so the value never advertises a shorter wait than the limiter actually enforces.
Types ¶
type Cooldown ¶
type Cooldown struct {
// contains filtered or unexported fields
}
Cooldown rejects repeated actions on the same key that arrive less than interval apart (e.g. "this API may be called for a given resource once every N minutes"). Unlike Pacer it never delays a caller: an action is either allowed now or refused with the wait time. It is implemented as one rate.Limiter (burst 1) per key.
func NewCooldown ¶
NewCooldown creates a Cooldown enforcing interval between allowed calls per key. Entries unused for longer than maxAge are periodically evicted (checked every cleanupInterval) to bound memory; pass maxAge or cleanupInterval as 0 to disable cleanup (e.g. for short-lived Cooldowns such as in tests).
type ErrLimited ¶
ErrLimited reports that a call was refused because a rate limit would otherwise be exceeded. RetryAfter is how long the caller should wait before trying again.
func (*ErrLimited) Error ¶
func (e *ErrLimited) Error() string
type Pacer ¶
type Pacer struct {
// contains filtered or unexported fields
}
Pacer spaces out calls to a resource with a fixed, known rate limit. Callers wait their turn rather than being rejected, so a burst is spread over time instead of failing.
Architecture: [callers] -> [token bucket: one call per interval] -> [resource]