Backend API. Server-side code: this runs in a Codename One backend, not in the app on the device.

public interface RateLimiter

Known subtypesInMemoryRateLimiter, JdbcRateLimiter, KeyValueRateLimiter

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.

Methods

public abstract boolean tryAcquire(String key)Counts one request under key.
public default long retryAfterSeconds(String key)How many seconds a request just refused under key should wait before trying again: what its Retry-After says.
public default void reset(String key)Forgets what was counted under key, so the next request under it is counted from nothing.
public 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.

Method details

tryAcquire

public abstract boolean tryAcquire(String key)
Counts one request under key.

Returns

whether the request is within the limit

retryAfterSeconds

public 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

public 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

public 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 String
what keeps the new limiter’s counts apart
permits int
how many requests a key may make in a period
periodSeconds long
the length of the period