checks.create() TypeScript SDK
The TypeScript SDK is a small typed client for Node.js, browsers and
Cloudflare Workers. guard and reserve put a limit around your code
in one call. Every API operation is also a typed method, and its types
come from the same definitions the API uses to validate requests. The
SDK always matches the API reference.
Install
Section titled “Install”npm install @limitry/sdkYour key
Section titled “Your key”Create an API key in the app under Settings → Developers. Give the key your app runs with Check limits. Give a script that also creates limits, subjects or credits Manage limits.
createClient()reads your key from theLIMITRY_API_KEYenvironment variable. If that isn’t set, it readsLIMITRY_TOKEN, the variable the CLI uses. If you set neither, it throws an error naming the variable.- Where there’s no
process.env, such as in a browser or a Cloudflare Worker, pass the key yourself:createClient({ apiKey: env.LIMITRY_API_KEY }). - A test key (
lim_test_…) acts in test, and a live key (lim_live_…) acts in live. Test and live explains the difference. - With a personal access token, pass it as
tokenand name the workspace. The token acts in test unless you name live:createClient({ token, workspace: "acme", environment: "live" }).
Guard costly work
Section titled “Guard costly work”Say each of your users has a $2 AI budget a month, counted in cents. You
only know what a reply cost once it’s done. reserve holds what the
reply will probably cost (5 cents here), runs your code, then charges
what it actually cost. If your code throws, reserve releases the hold:
import { createClient, LimitReachedError, UnavailableError,} from "@limitry/sdk";
const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable
try { const reply = await limitry.reserve( { subject: { kind: "user", id: "user_123" }, action: "ai-call", cost: 5 }, async (reservation) => { const response = await callModel(prompt); reservation.cost(priceCents(response.usage)); // your prices, in cents return response; }, ); console.log(reply);} catch (error) { if (error instanceof LimitReachedError) { console.log(`Try again in ${error.retryAfterSeconds} seconds`); } else if (error instanceof UnavailableError) { console.log(`No decision (${error.reason}), and this limit fails closed`); } else { throw error; }}A refusal throws LimitReachedError. Its reason is limit_reached
or too_many_reservations. It also carries limitId, limitName,
retryAfterSeconds and the whole decision.
Both errors share the base class LimitryError, as every error the SDK
throws does. A mistake in your request, such as a cost that isn’t a
whole number, throws the API’s error instead, such as
BadRequestError.
When every request costs the same, guard is simpler. It checks the limit,
then runs your code only if Limitry allows it. Here it counts one
request to your API against a limit of 60 a minute for each key:
import { createClient } from "@limitry/sdk";
const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable
const response = await limitry.guard( { subject: { kind: "apikey", id: "key_42" }, action: "api-request" }, () => handleRequest(request),);console.log(response);If your code can’t reach Limitry
Section titled “If your code can’t reach Limitry”If guard or reserve gets no decision, each limit’s fail mode decides.
With open, the work runs. With closed, they throw
UnavailableError, and never LimitReachedError. Its reason says
what happened: timeout, unreachable, plan_limit_reached or
rate_limited. Its cause holds the failure itself.
“No decision” means one of these, within timeout (1.5 seconds by
default) and counting every retry:
| What happened | What the SDK does |
|---|---|
A network error, or a 408, 429, 500, 502, 503 or 504 |
Retries at most twice with the same key, then the fail mode decides. |
A 402, because the workspace is past its plan |
The fail mode decides. |
A 503 with the code moving or busy |
Retries with the same key while the wait still fits, then the fail mode decides. |
A 503 with moving means a busy workspace’s counts are moving between
Limitry’s servers, which takes a few seconds. One with busy means
there were too many checks at once, and Limitry charged nothing. Each retry waits for the response’s Retry-After, or a second if that’s shorter.
It then adds a random backoff that grows each time, so clients don’t all
retry together.
A concurrent limit that fails open still runs no more than its
amount at once in your process. Past that, reserve throws
UnavailableError. Concurrency
explains why.
The commit or release after the work gets the same time as the check. If a commit doesn’t get through in that time, the SDK lets it go. Your work’s result still comes back. The reservation expires with no charge. Limitry never counts that work. This happens only while Limitry is moving counts or has too much to do.
reservation.cost()takes a whole number from 0 to 1,000,000,000. It throws aRangeErrorfor anything else, before the work’s usage could be lost.reservation.extend()throws the API’s error, for example when the reservation has already expired.
How Limitry works has the details.
Methods
Section titled “Methods”Every API operation is a method, named after the operation in the
API reference. For example, limits.create is
limitry.limits.create():
import { createClient } from "@limitry/sdk";
const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable
const limit = await limitry.limits.create({ name: "AI budget", subject: { kind: "user" }, action: "ai-call", amount: 200, unit: "cents", window: "month",});const { items } = await limitry.limits.list();console.log(limit.id, items.length);-
Ids in the path are arguments, and everything else goes in one object:
limitry.limits.get(limitId); -
A method returns the response’s data.
-
Because the types come from the API itself, your editor completes every method, field and response.
Here is every method. Each one links to its fields and a full example under Endpoints:
Checks
- Check whether a subject may act
checks.list() - List checks
Reservations
reservations.commit() - Commit a reservation
reservations.extend() - Extend a reservation
reservations.get() - Get a reservation
reservations.release() - Release a reservation
Limits
limits.archive() - Archive a limit
limits.create() - Create a limit
limits.credits. create() - Add credits to a balance
limits.credits. get() - Get a credit
limits.credits. list() - List a balance's credits
limits.get() - Get a limit
limits.list() - List limits
limits.restore() - Restore an archived limit
limits.sync() - Sync limits from a list
limits.update() - Change a limit
Subjects
subjects.get() - Get a subject
subjects.import() - Name many subjects
subjects.list() - List subjects
subjects.names. delete() - Erase a subject's name and labels
subjects.reset() - Reset a subject's limits
subjects.standing() - Get where a subject stands
subjects.update() - Update a subject
Usage
usage.overview() - Get every limit's usage at once
usage.query() - Get a limit's usage over time
usage.subjects() - List who is using a limit
Workspace
workspace.get() - Get the current workspace
workspace.invitations. list() - List pending invitations
workspace.members. list() - List workspace members
workspace.planUsage. get() - Get your plan's usage this period
workspace.teams. list() - List teams
Webhooks
workspace.eventTypes. list() - List event types
workspace.webhookDeliveries. list() - List an endpoint's deliveries
workspace.webhookDeliveries. redeliver() - Redeliver an event
workspace.webhookEndpoints. create() - Add a webhook endpoint
workspace.webhookEndpoints. delete() - Remove a webhook endpoint
workspace.webhookEndpoints. enable() - Re-enable a webhook endpoint
workspace.webhookEndpoints. get() - Get a webhook endpoint
workspace.webhookEndpoints. list() - List webhook endpoints
workspace.webhookEndpoints. test() - Send a test event
workspace.webhookEndpoints. update() - Update a webhook endpoint
Approvals
workspace.approvalActions. list() - List the actions you can ask approval for
workspace.approvalRequests. create() - Ask a person to approve an action
workspace.approvalRequests. get() - Check an approval request
workspace.approvalRequests. redeem() - Redeem an approved request
Audit events
workspace.auditEvents. list() - List workspace audit events
Personal access tokens
user.me() - Get the current user
user.revokeToken() - Revoke the token making this request
A list method returns its first page when you await it. The page has
the response’s items and nextCursor:
import { createClient } from "@limitry/sdk";
const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable
const page = await limitry.limits.list({ limit: 50 });console.log(page.items);
if (page.hasNextPage()) { const next = await page.getNextPage(); console.log(next.items);}To go through every item, use for await. The SDK fetches each next
page when it needs it:
for await (const limit of limitry.limits.list()) { console.log(limit.name);}Each next page is the same call with cursor set, so your other
fields and options hold for every page. Read more about
pagination.
Errors
Section titled “Errors”When the API refuses a call, the method throws an APIError. It has
the error’s code, message, status and
requestId. It also has:
details: what is wrong with each field, as{ path, message }, when the API refused the input.docs: a link to the error on the Errors page.headers: the response’s headers, such asRetry-Afterand the rate-limit headers.
Each status has its own class, so you can catch one kind of failure:
| Status | Class |
|---|---|
| 400 | BadRequestError |
| 401 | AuthenticationError |
| 402 | PlanLimitError |
| 403 | PermissionDeniedError |
| 404 | NotFoundError |
| 409 | ConflictError |
| 422 | UnprocessableEntityError |
| 429 | RateLimitError |
| 500+ | InternalServerError |
Any other status is an APIError itself.
When the SDK can’t reach the API, the method throws an
APIConnectionError, with the network’s error as its cause. When
every attempt timed out, it throws an APITimeoutError, which is an
APIConnectionError too.
Every error the SDK throws is a LimitryError, including
LimitReachedError and UnavailableError:
import { createClient, LimitryError, NotFoundError } from "@limitry/sdk";
const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable
try { const limit = await limitry.limits.get("lmt_123"); console.log(limit.name);} catch (error) { if (error instanceof NotFoundError) { console.log("No such limit"); } else if (error instanceof LimitryError) { console.log(error.message); } else { throw error; }}Retries and time limits
Section titled “Retries and time limits”These apply to every method. guard and reserve keep their own,
shorter time limit, as Your own timeout or fail mode
shows.
-
Every write sends an idempotency key. When the SDK retries a failed attempt, such as after a network error or a
503, the write still happens only once. -
The SDK retries a failed attempt twice. To change that, pass
maxRetriestocreateClient.0turns retries off. -
When the API says how long to wait with
Retry-After, the SDK waits that long, up to 60 seconds. If it must wait longer, it throws the error, such as aRateLimitError, instead. -
To make your own retries safe too, pass your key as the last argument:
limitry.checks.create(check, { idempotencyKey: id }); -
Each attempt waits up to 60 seconds for a response. A timed-out attempt is retried with the same key. To change the limit, pass
timeoutin milliseconds tocreateClient, or to one call:limitry.limits.list({}, { timeout: 5000 }); -
To limit a whole call, retries included, pass a
signal. WithAbortSignal.timeout(), the call stops at once when time is up, even while it waits to retry. It then throws the signal’sTimeoutError, not an SDK error:limitry.limits.list({}, { signal: AbortSignal.timeout(2000) });
Client options
Section titled “Client options”| Option | What it does |
|---|---|
apiKey |
Your API key. By default, LIMITRY_API_KEY. |
token |
A personal access token, instead of a key. |
workspace |
The workspace a personal access token acts in. |
environment |
test or live, for a personal access token. By default, test. |
baseURL |
The API’s address, without /v1. By default, LIMITRY_BASE_URL, else our API. |
defaultHeaders |
Headers to send with every request. A call’s own headers win. |
maxRetries |
How many times to retry a failed attempt. By default, 2. |
timeout |
How long each attempt may take, in milliseconds. By default, 60 000. |
fetch |
Your own fetch, such as a Cloudflare service binding. |
Outside a browser, every request names the SDK and its version in its
User-Agent header, such as limitry-node/1.0.0.
Each method takes these options for one call, as its last argument:
idempotencyKey, headers, timeout and signal.
Your own timeout or fail mode
Section titled “Your own timeout or fail mode”createLimits(client, options) gives you guard and reserve with
your own settings. timeout is the most a check adds to your request,
its tries included. It’s in milliseconds, 1,500 by default. failMode
fixes the fail mode for every limit:
import { createClient, createLimits } from "@limitry/sdk";
const limits = createLimits(createClient(), { timeout: 500 });Each guard or reserve call also takes timeout, failMode,
signal and idempotencyKey, for that call only:
import { createClient } from "@limitry/sdk";
const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable
const response = await limitry.guard( { subject: { kind: "apikey", id: "key_42" }, action: "api-request", timeout: 300, signal: request.signal, idempotencyKey: request.headers.get("idempotency-key") ?? undefined, }, () => handleRequest(request),);console.log(response);A signal that aborts ends the check at once and throws its reason.
The work never runs, and no fail mode applies.
Calling a path directly
Section titled “Calling a path directly”limitry.GET, limitry.POST and the other HTTP methods call any path,
with the same types. They return { data, error, response } instead of
throwing, and unwrap turns that into the data or an APIError:
import { createClient, unwrap } from "@limitry/sdk";
const limitry = createClient(); // uses the LIMITRY_API_KEY environment variableconst limits = unwrap(await limitry.GET("/limits"));console.log(limits.items.length);