Interface RateLimiter

All Known Implementing Classes:
InMemoryRateLimiter, JdbcRateLimiter

public interface RateLimiter

Counts requests under a key and says when there have been too many.

An application that keeps its counts somewhere of its own -- a database, so that several servers share one count -- implements this.

  • Method Summary

    Modifier and Type
    Method
    Description
    default RateLimiter
    derive(String name, int permits, long periodSeconds)
    A limiter that keeps its counts where this one does, apart from this one's, with a limit of its own; null when this limiter cannot make one, which is what it answers unless it says more.
    default void
    Forgets what was counted under key, so the next request under it is counted from nothing.
    default long
    How many seconds a request just refused under key should wait before trying again: what its Retry-After says.
    boolean
    Counts one request under key.
  • Method Details

    • tryAcquire

      boolean tryAcquire(String key)
      Counts one request under key.
      Returns:
      whether the request is within the limit
    • retryAfterSeconds

      default long retryAfterSeconds(String key)
      How many seconds a request just refused under key should wait before trying again: what its Retry-After says. One second unless the limiter knows better.
    • reset

      default void reset(String key)

      Forgets what was counted under key, so the next request under it is counted from nothing.

      A bound on wrong guesses uses this: the guess is counted before it is looked at, so that guesses made together cannot each be let through as the last one, and a right one hands the count back. A limiter that cannot forget does nothing here, which is what it does unless it says more; a right guess then costs what a wrong one does.

    • derive

      default RateLimiter derive(String name, int permits, long periodSeconds)

      A limiter that keeps its counts where this one does, apart from this one's, with a limit of its own; null when this limiter cannot make one, which is what it answers unless it says more.

      The parts of the layer that count something themselves -- attempts at a second factor, tries at a device's code -- ask the application's limiter bean for one each. That is how a bean declared to throttle an API at 600 a minute comes to count guesses at a one-time code at five in five minutes, in the same database, without the two sharing either a count or a limit.

      Parameters:
      name - what keeps the new limiter's counts apart
      permits - how many requests a key may make in a period
      periodSeconds - the length of the period