001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.util.concurrent.Internal.toNanosSaturated;
020import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
021import static java.lang.Math.max;
022import static java.util.concurrent.TimeUnit.MICROSECONDS;
023import static java.util.concurrent.TimeUnit.NANOSECONDS;
024import static java.util.concurrent.TimeUnit.SECONDS;
025
026import com.google.common.annotations.Beta;
027import com.google.common.annotations.GwtIncompatible;
028import com.google.common.annotations.J2ktIncompatible;
029import com.google.common.annotations.VisibleForTesting;
030import com.google.common.base.Stopwatch;
031import com.google.common.util.concurrent.SmoothRateLimiter.SmoothBursty;
032import com.google.common.util.concurrent.SmoothRateLimiter.SmoothWarmingUp;
033import com.google.errorprone.annotations.CanIgnoreReturnValue;
034import java.time.Duration;
035import java.util.Locale;
036import java.util.concurrent.TimeUnit;
037import org.jspecify.annotations.Nullable;
038
039/**
040 * A rate limiter. Conceptually, a rate limiter distributes permits at a configurable rate. Each
041 * {@link #acquire()} blocks if necessary until a permit is available, and then takes it. Once
042 * acquired, permits need not be released.
043 *
044 * <p>{@code RateLimiter} is safe for concurrent use: It will restrict the total rate of calls from
045 * all threads. Note, however, that it does not guarantee fairness.
046 *
047 * <p>Rate limiters are often used to restrict the rate at which some physical or logical resource
048 * is accessed. This is in contrast to {@link java.util.concurrent.Semaphore} which restricts the
049 * number of concurrent accesses instead of the rate (note though that concurrency and rate are
050 * closely related, e.g. see <a href="http://en.wikipedia.org/wiki/Little%27s_law">Little's
051 * Law</a>).
052 *
053 * <p>A {@code RateLimiter} is defined primarily by the rate at which permits are issued. Absent
054 * additional configuration, permits will be distributed at a fixed rate, defined in terms of
055 * permits per second. Permits will be distributed smoothly, with the delay between individual
056 * permits being adjusted to ensure that the configured rate is maintained.
057 *
058 * <p>It is possible to configure a {@code RateLimiter} to have a warmup period during which time
059 * the permits issued each second steadily increases until it hits the stable rate.
060 *
061 * <p>As an example, imagine that we have a list of tasks to execute, but we don't want to submit
062 * more than 2 per second:
063 *
064 * {@snippet :
065 * final RateLimiter rateLimiter = RateLimiter.create(2.0); // rate is "2 permits per second"
066 * void submitTasks(List<Runnable> tasks, Executor executor) {
067 *   for (Runnable task : tasks) {
068 *     rateLimiter.acquire(); // may wait
069 *     executor.execute(task);
070 *   }
071 * }
072 * }
073 *
074 * <p>As another example, imagine that we produce a stream of data, and we want to cap it at 5kb per
075 * second. This could be accomplished by requiring a permit per byte, and specifying a rate of 5000
076 * permits per second:
077 *
078 * {@snippet :
079 * final RateLimiter rateLimiter = RateLimiter.create(5000.0); // rate = 5000 permits per second
080 * void submitPacket(byte[] packet) {
081 *   rateLimiter.acquire(packet.length);
082 *   networkService.send(packet);
083 * }
084 * }
085 *
086 * <p>It is important to note that the number of permits requested <i>never</i> affects the
087 * throttling of the request itself (an invocation to {@code acquire(1)} and an invocation to {@code
088 * acquire(1000)} will result in exactly the same throttling, if any), but it affects the throttling
089 * of the <i>next</i> request. I.e., if an expensive task arrives at an idle RateLimiter, it will be
090 * granted immediately, but it is the <i>next</i> request that will experience extra throttling,
091 * thus paying for the cost of the expensive task.
092 *
093 * @author Dimitris Andreou
094 * @since 13.0
095 */
096// TODO(user): switch to nano precision. A natural unit of cost is "bytes", and a micro precision
097// would mean a maximum rate of "1MB/s", which might be small in some cases.
098@Beta
099@J2ktIncompatible
100@GwtIncompatible
101public abstract class RateLimiter {
102  /**
103   * Creates a {@code RateLimiter} with the specified stable throughput, given as "permits per
104   * second" (commonly referred to as <i>QPS</i>, queries per second).
105   *
106   * <p>The returned {@code RateLimiter} ensures that on average no more than {@code
107   * permitsPerSecond} are issued during any given second, with sustained requests being smoothly
108   * spread over each second. When the incoming request rate exceeds {@code permitsPerSecond} the
109   * rate limiter will release one permit every {@code (1.0 / permitsPerSecond)} seconds. When the
110   * rate limiter is unused, bursts of up to {@code permitsPerSecond} permits will be allowed, with
111   * subsequent requests being smoothly limited at the stable rate of {@code permitsPerSecond}.
112   *
113   * @param permitsPerSecond the rate of the returned {@code RateLimiter}, measured in how many
114   *     permits become available per second
115   * @throws IllegalArgumentException if {@code permitsPerSecond} is negative or zero
116   */
117  // TODO(user): "This is equivalent to
118  // {@code createWithCapacity(permitsPerSecond, 1, TimeUnit.SECONDS)}".
119  public static RateLimiter create(double permitsPerSecond) {
120    /*
121     * The default RateLimiter configuration can save the unused permits of up to one second. This
122     * is to avoid unnecessary stalls in situations like this: A RateLimiter of 1qps, and 4 threads,
123     * all calling acquire() at these moments:
124     *
125     * T0 at 0 seconds
126     * T1 at 1.05 seconds
127     * T2 at 2 seconds
128     * T3 at 3 seconds
129     *
130     * Due to the slight delay of T1, T2 would have to sleep till 2.05 seconds, and T3 would also
131     * have to sleep till 3.05 seconds.
132     */
133    return create(permitsPerSecond, SleepingStopwatch.createFromSystemTimer());
134  }
135
136  @VisibleForTesting
137  static RateLimiter create(double permitsPerSecond, SleepingStopwatch stopwatch) {
138    RateLimiter rateLimiter = new SmoothBursty(stopwatch, /* maxBurstSeconds= */ 1.0);
139    rateLimiter.setRate(permitsPerSecond);
140    return rateLimiter;
141  }
142
143  /**
144   * Creates a {@code RateLimiter} with the specified stable throughput, given as "permits per
145   * second" (commonly referred to as <i>QPS</i>, queries per second), and a <i>warmup period</i>,
146   * during which the {@code RateLimiter} smoothly ramps up its rate, until it reaches its maximum
147   * rate at the end of the period (as long as there are enough requests to saturate it). Similarly,
148   * if the {@code RateLimiter} is left <i>unused</i> for a duration of {@code warmupPeriod}, it
149   * will gradually return to its "cold" state, i.e. it will go through the same warming up process
150   * as when it was first created.
151   *
152   * <p>The returned {@code RateLimiter} is intended for cases where the resource that actually
153   * fulfills the requests (e.g., a remote server) needs "warmup" time, rather than being
154   * immediately accessed at the stable (maximum) rate.
155   *
156   * <p>The returned {@code RateLimiter} starts in a "cold" state (i.e. the warmup period will
157   * follow), and if it is left unused for long enough, it will return to that state.
158   *
159   * @param permitsPerSecond the rate of the returned {@code RateLimiter}, measured in how many
160   *     permits become available per second
161   * @param warmupPeriod the duration of the period where the {@code RateLimiter} ramps up its rate,
162   *     before reaching its stable (maximum) rate
163   * @throws IllegalArgumentException if {@code permitsPerSecond} is negative or zero or {@code
164   *     warmupPeriod} is negative
165   * @since 28.0 (but only since 33.4.0 in the Android flavor)
166   */
167  public static RateLimiter create(double permitsPerSecond, Duration warmupPeriod) {
168    return create(permitsPerSecond, toNanosSaturated(warmupPeriod), NANOSECONDS);
169  }
170
171  /**
172   * Creates a {@code RateLimiter} with the specified stable throughput, given as "permits per
173   * second" (commonly referred to as <i>QPS</i>, queries per second), and a <i>warmup period</i>,
174   * during which the {@code RateLimiter} smoothly ramps up its rate, until it reaches its maximum
175   * rate at the end of the period (as long as there are enough requests to saturate it). Similarly,
176   * if the {@code RateLimiter} is left <i>unused</i> for a duration of {@code warmupPeriod}, it
177   * will gradually return to its "cold" state, i.e. it will go through the same warming up process
178   * as when it was first created.
179   *
180   * <p>The returned {@code RateLimiter} is intended for cases where the resource that actually
181   * fulfills the requests (e.g., a remote server) needs "warmup" time, rather than being
182   * immediately accessed at the stable (maximum) rate.
183   *
184   * <p>The returned {@code RateLimiter} starts in a "cold" state (i.e. the warmup period will
185   * follow), and if it is left unused for long enough, it will return to that state.
186   *
187   * @param permitsPerSecond the rate of the returned {@code RateLimiter}, measured in how many
188   *     permits become available per second
189   * @param warmupPeriod the duration of the period where the {@code RateLimiter} ramps up its rate,
190   *     before reaching its stable (maximum) rate
191   * @param unit the time unit of the warmupPeriod argument
192   * @throws IllegalArgumentException if {@code permitsPerSecond} is negative or zero or {@code
193   *     warmupPeriod} is negative
194   */
195  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
196  public static RateLimiter create(double permitsPerSecond, long warmupPeriod, TimeUnit unit) {
197    checkArgument(warmupPeriod >= 0, "warmupPeriod must not be negative: %s", warmupPeriod);
198    return create(
199        permitsPerSecond, warmupPeriod, unit, 3.0, SleepingStopwatch.createFromSystemTimer());
200  }
201
202  @VisibleForTesting
203  static RateLimiter create(
204      double permitsPerSecond,
205      long warmupPeriod,
206      TimeUnit unit,
207      double coldFactor,
208      SleepingStopwatch stopwatch) {
209    RateLimiter rateLimiter = new SmoothWarmingUp(stopwatch, warmupPeriod, unit, coldFactor);
210    rateLimiter.setRate(permitsPerSecond);
211    return rateLimiter;
212  }
213
214  /**
215   * The underlying timer; used both to measure elapsed time and sleep as necessary. A separate
216   * object to facilitate testing.
217   */
218  private final SleepingStopwatch stopwatch;
219
220  // Can't be initialized in the constructor because mocks don't call the constructor.
221  private volatile @Nullable Object mutexDoNotUseDirectly;
222
223  private Object mutex() {
224    Object mutex = mutexDoNotUseDirectly;
225    if (mutex == null) {
226      synchronized (this) {
227        mutex = mutexDoNotUseDirectly;
228        if (mutex == null) {
229          mutexDoNotUseDirectly = mutex = new Object();
230        }
231      }
232    }
233    return mutex;
234  }
235
236  RateLimiter(SleepingStopwatch stopwatch) {
237    this.stopwatch = checkNotNull(stopwatch);
238  }
239
240  /**
241   * Updates the stable rate of this {@code RateLimiter}, that is, the {@code permitsPerSecond}
242   * argument provided in the factory method that constructed the {@code RateLimiter}. Currently
243   * throttled threads will <b>not</b> be awakened as a result of this invocation, thus they do not
244   * observe the new rate; only subsequent requests will.
245   *
246   * <p>Note though that, since each request repays (by waiting, if necessary) the cost of the
247   * <i>previous</i> request, this means that the very next request after an invocation to {@code
248   * setRate} will not be affected by the new rate; it will pay the cost of the previous request,
249   * which is in terms of the previous rate.
250   *
251   * <p>The behavior of the {@code RateLimiter} is not modified in any other way, e.g. if the {@code
252   * RateLimiter} was configured with a warmup period of 20 seconds, it still has a warmup period of
253   * 20 seconds after this method invocation.
254   *
255   * @param permitsPerSecond the new stable rate of this {@code RateLimiter}
256   * @throws IllegalArgumentException if {@code permitsPerSecond} is negative or zero
257   */
258  public final void setRate(double permitsPerSecond) {
259    checkArgument(permitsPerSecond > 0.0, "rate must be positive");
260    synchronized (mutex()) {
261      doSetRate(permitsPerSecond, stopwatch.readMicros());
262    }
263  }
264
265  abstract void doSetRate(double permitsPerSecond, long nowMicros);
266
267  /**
268   * Returns the stable rate (as {@code permits per seconds}) with which this {@code RateLimiter} is
269   * configured with. The initial value of this is the same as the {@code permitsPerSecond} argument
270   * passed in the factory method that produced this {@code RateLimiter}, and it is only updated
271   * after invocations to {@linkplain #setRate}.
272   */
273  public final double getRate() {
274    synchronized (mutex()) {
275      return doGetRate();
276    }
277  }
278
279  abstract double doGetRate();
280
281  /**
282   * Acquires a single permit from this {@code RateLimiter}, blocking until the request can be
283   * granted. Tells the amount of time slept, if any.
284   *
285   * <p>This method is equivalent to {@code acquire(1)}.
286   *
287   * @return time spent sleeping to enforce rate, in seconds; 0.0 if not rate-limited
288   * @since 16.0 (present in 13.0 with {@code void} return type})
289   */
290  @CanIgnoreReturnValue
291  public double acquire() {
292    return acquire(1);
293  }
294
295  /**
296   * Acquires the given number of permits from this {@code RateLimiter}, blocking until the request
297   * can be granted. Tells the amount of time slept, if any.
298   *
299   * @param permits the number of permits to acquire
300   * @return time spent sleeping to enforce rate, in seconds; 0.0 if not rate-limited
301   * @throws IllegalArgumentException if the requested number of permits is negative or zero
302   * @since 16.0 (present in 13.0 with {@code void} return type})
303   */
304  @CanIgnoreReturnValue
305  public double acquire(int permits) {
306    long microsToWait = reserve(permits);
307    stopwatch.sleepMicrosUninterruptibly(microsToWait);
308    return 1.0 * microsToWait / SECONDS.toMicros(1L);
309  }
310
311  /**
312   * Reserves the given number of permits from this {@code RateLimiter} for future use, returning
313   * the number of microseconds until the reservation can be consumed.
314   *
315   * @return time in microseconds to wait until the resource can be acquired, never negative
316   */
317  final long reserve(int permits) {
318    checkPermits(permits);
319    synchronized (mutex()) {
320      return reserveAndGetWaitLength(permits, stopwatch.readMicros());
321    }
322  }
323
324  /**
325   * Acquires a permit from this {@code RateLimiter} if it can be obtained without exceeding the
326   * specified {@code timeout}, or returns {@code false} immediately (without waiting) if the permit
327   * would not have been granted before the timeout expired.
328   *
329   * <p>This method is equivalent to {@code tryAcquire(1, timeout)}.
330   *
331   * @param timeout the maximum time to wait for the permit. Negative values are treated as zero.
332   * @return {@code true} if the permit was acquired, {@code false} otherwise
333   * @throws IllegalArgumentException if the requested number of permits is negative or zero
334   * @since 28.0 (but only since 33.4.0 in the Android flavor)
335   */
336  public boolean tryAcquire(Duration timeout) {
337    return tryAcquire(1, toNanosSaturated(timeout), NANOSECONDS);
338  }
339
340  /**
341   * Acquires a permit from this {@code RateLimiter} if it can be obtained without exceeding the
342   * specified {@code timeout}, or returns {@code false} immediately (without waiting) if the permit
343   * would not have been granted before the timeout expired.
344   *
345   * <p>This method is equivalent to {@code tryAcquire(1, timeout, unit)}.
346   *
347   * @param timeout the maximum time to wait for the permit. Negative values are treated as zero.
348   * @param unit the time unit of the timeout argument
349   * @return {@code true} if the permit was acquired, {@code false} otherwise
350   * @throws IllegalArgumentException if the requested number of permits is negative or zero
351   */
352  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
353  public boolean tryAcquire(long timeout, TimeUnit unit) {
354    return tryAcquire(1, timeout, unit);
355  }
356
357  /**
358   * Acquires permits from this {@link RateLimiter} if it can be acquired immediately without delay.
359   *
360   * <p>This method is equivalent to {@code tryAcquire(permits, 0, anyUnit)}.
361   *
362   * @param permits the number of permits to acquire
363   * @return {@code true} if the permits were acquired, {@code false} otherwise
364   * @throws IllegalArgumentException if the requested number of permits is negative or zero
365   * @since 14.0
366   */
367  public boolean tryAcquire(int permits) {
368    return tryAcquire(permits, 0, MICROSECONDS);
369  }
370
371  /**
372   * Acquires a permit from this {@link RateLimiter} if it can be acquired immediately without
373   * delay.
374   *
375   * <p>This method is equivalent to {@code tryAcquire(1)}.
376   *
377   * @return {@code true} if the permit was acquired, {@code false} otherwise
378   * @since 14.0
379   */
380  public boolean tryAcquire() {
381    return tryAcquire(1, 0, MICROSECONDS);
382  }
383
384  /**
385   * Acquires the given number of permits from this {@code RateLimiter} if it can be obtained
386   * without exceeding the specified {@code timeout}, or returns {@code false} immediately (without
387   * waiting) if the permits would not have been granted before the timeout expired.
388   *
389   * @param permits the number of permits to acquire
390   * @param timeout the maximum time to wait for the permits. Negative values are treated as zero.
391   * @return {@code true} if the permits were acquired, {@code false} otherwise
392   * @throws IllegalArgumentException if the requested number of permits is negative or zero
393   * @since 28.0 (but only since 33.4.0 in the Android flavor)
394   */
395  public boolean tryAcquire(int permits, Duration timeout) {
396    return tryAcquire(permits, toNanosSaturated(timeout), NANOSECONDS);
397  }
398
399  /**
400   * Acquires the given number of permits from this {@code RateLimiter} if it can be obtained
401   * without exceeding the specified {@code timeout}, or returns {@code false} immediately (without
402   * waiting) if the permits would not have been granted before the timeout expired.
403   *
404   * @param permits the number of permits to acquire
405   * @param timeout the maximum time to wait for the permits. Negative values are treated as zero.
406   * @param unit the time unit of the timeout argument
407   * @return {@code true} if the permits were acquired, {@code false} otherwise
408   * @throws IllegalArgumentException if the requested number of permits is negative or zero
409   */
410  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
411  public boolean tryAcquire(int permits, long timeout, TimeUnit unit) {
412    long timeoutMicros = max(unit.toMicros(timeout), 0);
413    checkPermits(permits);
414    long microsToWait;
415    synchronized (mutex()) {
416      long nowMicros = stopwatch.readMicros();
417      if (!canAcquire(nowMicros, timeoutMicros)) {
418        return false;
419      } else {
420        microsToWait = reserveAndGetWaitLength(permits, nowMicros);
421      }
422    }
423    stopwatch.sleepMicrosUninterruptibly(microsToWait);
424    return true;
425  }
426
427  private boolean canAcquire(long nowMicros, long timeoutMicros) {
428    return queryEarliestAvailable(nowMicros) - timeoutMicros <= nowMicros;
429  }
430
431  /**
432   * Reserves next ticket and returns the wait time that the caller must wait for.
433   *
434   * @return the required wait time, never negative
435   */
436  final long reserveAndGetWaitLength(int permits, long nowMicros) {
437    long momentAvailable = reserveEarliestAvailable(permits, nowMicros);
438    return max(momentAvailable - nowMicros, 0);
439  }
440
441  /**
442   * Returns the earliest time that permits are available (with one caveat).
443   *
444   * @return the time that permits are available, or, if permits are available immediately, an
445   *     arbitrary past or present time
446   */
447  abstract long queryEarliestAvailable(long nowMicros);
448
449  /**
450   * Reserves the requested number of permits and returns the time that those permits can be used
451   * (with one caveat).
452   *
453   * @return the time that the permits may be used, or, if the permits may be used immediately, an
454   *     arbitrary past or present time
455   */
456  abstract long reserveEarliestAvailable(int permits, long nowMicros);
457
458  @Override
459  public String toString() {
460    return String.format(Locale.ROOT, "RateLimiter[stableRate=%3.1fqps]", getRate());
461  }
462
463  abstract static class SleepingStopwatch {
464    /** Constructor for use by subclasses. */
465    protected SleepingStopwatch() {}
466
467    /*
468     * We always hold the mutex when calling this. TODO(cpovirk): Is that important? Perhaps we need
469     * to guarantee that each call to reserveEarliestAvailable, etc. sees a value >= the previous?
470     * Also, is it OK that we don't hold the mutex when sleeping?
471     */
472    protected abstract long readMicros();
473
474    protected abstract void sleepMicrosUninterruptibly(long micros);
475
476    public static SleepingStopwatch createFromSystemTimer() {
477      return new SleepingStopwatch() {
478        final Stopwatch stopwatch = Stopwatch.createStarted();
479
480        @Override
481        protected long readMicros() {
482          return stopwatch.elapsed(MICROSECONDS);
483        }
484
485        @Override
486        protected void sleepMicrosUninterruptibly(long micros) {
487          if (micros > 0) {
488            sleepUninterruptibly(micros, MICROSECONDS);
489          }
490        }
491      };
492    }
493  }
494
495  private static void checkPermits(int permits) {
496    checkArgument(permits > 0, "Requested permits (%s) must be positive", permits);
497  }
498}