Skip to content

Core\RateLimit::consume

Limits how often something may happen for one key, and gives the same answer on every server.

A key is what the limit is for: one account, one API key, one IP address. You say how many units the key may use in a period, such as 5 per 15 minutes. Each call uses one unit, or the number you give as cost. The result is a Core\RateLimit\Decision. It says whether the call was allowed, and how long to wait when it was not.

The count is kept in the shared store that the person who runs the server sets up. So every server process and every machine counts together. When that store cannot be reached, consume throws an error. Your program then decides what to do. A login limit stops the call, and a plan quota allows it.

Good to know: Core\RateLimit::consumeLocally takes the same arguments and counts in one server process only. It needs no store, and its limit is less exact.

The examples below show the settings consume needs. Then they show a login limit that stops the login when the store cannot be reached, and an API quota that writes response headers.

Parameters

  • $keystringWho the limit is for, such as an account, a tenant or an API key id. A tainted value is allowed. A secret value is not allowed, because the key is written to the store. Use Core\Hash::of of the secret instead.
  • $limituintHow many units are allowed in each $per. This is the average rate. It is not a limit on one single moment.
  • $perCore\Time\DurationThe period in which $limit units are allowed.

Options

  • burstuintoptionalHow many units may arrive at the same moment. The default is $limit, which allows a whole period's units at once.
  • costuintoptionalHow many units this call uses. The default is 1. An expensive endpoint can use five units of the same limit, for example.

Return value

Returns Core\RateLimit\Decision. A Core\RateLimit\Decision. Its retryAfter is null when the call is allowed. Otherwise it is the exact time to wait until the call would be allowed. It is not an estimate, and it is not rounded up to the next period.

Errors

  • IOErrorThe shared store cannot be reached, or it rejected the command. The call is never treated as allowed. Your code catches this error and decides whether to allow the call or not.
  • RuntimeErrorNo [cache.shared] url is configured, or cache.shared is not granted. This is a deployment mistake, so it is not an IOError that your catch for a store failure handles. This error is also thrown when $limit, $per or $burst is zero. It is also thrown when the period is too short to divide into $limit units, or when $cost is larger than $burst.

Examples

What consume needs

<?nvs
// Shows what `Core\RateLimit::consume` needs before a program can use it. This
// server has no shared store, so the call below throws an error. The message
// names the setting that is missing.
// The person who runs the server writes both of these blocks in `nvs.toml`.
// A program cannot set them for itself.
//
// [capabilities.cache]
// shared = true
//
// [cache.shared]
// url = "redis://cache.internal:6379"
try {
var $decision = Core\RateLimit::consume('account:8412', 100, 1m);
echo 'allowed: ', $decision->isAllowed() ? 'yes' : 'no', "\n";
} catch (RuntimeError $error) {
echo $error->message, "\n";
}
Output
Core\RateLimit::consume needs the capability `cache.shared`, which is not granted
help: add `shared = true` under `[capabilities.cache]` in nvs.toml

A login limit that fails closed

<?nvs
// Shows a login limit of 5 tries per 15 minutes for each account. When the
// limit cannot be checked, this program refuses the login.
class Login
{
public static function mayTry(string $account): bool
{
try {
var $decision = Core\RateLimit::consume('login:' . $account, 5, 15m);
return $decision->isAllowed();
} catch (Throwable $error) {
// A guessed password is worse than a login that has to wait,
// so an error here means no.
return false;
}
}
}
// This server has no shared store, so this prints `refused`.
if (Login::mayTry('kim@example.com')) {
echo "checking the password\n";
} else {
echo "refused\n";
}
Output
refused

An api quota with headers

<?nvs
// Shows an API quota of 1000 units per hour for each API key. The response
// headers tell the client how much is left.
class Quota
{
public static function charge(string $apiKey, uint $cost): Core\RateLimit\Decision
{
try {
return Core\RateLimit::consume('api:' . $apiKey, 1000, 1h, { cost: $cost });
} catch (Throwable $away) {
// `consumeLocally` counts in this server process only, so the limit is less exact.
// The API keeps working while the shared store cannot be reached.
return Core\RateLimit::consumeLocally('api:' . $apiKey, 1000, 1h, { cost: $cost });
}
}
}
// An export is expensive, so it costs 10 units. This prints 1000 and 990.
var $decision = Quota::charge('key-51', 10);
echo 'RateLimit-Limit: ', $decision->limit(), "\n";
echo 'RateLimit-Remaining: ', $decision->remaining(), "\n";
// `retryAfter` is `null` when the call was allowed.
var $wait = $decision->retryAfter();
if ($wait == null) {
echo "status: 200\n";
} else {
echo "status: 429\n";
echo 'Retry-After: ', $wait->toSeconds(), "\n";
}
Output
RateLimit-Limit: 1000
RateLimit-Remaining: 990
status: 200