Handle rate limits
Make a client behave well at a limit: read the headers, wait, and try again.
This page is a draft. The code exists, and not all of it has been run for this page yet. The page says what was checked.
What it shows
- A batch job makes many permission checks in a row with one API key.
- When the key has made too many requests, LumoAuth answers
429 Too Many Requestswith aRetry-Afterheader. The header gives the wait in seconds. - The SDK turns that answer into a typed error, which carries the wait.
- The job waits that long, plus a small random part, and sends the same call again. When the header is missing, it waits 1, 2, 4 and then 8 seconds.
- After five attempts the job gives up on that call and goes on.
Each SDK reports a 429 in its own way:
| Language | The error | The wait |
|---|---|---|
| JavaScript | LumoAuthRateLimitError | retryAfter: seconds, or undefined |
| Python | LumoAuthRateLimitError | retry_after: seconds, or None |
| Go | *lumoauth.APIError, and errors.Is(err, lumoauth.ErrRateLimited) is true | RetryAfter: a time.Duration, 0 without the header |
| PHP | LumoAuth\Error\LumoAuthRateLimitError | $retryAfter: seconds, or null |
| Java | io.lumoauth.errors.LumoAuthRateLimitException | retryAfter(): an Optional<Duration> |
| C# | LumoAuth.Errors.LumoAuthRateLimitException | RetryAfter: a TimeSpan? |
Before you start
- An API key with the scope
authz:check. Create it in the portal under Applications & developer tools, API keys. - A user to ask about. The setup script creates
rate-limit-user@example.com. Its API key also needsadmin:users:write.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | An API key with the scope authz:check. The setup script also needs admin:users:write. |
USER_ID | The ID of the user that the checks are about. The setup script prints it. |
CALLS | Optional. The number of checks in the batch. Default: 20. |
The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.
node operations/rate-limits/setup.mjs
setup.mjs
// Creates the test user that the batch job asks about. Run it again at any
// time.
//
// node operations/rate-limits/setup.mjs
//
// The API key needs the scope admin:users:write.
import { randomBytes } from 'node:crypto';
import { ensure, printEnv } from '../../_lib/admin.mjs';
const user = await ensure('/admin/users', (u) => u.email === 'rate-limit-user@example.com', {
email: 'rate-limit-user@example.com',
name: 'Riley Rivera',
// The recipe never signs in as this user, so nobody needs the password.
password: `${randomBytes(18).toString('base64url')}#Aa1`,
emailVerified: true,
});
console.log(`User ${user.email} is ready.`);
printEnv({ USER_ID: user.id });
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. The programs ran against an organization through a local proxy. The proxy answered three requests itself with 429, in the form that LumoAuth uses, so that the test did not use up the real limit. One of the three had no Retry-After header, to test the backoff.
- Node.js
- Python
- Go
- PHP
- Java
- C#
- curl
operations/rate-limits/js/batch.mjs
// Run a batch of permission checks, and wait each time that LumoAuth answers
// 429 Too Many Requests.
//
// node operations/rate-limits/js/batch.mjs
import { LumoAuthBackend, LumoAuthRateLimitError } from '@lumoauth/backend';
const lumo = new LumoAuthBackend({
baseUrl: process.env.LUMOAUTH_URL,
orgId: process.env.LUMOAUTH_ORG_ID,
secretKey: process.env.LUMOAUTH_API_KEY,
// The cache would answer repeated checks without a request. The batch
// wants every call to reach LumoAuth.
cache: false,
});
const calls = Number(process.env.CALLS ?? 20);
const maxAttempts = 5;
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
let answered = 0;
let waits = 0;
for (let call = 1; call <= calls; call++) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
// users.view is a built-in permission, so the batch needs no role.
await lumo.permissions.check('users.view', undefined, { userId: process.env.USER_ID });
answered++;
break;
} catch (error) {
// Any other error is not a reason to wait.
if (!(error instanceof LumoAuthRateLimitError)) throw error;
if (attempt === maxAttempts) {
console.log(`call ${call}: still 429 after ${maxAttempts} attempts`);
break;
}
// Retry-After is the number of seconds that LumoAuth asks you to wait.
// Without it, wait 1, 2, 4, 8 seconds. The random part stops many
// clients from trying again at the same moment.
const hint = error.retryAfter;
const wait = (hint ?? 2 ** (attempt - 1)) + Math.random() * 0.5;
waits++;
console.log(`call ${call}: 429, ${hint === undefined ? 'no Retry-After' : `Retry-After ${hint} s`}, waiting ${wait.toFixed(1)} s`);
await sleep(wait);
}
}
}
console.log(`${answered} of ${calls} calls answered, ${waits} waits`);
if (answered < calls) process.exit(1);
node operations/rate-limits/js/batch.mjs
operations/rate-limits/python/batch.py
"""Run a batch of permission checks, and wait each time that LumoAuth answers
429 Too Many Requests.
python operations/rate-limits/python/batch.py
"""
import os
import random
import sys
import time
from lumoauth import LumoAuth, LumoAuthRateLimitError
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
lumo = LumoAuth()
calls = int(os.environ.get("CALLS", "20"))
max_attempts = 5
answered = 0
waits = 0
for call in range(1, calls + 1):
for attempt in range(1, max_attempts + 1):
try:
# users.view is a built-in permission, so the batch needs no role.
lumo.permissions.check("users.view", user_id=os.environ["USER_ID"])
answered += 1
break
except LumoAuthRateLimitError as error:
# Any other error is not a reason to wait, so only this one is caught.
if attempt == max_attempts:
print(f"call {call}: still 429 after {max_attempts} attempts")
break
# Retry-After is the number of seconds that LumoAuth asks you to wait.
# Without it, wait 1, 2, 4, 8 seconds. The random part stops many
# clients from trying again at the same moment.
hint = error.retry_after
wait = (hint if hint is not None else 2 ** (attempt - 1)) + random.random() * 0.5
waits += 1
told = "no Retry-After" if hint is None else f"Retry-After {hint:g} s"
print(f"call {call}: 429, {told}, waiting {wait:.1f} s")
time.sleep(wait)
print(f"{answered} of {calls} calls answered, {waits} waits")
if answered < calls:
sys.exit(1)
python operations/rate-limits/python/batch.py
operations/rate-limits/go/main.go
// Run a batch of permission checks, and wait each time that LumoAuth answers
// 429 Too Many Requests.
//
// go run ./operations/rate-limits/go
package main
import (
"context"
"errors"
"fmt"
"log"
"math/rand/v2"
"os"
"strconv"
"time"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
client, err := lumoauth.New()
if err != nil {
log.Fatal(err)
}
calls := 20
if value := os.Getenv("CALLS"); value != "" {
if calls, err = strconv.Atoi(value); err != nil {
log.Fatal(err)
}
}
const maxAttempts = 5
ctx := context.Background()
answered, waits := 0, 0
for call := 1; call <= calls; call++ {
for attempt := 1; attempt <= maxAttempts; attempt++ {
// users.view is a built-in permission, so the batch needs no role.
_, err := client.Permissions.Check(ctx, "users.view", &lumoauth.CheckOptions{UserID: os.Getenv("USER_ID")})
if err == nil {
answered++
break
}
// Any other error is not a reason to wait.
apiErr, ok := lumoauth.AsAPIError(err)
if !ok || !errors.Is(err, lumoauth.ErrRateLimited) {
log.Fatal(err)
}
if attempt == maxAttempts {
fmt.Printf("call %d: still 429 after %d attempts\n", call, maxAttempts)
break
}
// RetryAfter is how long LumoAuth asks you to wait, 0 when the
// answer had no Retry-After. Then wait 1, 2, 4, 8 seconds. The
// random part stops many clients from trying again at the same moment.
told := "no Retry-After"
wait := time.Duration(1<<(attempt-1)) * time.Second
if apiErr.RetryAfter > 0 {
told = fmt.Sprintf("Retry-After %g s", apiErr.RetryAfter.Seconds())
wait = apiErr.RetryAfter
}
wait += time.Duration(rand.Float64() * float64(500*time.Millisecond))
waits++
fmt.Printf("call %d: 429, %s, waiting %.1f s\n", call, told, wait.Seconds())
time.Sleep(wait)
}
}
fmt.Printf("%d of %d calls answered, %d waits\n", answered, calls, waits)
if answered < calls {
os.Exit(1)
}
}
go run ./operations/rate-limits/go
operations/rate-limits/php/batch.php
<?php
// Run a batch of permission checks, and wait each time that LumoAuth answers
// 429 Too Many Requests.
//
// php operations/rate-limits/php/batch.php
require __DIR__ . '/../../../php/vendor/autoload.php';
use LumoAuth\Error\LumoAuthRateLimitError;
use LumoAuth\LumoAuth;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
$lumo = new LumoAuth();
$calls = (int) (getenv('CALLS') ?: 20);
$maxAttempts = 5;
$answered = 0;
$waits = 0;
for ($call = 1; $call <= $calls; $call++) {
for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
try {
// users.view is a built-in permission, so the batch needs no role.
$lumo->permissions->check('users.view', userId: getenv('USER_ID'));
$answered++;
break;
} catch (LumoAuthRateLimitError $error) {
// Any other error is not a reason to wait, so only this one is caught.
if ($attempt === $maxAttempts) {
printf("call %d: still 429 after %d attempts\n", $call, $maxAttempts);
break;
}
// retryAfter is the number of seconds that LumoAuth asks you to wait.
// Without it, wait 1, 2, 4, 8 seconds. The random part stops many
// clients from trying again at the same moment.
$hint = $error->retryAfter;
$wait = ($hint ?? 2 ** ($attempt - 1)) + mt_rand(0, 500) / 1000;
$waits++;
$told = $hint === null ? 'no Retry-After' : sprintf('Retry-After %g s', $hint);
printf("call %d: 429, %s, waiting %.1f s\n", $call, $told, $wait);
usleep((int) ($wait * 1_000_000));
}
}
}
printf("%d of %d calls answered, %d waits\n", $answered, $calls, $waits);
exit($answered < $calls ? 1 : 0);
php operations/rate-limits/php/batch.php
operations/rate-limits/java/Batch.java
// Run a batch of permission checks, and wait each time that LumoAuth answers
// 429 Too Many Requests.
//
// java -cp "java/lib/*" operations/rate-limits/java/Batch.java
import io.lumoauth.LumoAuth;
import io.lumoauth.errors.LumoAuthRateLimitException;
import io.lumoauth.model.CheckOptions;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
public class Batch {
public static void main(String[] args) throws InterruptedException {
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
LumoAuth lumo = LumoAuth.fromEnvironment();
int calls = Integer.parseInt(System.getenv().getOrDefault("CALLS", "20"));
int maxAttempts = 5;
int answered = 0;
int waits = 0;
for (int call = 1; call <= calls; call++) {
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
// users.view is a built-in permission, so the batch needs no role.
lumo.permissions().check("users.view", CheckOptions.forUser(System.getenv("USER_ID")));
answered++;
break;
} catch (LumoAuthRateLimitException error) {
// Any other error is not a reason to wait, so only this one is caught.
if (attempt == maxAttempts) {
System.out.printf("call %d: still 429 after %d attempts%n", call, maxAttempts);
break;
}
// retryAfter() is how long LumoAuth asks you to wait. Without
// it, wait 1, 2, 4, 8 seconds. The random part stops many
// clients from trying again at the same moment.
Optional<Duration> hint = error.retryAfter();
Duration wait = hint.orElse(Duration.ofSeconds(1L << (attempt - 1)))
.plusMillis(ThreadLocalRandom.current().nextLong(500));
waits++;
String told = hint.map(d -> "Retry-After " + d.toSeconds() + " s").orElse("no Retry-After");
System.out.printf("call %d: 429, %s, waiting %.1f s%n", call, told, wait.toMillis() / 1000.0);
Thread.sleep(wait);
}
}
}
System.out.printf("%d of %d calls answered, %d waits%n", answered, calls, waits);
if (answered < calls) {
System.exit(1);
}
}
}
java -cp "java/lib/*" operations/rate-limits/java/Batch.java
operations/rate-limits/csharp/Batch.cs
#:package LumoAuth@1.7.0
#:property PublishAot=false
// Run a batch of permission checks, and wait each time that LumoAuth answers
// 429 Too Many Requests.
//
// dotnet run operations/rate-limits/csharp/Batch.cs
using LumoAuth;
using LumoAuth.Errors;
using LumoAuth.Models;
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_API_KEY.
var lumo = LumoAuthClient.FromEnvironment();
var calls = int.Parse(Environment.GetEnvironmentVariable("CALLS") ?? "20");
const int maxAttempts = 5;
var answered = 0;
var waits = 0;
for (var call = 1; call <= calls; call++)
{
for (var attempt = 1; attempt <= maxAttempts; attempt++)
{
try
{
// users.view is a built-in permission, so the batch needs no role.
await lumo.Permissions.CheckAsync("users.view", CheckOptions.ForUser(Environment.GetEnvironmentVariable("USER_ID")!));
answered++;
break;
}
catch (LumoAuthRateLimitException error)
{
// Any other error is not a reason to wait, so only this one is caught.
if (attempt == maxAttempts)
{
Console.WriteLine($"call {call}: still 429 after {maxAttempts} attempts");
break;
}
// RetryAfter is how long LumoAuth asks you to wait. Without it,
// wait 1, 2, 4, 8 seconds. The random part stops many clients from
// trying again at the same moment.
var hint = error.RetryAfter;
var wait = (hint ?? TimeSpan.FromSeconds(1 << (attempt - 1))) + TimeSpan.FromMilliseconds(Random.Shared.Next(500));
waits++;
var told = hint is null ? "no Retry-After" : $"Retry-After {hint.Value.TotalSeconds:0.#} s";
Console.WriteLine($"call {call}: 429, {told}, waiting {wait.TotalSeconds:0.0} s");
await Task.Delay(wait);
}
}
}
Console.WriteLine($"{answered} of {calls} calls answered, {waits} waits");
return answered < calls ? 1 : 0;
dotnet run operations/rate-limits/csharp/Batch.cs
operations/rate-limits/http/batch.sh
#!/bin/sh
# Run a batch of permission checks with curl, and wait each time that
# LumoAuth answers 429 Too Many Requests.
#
# sh operations/rate-limits/http/batch.sh
set -eu
CALLS="${CALLS:-20}"
MAX_ATTEMPTS=5
HEADERS=$(mktemp)
trap 'rm -f "$HEADERS"' EXIT
ANSWERED=0
WAITS=0
CALL=1
while [ "$CALL" -le "$CALLS" ]; do
ATTEMPT=1
while [ "$ATTEMPT" -le "$MAX_ATTEMPTS" ]; do
# users.view is a built-in permission, so the batch needs no role.
STATUS=$(curl --silent --show-error --output /dev/null --dump-header "$HEADERS" --write-out '%{http_code}' \
"$LUMOAUTH_URL/api/v1/authz/check" \
--header "X-API-Key: $LUMOAUTH_API_KEY" \
--header "Content-Type: application/json" \
--data "{\"permission\": \"users.view\", \"subject\": {\"type\": \"user\", \"id\": \"$USER_ID\"}}")
if [ "$STATUS" = 200 ]; then
ANSWERED=$((ANSWERED + 1))
break
fi
# Any other status is not a reason to wait.
if [ "$STATUS" != 429 ]; then
echo "call $CALL: HTTP $STATUS" >&2
exit 1
fi
if [ "$ATTEMPT" = "$MAX_ATTEMPTS" ]; then
echo "call $CALL: still 429 after $MAX_ATTEMPTS attempts"
break
fi
# Retry-After is the number of seconds that LumoAuth asks you to wait.
# Without it, wait 1, 2, 4, 8 seconds. The random part stops many clients
# from trying again at the same moment.
HINT=$(tr -d '\r' < "$HEADERS" | awk 'tolower($1) == "retry-after:" { print $2 }')
if [ -n "$HINT" ]; then
TOLD="Retry-After $HINT s"
BASE="$HINT"
else
TOLD="no Retry-After"
BASE=$((1 << (ATTEMPT - 1)))
fi
WAIT=$(awk -v base="$BASE" 'BEGIN { srand(); printf "%.1f", base + rand() * 0.5 }')
WAITS=$((WAITS + 1))
echo "call $CALL: 429, $TOLD, waiting $WAIT s"
sleep "$WAIT"
ATTEMPT=$((ATTEMPT + 1))
done
CALL=$((CALL + 1))
done
echo "$ANSWERED of $CALLS calls answered, $WAITS waits"
[ "$ANSWERED" = "$CALLS" ]
sh operations/rate-limits/http/batch.sh
Check the result
Output
call 3: 429, Retry-After 1 s, waiting 1.3 s
call 3: 429, Retry-After 1 s, waiting 1.4 s
call 7: 429, no Retry-After, waiting 1.3 s
20 of 20 calls answered, 3 waits
- With the default of 20 calls, the batch usually ends with
20 of 20 calls answered, 0 waits. Twenty checks stay far below the limit. - To reach the limit, run the batch with
CALLS=650. Each API key may make 600 requests in 60 seconds to the Admin API and to the authorization APIs. The calls after that get 429 until the window has room again. - Every request of the key counts toward the same budget. Use a key that no other job needs while you try this, because that job waits too.
- The batch exits with status 1 when a call still gets 429 after five attempts. A scheduler can then run it again later.
Limits
- No SDK waits and tries again by itself. Your code decides how long to wait and how often to try.
- Ordinary answers carry no
X-RateLimit-*headers. You learn about the limit only from the 429. - The JavaScript, Python and PHP SDKs read
Retry-Afteronly as a number of seconds. Go, Java and C# also read the date form of the header. - An organization cannot change the limits. To spread the load, give independent jobs their own API keys: each key has its own budget.
- Sign-in, the token endpoint and other flows have their own limits, listed in Rate limits. A refused sign-in is not an error to try again in a loop.