1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package rate provides a rate limiter.
16 // Limit defines the maximum frequency of some events.
17 // Limit is represented as number of events per second.
18 // A zero Limit allows no events.
21 // Inf is the infinite rate limit; it allows all events (even if burst is zero).
22 const Inf = Limit(math.MaxFloat64)
24 // Every converts a minimum time interval between events to a Limit.
25 func Every(interval time.Duration) Limit {
29 return 1 / Limit(interval.Seconds())
32 // A Limiter controls how frequently events are allowed to happen.
33 // It implements a "token bucket" of size b, initially full and refilled
34 // at rate r tokens per second.
35 // Informally, in any large enough time interval, the Limiter limits the
36 // rate to r tokens per second, with a maximum burst size of b events.
37 // As a special case, if r == Inf (the infinite rate), b is ignored.
38 // See https://en.wikipedia.org/wiki/Token_bucket for more about token buckets.
40 // The zero value is a valid Limiter, but it will reject all events.
41 // Use NewLimiter to create non-zero Limiters.
43 // Limiter has three main methods, Allow, Reserve, and Wait.
44 // Most callers should use Wait.
46 // Each of the three methods consumes a single token.
47 // They differ in their behavior when no token is available.
48 // If no token is available, Allow returns false.
49 // If no token is available, Reserve returns a reservation for a future token
50 // and the amount of time the caller must wait before using it.
51 // If no token is available, Wait blocks until one can be obtained
52 // or its associated context.Context is canceled.
54 // The methods AllowN, ReserveN, and WaitN consume n tokens.
60 // last is the last time the limiter's tokens field was updated
62 // lastEvent is the latest time of a rate-limited event (past or future)
66 // Limit returns the maximum overall event rate.
67 func (lim *Limiter) Limit() Limit {
73 // Burst returns the maximum burst size. Burst is the maximum number of tokens
74 // that can be consumed in a single call to Allow, Reserve, or Wait, so higher
75 // Burst values allow more events to happen at once.
76 // A zero Burst allows no events, unless limit == Inf.
77 func (lim *Limiter) Burst() int {
83 // NewLimiter returns a new Limiter that allows events up to rate r and permits
84 // bursts of at most b tokens.
85 func NewLimiter(r Limit, b int) *Limiter {
92 // Allow is shorthand for AllowN(time.Now(), 1).
93 func (lim *Limiter) Allow() bool {
94 return lim.AllowN(time.Now(), 1)
97 // AllowN reports whether n events may happen at time now.
98 // Use this method if you intend to drop / skip events that exceed the rate limit.
99 // Otherwise use Reserve or Wait.
100 func (lim *Limiter) AllowN(now time.Time, n int) bool {
101 return lim.reserveN(now, n, 0).ok
104 // A Reservation holds information about events that are permitted by a Limiter to happen after a delay.
105 // A Reservation may be canceled, which may enable the Limiter to permit additional events.
106 type Reservation struct {
111 // This is the Limit at reservation time, it can change later.
115 // OK returns whether the limiter can provide the requested number of tokens
116 // within the maximum wait time. If OK is false, Delay returns InfDuration, and
117 // Cancel does nothing.
118 func (r *Reservation) OK() bool {
122 // Delay is shorthand for DelayFrom(time.Now()).
123 func (r *Reservation) Delay() time.Duration {
124 return r.DelayFrom(time.Now())
127 // InfDuration is the duration returned by Delay when a Reservation is not OK.
128 const InfDuration = time.Duration(1<<63 - 1)
130 // DelayFrom returns the duration for which the reservation holder must wait
131 // before taking the reserved action. Zero duration means act immediately.
132 // InfDuration means the limiter cannot grant the tokens requested in this
133 // Reservation within the maximum wait time.
134 func (r *Reservation) DelayFrom(now time.Time) time.Duration {
138 delay := r.timeToAct.Sub(now)
145 // Cancel is shorthand for CancelAt(time.Now()).
146 func (r *Reservation) Cancel() {
147 r.CancelAt(time.Now())
151 // CancelAt indicates that the reservation holder will not perform the reserved action
152 // and reverses the effects of this Reservation on the rate limit as much as possible,
153 // considering that other reservations may have already been made.
154 func (r *Reservation) CancelAt(now time.Time) {
160 defer r.lim.mu.Unlock()
162 if r.lim.limit == Inf || r.tokens == 0 || r.timeToAct.Before(now) {
166 // calculate tokens to restore
167 // The duration between lim.lastEvent and r.timeToAct tells us how many tokens were reserved
168 // after r was obtained. These tokens should not be restored.
169 restoreTokens := float64(r.tokens) - r.limit.tokensFromDuration(r.lim.lastEvent.Sub(r.timeToAct))
170 if restoreTokens <= 0 {
173 // advance time to now
174 now, _, tokens := r.lim.advance(now)
175 // calculate new number of tokens
176 tokens += restoreTokens
177 if burst := float64(r.lim.burst); tokens > burst {
182 r.lim.tokens = tokens
183 if r.timeToAct == r.lim.lastEvent {
184 prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens)))
185 if !prevEvent.Before(now) {
186 r.lim.lastEvent = prevEvent
193 // Reserve is shorthand for ReserveN(time.Now(), 1).
194 func (lim *Limiter) Reserve() *Reservation {
195 return lim.ReserveN(time.Now(), 1)
198 // ReserveN returns a Reservation that indicates how long the caller must wait before n events happen.
199 // The Limiter takes this Reservation into account when allowing future events.
200 // The returned Reservation’s OK() method returns false if n exceeds the Limiter's burst size.
202 // r := lim.ReserveN(time.Now(), 1)
204 // // Not allowed to act! Did you remember to set lim.burst to be > 0 ?
207 // time.Sleep(r.Delay())
209 // Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events.
210 // If you need to respect a deadline or cancel the delay, use Wait instead.
211 // To drop or skip events exceeding rate limit, use Allow instead.
212 func (lim *Limiter) ReserveN(now time.Time, n int) *Reservation {
213 r := lim.reserveN(now, n, InfDuration)
217 // Wait is shorthand for WaitN(ctx, 1).
218 func (lim *Limiter) Wait(ctx context.Context) (err error) {
219 return lim.WaitN(ctx, 1)
222 // WaitN blocks until lim permits n events to happen.
223 // It returns an error if n exceeds the Limiter's burst size, the Context is
224 // canceled, or the expected wait time exceeds the Context's Deadline.
225 // The burst limit is ignored if the rate limit is Inf.
226 func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
232 if n > burst && limit != Inf {
233 return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, burst)
235 // Check if ctx is already cancelled
241 // Determine wait limit
243 waitLimit := InfDuration
244 if deadline, ok := ctx.Deadline(); ok {
245 waitLimit = deadline.Sub(now)
248 r := lim.reserveN(now, n, waitLimit)
250 return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
253 delay := r.DelayFrom(now)
257 t := time.NewTimer(delay)
264 // Context was canceled before we could proceed. Cancel the
265 // reservation, which may permit other events to proceed sooner.
271 // SetLimit is shorthand for SetLimitAt(time.Now(), newLimit).
272 func (lim *Limiter) SetLimit(newLimit Limit) {
273 lim.SetLimitAt(time.Now(), newLimit)
276 // SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated
277 // or underutilized by those which reserved (using Reserve or Wait) but did not yet act
278 // before SetLimitAt was called.
279 func (lim *Limiter) SetLimitAt(now time.Time, newLimit Limit) {
281 defer lim.mu.Unlock()
283 now, _, tokens := lim.advance(now)
290 // SetBurst is shorthand for SetBurstAt(time.Now(), newBurst).
291 func (lim *Limiter) SetBurst(newBurst int) {
292 lim.SetBurstAt(time.Now(), newBurst)
295 // SetBurstAt sets a new burst size for the limiter.
296 func (lim *Limiter) SetBurstAt(now time.Time, newBurst int) {
298 defer lim.mu.Unlock()
300 now, _, tokens := lim.advance(now)
307 // reserveN is a helper method for AllowN, ReserveN, and WaitN.
308 // maxFutureReserve specifies the maximum reservation wait duration allowed.
309 // reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN.
310 func (lim *Limiter) reserveN(now time.Time, n int, maxFutureReserve time.Duration) Reservation {
313 if lim.limit == Inf {
323 now, last, tokens := lim.advance(now)
325 // Calculate the remaining number of tokens resulting from the request.
328 // Calculate the wait duration
329 var waitDuration time.Duration
331 waitDuration = lim.limit.durationFromTokens(-tokens)
335 ok := n <= lim.burst && waitDuration <= maxFutureReserve
337 // Prepare reservation
345 r.timeToAct = now.Add(waitDuration)
352 lim.lastEvent = r.timeToAct
361 // advance calculates and returns an updated state for lim resulting from the passage of time.
362 // lim is not changed.
363 // advance requires that lim.mu is held.
364 func (lim *Limiter) advance(now time.Time) (newNow time.Time, newLast time.Time, newTokens float64) {
366 if now.Before(last) {
370 // Avoid making delta overflow below when last is very old.
371 maxElapsed := lim.limit.durationFromTokens(float64(lim.burst) - lim.tokens)
372 elapsed := now.Sub(last)
373 if elapsed > maxElapsed {
377 // Calculate the new number of tokens, due to time that passed.
378 delta := lim.limit.tokensFromDuration(elapsed)
379 tokens := lim.tokens + delta
380 if burst := float64(lim.burst); tokens > burst {
384 return now, last, tokens
387 // durationFromTokens is a unit conversion function from the number of tokens to the duration
388 // of time it takes to accumulate them at a rate of limit tokens per second.
389 func (limit Limit) durationFromTokens(tokens float64) time.Duration {
390 seconds := tokens / float64(limit)
391 return time.Nanosecond * time.Duration(1e9*seconds)
394 // tokensFromDuration is a unit conversion function from a time duration to the number of tokens
395 // which could be accumulated during that duration at a rate of limit tokens per second.
396 func (limit Limit) tokensFromDuration(d time.Duration) float64 {
397 // Split the integer and fractional parts ourself to minimize rounding errors.
398 // See golang.org/issues/34861.
399 sec := float64(d/time.Second) * float64(limit)
400 nsec := float64(d%time.Second) * float64(limit)
401 return sec + nsec/1e9