Documentation
¶
Overview ¶
Package ratelimit limits the requests of each client with a token bucket per key, in memory and bounded: an idle bucket is forgotten, and the number of buckets is capped. A spent request can be given back, which golang.org/x/time/rate cannot do once time has passed (Reservation.CancelAt restores nothing after the time to act).
Index ¶
Constants ¶
const DefaultMaxKeys = 100_000
DefaultMaxKeys is a cap on the keys a Limiter tracks at once: 17 MB of heap, as measured with IPv6 prefixes as keys.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Decision ¶
type Decision struct {
// Allowed reports whether the request may be served.
Allowed bool
// Remaining is the number of requests the client may still send now.
Remaining int
// Reset is how long until one more request is restored, rounded up to
// the second: within it, the client may send no more than Remaining.
// It is zero when the whole quota is available.
Reset time.Duration
// Full reports a key refused only because the Limiter already keeps
// as many keys as it may: the key itself spent nothing.
Full bool
}
Decision is the answer of a Limiter to one request.
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter applies a Policy to each key on its own. It is safe for concurrent use.
func PerMinute ¶ added in v0.41.0
PerMinute returns a limiter allowing each client n requests a minute, keeping at most DefaultMaxKeys clients.
func (*Limiter) Allow ¶
Allow spends one request of key. A key l does not know yet while it already keeps maxKeys buckets is refused for a whole window: memory stays bounded, and the keys already known keep their quota.
func (*Limiter) Refund ¶ added in v0.41.0
Refund gives back one request of key, spent by Allow, up to the quota. A key l does not know has its whole quota: Refund keeps nothing for it. A refunded bucket is kept until the sweep, so that a client whose requests are all refunded does not allocate one on each.
type Policy ¶
type Policy struct {
// Quota is the number of requests of a window, at least one.
Quota int
// Window is the period over which Quota is restored, at least one
// second.
Window time.Duration
}
Policy is a quota of requests per window. A client may spend the whole quota at once; it is then restored at an even pace over the window.