Skip to main content

Handle rate limits

Make a client behave well at a limit: read the headers, wait, and try again.

RecipeDraftView source
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.
Works with
JavaScript / TypeScriptPythonGoPHPJavaC# / .NETPlain HTTP

What it shows​

  1. A batch job makes many permission checks in a row with one API key.
  2. When the key has made too many requests, LumoAuth answers 429 Too Many Requests with a Retry-After header. The header gives the wait in seconds.
  3. The SDK turns that answer into a typed error, which carries the wait.
  4. 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.
  5. After five attempts the job gives up on that call and goes on.

Each SDK reports a 429 in its own way:

LanguageThe errorThe wait
JavaScriptLumoAuthRateLimitErrorretryAfter: seconds, or undefined
PythonLumoAuthRateLimitErrorretry_after: seconds, or None
Go*lumoauth.APIError, and errors.Is(err, lumoauth.ErrRateLimited) is trueRetryAfter: a time.Duration, 0 without the header
PHPLumoAuth\Error\LumoAuthRateLimitError$retryAfter: seconds, or null
Javaio.lumoauth.errors.LumoAuthRateLimitExceptionretryAfter(): an Optional<Duration>
C#LumoAuth.Errors.LumoAuthRateLimitExceptionRetryAfter: 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 needs admin:users:write.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYAn API key with the scope authz:check. The setup script also needs admin:users:write.
USER_IDThe ID of the user that the checks are about. The setup script prints it.
CALLSOptional. 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.

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

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-After only 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.