{limit.limitName}
{label}
0 ? (left / max) * 100 : 0}%`,
height: "100%",
background: left === 0 ? "#b91c1c" : "#1d4ed8",
}}
/>
{resets &&
{resets}}
);
}
```
The bar shows what’s left, so it empties as the team spends. Screen readers announce the same words the user sees, such as “4975 credits left”. Swap the inline styles for your own classes.
Fetch it when the page opens, not on a timer. If your product shows the bar on every page, cache the route’s response for a few seconds on your server.
## 4. When they run out
[Section titled “4. When they run out”](#4-when-they-run-out)
A refused check throws `LimitReachedError` from `limitry.guard()` and `limitry.reserve()`. Answer it where your product talks to the user, and point them at the bar or a way to get more:
* TypeScript
```ts
import { LimitReachedError } from "@limitry/sdk";
try {
return await limitry.guard(
{
subject: { kind: "user", id: user.id },
shared: [{ kind: "team", id: user.teamId }],
action: "report",
cost: 25,
},
() => buildReport(params),
);
} catch (err) {
if (err instanceof LimitReachedError && err.reason === "limit_reached") {
return res.status(402).json({
message: "Your team is out of credits. Buy more to keep going.",
buyUrl: "/billing/credits",
});
}
throw err;
}
```
* Python
```python
from flask import jsonify
from limitry import LimitReachedError
try:
with limitry.guard(
subject={"kind": "user", "id": user.id},
shared=[{"kind": "team", "id": user.team_id}],
action="report",
cost=25,
):
return build_report(params)
except LimitReachedError as err:
if err.reason == "limit_reached":
return jsonify(
message="Your team is out of credits. Buy more to keep going.",
buyUrl="/billing/credits",
), 402
raise
```
A balance’s `retryAfterSeconds` is `null`, because waiting won’t help. Show a “Buy more credits” button when `remaining` reaches 0, and add the credits from your payment webhook (see [Sell prepaid credits](/docs/guides/prepaid-credits/)). For a limit that resets, tell the user when, from `err.retryAfterSeconds`.
To tell users before they run out, see [Warn your users before they hit a limit](/docs/guides/warn-users/).
# Sync limits from GitHub
> Keep your limits in limitry.json in your repository, review changes in pull requests, and sync them on merge with a short GitHub Actions workflow.
Say you want your limits in your GitHub repository, next to the code that checks them. A change to a limit then goes through a pull request like any other change, and a GitHub Actions workflow syncs it to Limitry when it reaches `main`.
## 1. Write limitry.json
[Section titled “1. Write limitry.json”](#1-write-limitryjson)
Put a `limitry.json` at the root of your repository, listing your limits by name. [limitry.json](/docs/limitry-json/) has every field each limit takes.
```json
{
"limits": [
{
"name": "AI budget",
"subject": { "kind": "user" },
"action": "ai-call",
"amount": 200,
"unit": "cents",
"window": "month",
"failMode": "closed"
},
{
"name": "API burst",
"subject": { "kind": "apikey" },
"action": "api-request",
"amount": 60,
"window": "minute",
"rolling": true
},
{
"name": "Exports at once",
"subject": { "kind": "workspace" },
"action": "export",
"amount": 3,
"window": "concurrent"
}
]
}
```
## 2. Try it in test
[Section titled “2. Try it in test”](#2-try-it-in-test)
Install the [CLI](/docs/cli/) and give it a test key with Limits set to **View and change** under **Custom**. That gives it `limits:read` and `limits:write`. Then ask what a sync would change.
```bash
npm install -g @limitry/cli
export LIMITRY_TOKEN="lim_test_…"
limitry sync --dry-run
```
```text
Would create: AI budget
Would create: API burst
Would create: Exports at once
Dry run: nothing was changed.
```
`limitry sync` reads `./limitry.json`, unless you pass another path. Without `--dry-run`, it makes the changes.
```bash
limitry sync
```
```text
Created: AI budget
Created: API burst
Created: Exports at once
```
Run it again and nothing changes:
```text
No changes: 3 limits already match.
```
A key acts in its own environment, so a test key syncs your test limits and a live key your live ones. Limitry checks the whole file before it changes anything. If one entry is wrong, such as a name used twice, nothing changes and the error says which entry to fix. Add `--json` for the API’s response as JSON.
## 3. Sync from GitHub Actions
[Section titled “3. Sync from GitHub Actions”](#3-sync-from-github-actions)
In your repository’s settings, under **Secrets and variables → Actions**, add a secret named `LIMITRY_API_KEY`: a live key with Limits set to **View and change**. This workflow shows the plan on pull requests that change `limitry.json`, and syncs when the change reaches `main`:
.github/workflows/limitry.yml
````yaml
name: Limitry limits
on:
pull_request:
paths: [limitry.json]
push:
branches: [main]
paths: [limitry.json]
concurrency: limitry-limits
jobs:
limits:
runs-on: ubuntu-latest
env:
LIMITRY_TOKEN: ${{ secrets.LIMITRY_API_KEY }}
steps:
- uses: actions/checkout@v7
# GitHub's runners come with Node.js and npm.
- run: npm install -g @limitry/cli
- name: Plan
if: github.event_name == 'pull_request'
run: |
{
echo "### Limitry: what merging this changes"
echo '```'
limitry sync --dry-run
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: Sync
if: github.event_name == 'push'
run: limitry sync
````
The plan appears on the run’s summary page, so reviewers see which limits a pull request changes, field by field. If the file has a mistake, the step fails and the pull request shows a failed check.
To keep test in step too, add a second secret with a test key and run the same steps with it, for example on pushes to a staging branch.
Once a sync runs on every merge, the file decides. The app locks each limit the file names, and the limit’s page says **Set by limitry.json**. An owner or admin can override one until the next sync. That sync puts the file’s values back. To archive the limits the file doesn’t name, see [When the file is the source of truth](/docs/limitry-json/#when-the-file-is-the-source-of-truth).
This guide is the first of [three ways to sync](/docs/limitry-json/#three-ways-to-sync). If your build writes `limitry.json` from your plans, run the same steps on the file it writes. If you can’t write a file, call `limits.sync` from your code.
# Warn your users before they hit a limit
> Email a user when they've used 80% of a limit, from the webhook Limitry sends, so they're never surprised by a refusal.
A user who hits a limit without warning feels cut off. A user who got an email at 80% had time to slow down or buy more. Limitry sends your server a webhook when a subject reaches 80% and 100% of a limit, and your server decides what to tell the user.
This guide uses the $2 monthly AI budget from [Limit AI spend per user](/docs/guides/limit-ai-spend/), a limit of 200 cents a month on each `user`. The warning at 80% arrives when a user has spent 160 cents.
Limitry never emails your users. You send the message, from your own domain, in your own words.
## 1. Add an endpoint for warnings
[Section titled “1. Add an endpoint for warnings”](#1-add-an-endpoint-for-warnings)
In the app, open **Settings → Developers**, add your endpoint’s URL, pick “Only these” and choose `limit.threshold_crossed`. Copy the signing secret. It’s shown once. Or with the API, using a live key:
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
const limitry = createClient({ apiKey: process.env.LIMITRY_LIVE_KEY });
await limitry.workspace.webhookEndpoints.create({
url: "https://example.com/hooks/limitry",
eventTypes: ["limit.threshold_crossed"],
});
```
* Python
```python
import os
from limitry import Limitry
limitry = Limitry(api_key=os.environ["LIMITRY_LIVE_KEY"])
limitry.workspace.webhook_endpoints.create(
url="https://example.com/hooks/limitry",
event_types=["limit.threshold_crossed"],
)
```
* CLI
```bash
limitry workspace webhook-endpoints create --environment live \
--url https://example.com/hooks/limitry \
--event-type limit.threshold_crossed
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/workspace/webhook-endpoints \
-H "Authorization: Bearer $LIMITRY_LIVE_KEY" \
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/hooks/limitry","eventTypes":["limit.threshold_crossed"]}'
```
## 2. Handle the warning
[Section titled “2. Handle the warning”](#2-handle-the-warning)
The handler verifies the signature, ignores repeats and test traffic, and emails the user:
* TypeScript
```ts
import { verifyWebhook, WebhookVerificationError } from "@limitry/sdk";
// What a limit.threshold_crossed event carries.
type ThresholdCrossed = {
subject: { kind: string; id: string };
environment: "test" | "live";
threshold: 80 | 100;
used: number;
amount: number;
resetsAt: string | null;
};
// `rawBody` must be the request body exactly as it arrived.
app.post("/hooks/limitry", async (req, res) => {
let event;
try {
event = await verifyWebhook(
req.rawBody,
req.headers,
process.env.LIMITRY_WEBHOOK_SECRET!,
);
} catch (error) {
if (error instanceof WebhookVerificationError) {
return res.status(400).send("bad signature");
}
throw error;
}
res.status(200).send("ok"); // respond first, work after
if (event.type !== "limit.threshold_crossed") return;
const data = event.data as ThresholdCrossed;
if (data.environment !== "live") return;
if (data.subject.kind !== "user") return;
// A warning resent after an outage keeps its id: send one email per id.
if (!(await markProcessed(event.id))) return;
const user = await db.users.find(data.subject.id);
if (!user) return;
const resets = data.resetsAt
? ` It resets ${new Date(data.resetsAt).toUTCString()}.`
: "";
await sendEmail({
to: user.email,
subject:
data.threshold === 80
? "You've used 80% of your allowance"
: "You've used all of your allowance",
text:
`You've used ${data.used} of ${data.amount}.` +
resets +
" See your usage at https://example.com/usage.",
});
});
```
* Python
```python
import os
from datetime import datetime
from flask import Flask, request
from limitry import WebhookEvent, WebhookVerificationError, verify_webhook
app = Flask(__name__)
# The body must be exactly as it arrived.
@app.post("/hooks/limitry")
def limitry_hook():
try:
event = verify_webhook(
request.get_data(),
request.headers,
os.environ["LIMITRY_WEBHOOK_SECRET"],
)
except WebhookVerificationError:
return "bad signature", 400
handle_later(event) # respond first, work after
return "ok", 200
def handle_later(event: WebhookEvent) -> None:
data = event.data
if event.type != "limit.threshold_crossed":
return
if data["environment"] != "live" or data["subject"]["kind"] != "user":
return
# A warning resent after an outage keeps its id: send one email per id.
if not mark_processed(event.id):
return
user = db.users.find(data["subject"]["id"])
if not user:
return
resets = (
f" It resets {datetime.fromisoformat(data['resetsAt'].replace('Z', '+00:00')):%a, %d %b %Y %H:%M} UTC."
if data["resetsAt"]
else ""
)
send_email(
to=user.email,
subject="You've used 80% of your allowance"
if data["threshold"] == 80
else "You've used all of your allowance",
text=f"You've used {data['used']} of {data['amount']}.{resets}"
" See your usage at https://example.com/usage.",
)
```
`markProcessed` records the event id and returns `false` if it was already there, for example an insert into a table with the id as its primary key. `sendEmail` is your email provider.
For prepaid credits, a limit with window `total`, `threshold: 80` means 20% of the credits are left and `threshold: 100` means none are. A balance never resets, so `resetsAt` is `null`. Link to your page for buying more instead of a reset time. After you add credits, the balance can warn again the next time it runs low.
The payload and how often each kind of limit warns are in [Webhooks](/docs/webhooks/#warnings-before-a-limit).
## 3. Try it in test
[Section titled “3. Try it in test”](#3-try-it-in-test)
The endpoint from step 1 belongs to live and receives only live events. To try the warning, add a test endpoint the same way, with the app on **test**, or through the API with a personal access token (it acts in test by default). It has its own signing secret. Point it at a test copy of your handler, or let your handler through for test events while you try it.
Then, with the test key, make `ai-call` checks for one user until they pass 80% of the test budget. A single check with a `cost` of 170 does it. The warning reaches the test endpoint within about a minute, with `"environment": "test"`.
## Show the numbers too
[Section titled “Show the numbers too”](#show-the-numbers-too)
An email says “you’re close”. A usage bar in your app says exactly how close at any time. See [Show users where they stand](/docs/guides/show-usage/).
# How Limitry works
> Where Limitry decides, why counts stay exact under load, what happens if Limitry is down, and what data it keeps.
## Where Limitry decides a check
[Section titled “Where Limitry decides a check”](#where-limitry-decides-a-check)
Your check reaches Limitry at the location nearest the server that sent it. Each subject’s counts live in one place, so Limitry decides every check for that subject against the same numbers. When a check also draws from a shared pool, such as a team’s, Limitry first reserves the cost on every subject. It charges them only if every limit fits.
Two things follow from this:
* **Counts are exact.** Two requests racing for the last unit can’t both get it, and a pool shared by many users is never overspent. Limitry saves every count before it responds, so a limit stays exact even if a server fails.
* **Changes reach checks at once.** A new or edited limit applies to the next check. A revoked API key can keep working for checks for up to 60 seconds.
## Choosing a region
[Section titled “Choosing a region”](#choosing-a-region)
Limitry keeps each workspace’s counts in one region and sets them up before your first check. A brand-new user, team or agent gets a decision as fast as one you’ve checked a thousand times. A check sent from another continent has to cross the ocean to reach those counts, which adds 100 to 200 ms.
Under **Settings → General**, an owner or admin sets **Region** to where your servers run: Western or Eastern North America, Western or Eastern Europe, Asia-Pacific, or Oceania. The default, **Automatic**, keeps your counts in Eastern North America. One setting covers test and live. The card shows the city your live counts are in, and where most of your live checks come from.
Changing the region moves every count, balance and open reservation there in the background. Nothing goes missing or counts twice, and checks keep working while it moves. Your counts move in parts. Each part pauses while it moves, usually for a few seconds and never more than 30. If a part takes longer, Limitry puts it back and tries again later. A check that arrives during a pause gets `503 moving`, and the SDKs retry it with the same idempotency key.
The page shows how far the move has got. Limitry saves the new region once everything has moved, and you can’t change it again until then. The region is a preference, not a guarantee. Limitry runs on Cloudflare, and Cloudflare picks the data center within it.
## When your code can’t reach Limitry
[Section titled “When your code can’t reach Limitry”](#when-your-code-cant-reach-limitry)
Every limit has a fail mode, which you choose per limit:
* `open`, the default: your code goes ahead as if allowed.
* `closed`: your code says no, as if Limitry had refused the check.
The SDK applies it for you. When Limitry doesn’t respond within 1.5 seconds, or returns a `429`, a `5xx` or `402 plan_limit_reached`, `guard` and `reserve` fall back to the fail mode of the limits they saw last. Under `closed`, they throw `UnavailableError`. That’s a different error from a refusal, which throws `LimitReachedError`. Choose `closed` where overspending would hurt more than refusing, such as an agent’s spending budget.
A `concurrent` limit that fails `open` still holds. While your code can’t reach Limitry, `reserve` runs at most the limit’s `amount` at once in your process, and throws `UnavailableError` beyond that. See [Rolling windows and concurrency](/docs/rolling-and-concurrency/#concurrency).
## Retries
[Section titled “Retries”](#retries)
Limitry counts a check sent with an `Idempotency-Key` header only once. For an hour, repeating it with the same key returns the same decision and counts nothing. Keys on commits, releases and resets last 24 hours, and a key on a credit never expires. `guard`, `reserve`, the SDKs and the CLI send a key for you and retry with it. Committing or releasing a reservation is safe to retry too. See [Idempotency](/docs/idempotency/).
## Work that crashes
[Section titled “Work that crashes”](#work-that-crashes)
A [reservation](/docs/reservations/) that nobody commits or releases gives itself back when it expires, after 5 minutes by default. A worker that crashes in the middle of a job never leaves a user blocked or a concurrency slot taken.
## What Limitry stores
[Section titled “What Limitry stores”](#what-limitry-stores)
* Your limits, plus a record of every change to them in the workspace’s audit log.
* Hourly counts for each limit and subject, kept as long as your plan keeps history. [Usage](/docs/usage/) lists how long each plan keeps them.
* The subject kinds and ids you send. Limitry attaches no meaning to them, so send your own opaque ids such as `user_123`, not names or email addresses.
* Any names and labels you give subjects. They’re optional, and `DELETE /v1/subjects/{subjectKind}/{subjectId}/names` erases them. See [Subjects, names and links](/docs/subjects/).
* Each check of the last 3 days: the subjects it named, its action and cost, and whether Limitry allowed it. Limitry keeps at most 100,000 in each environment.
Limitry never sees the work itself, such as prompts, model output or files. A check carries a subject, an action name and a number.
## Test and live
[Section titled “Test and live”](#test-and-live)
Every workspace has a test environment and a live environment, each with its own limits, counts, balances, reservations and usage. The API key decides which one a check uses: `lim_test_…` or `lim_live_…`. Test checks can’t move live counts, and they have their own allowance that isn’t billed. See [Test and live](/docs/test-and-live/).
## Access
[Section titled “Access”](#access)
An API key belongs to a workspace and one environment. Its scopes say what it may do: `checks:write` to check, and `limits:read` and `limits:write` to read and manage limits. Give each service the narrowest key it needs. Personal access tokens act as the person who created them. See [Authentication](/docs/authentication/).
# Idempotency
> Retry writes safely with the Idempotency-Key header.
A request can time out after the API has already acted on it. To retry a write safely, without doing it twice, send an `Idempotency-Key` header. Any unique string of up to 255 printable ASCII characters works, and a UUID for each operation is a good choice.
```bash
curl -X POST \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: 6f1c2e9a-8b3d-4c47-9a51-0d2f7e4b8c13" \
-H "Content-Type: application/json" \
-d '{ … }' \
https://api.limitry.com/v1/…
```
The first request with a key runs normally. If you retry the same request with the same key, you get the first response back, with the same status and body, and the operation doesn’t run again. A replayed response carries the header `Idempotency-Replayed: true`.
## What the SDKs, the CLI and the MCP server do
[Section titled “What the SDKs, the CLI and the MCP server do”](#what-the-sdks-the-cli-and-the-mcp-server-do)
* **Every write sends a key.** If you don’t pass one, the client makes one for that call.
* **The client retries a failed attempt with the same key.** It retries after:
* a network error, or an attempt that timed out
* a `408` or a `429`
* a `500`, `502`, `503` or `504`
* a `409` with the code `idempotency_in_progress`
It tries each call up to 3 times in all, waiting as long as `Retry-After` says when the API sends one. If `Retry-After` is longer than 60 seconds, it returns the error to you instead.
* **Pass your own key** when you might run the whole call again yourself, for example when a job reruns or you receive a webhook twice. Send the same key both times:
* TypeScript: `{ idempotencyKey: id }` as the last argument.
* Python: the `idempotency_key=id` keyword.
* CLI: `--idempotency-key
`. When a command makes several writes, it derives a key for each one from yours, so running it again with the same key repeats none of them.
* MCP: every tool that changes something takes an optional `idempotencyKey` argument.
* **Turn the retries off** with `maxRetries: 0` in TypeScript or `max_retries=0` in Python.
## Checks and reservations
[Section titled “Checks and reservations”](#checks-and-reservations)
* **Checks follow the same rules.** A repeat of a check with the same key gets the first decision back, marked `Idempotency-Replayed: true`, and isn’t counted again. That holds for a check across several subjects too. Sending the same key with a different check gets `409 idempotency_key_reused`.
* **`guard` and `reserve` send a key for you.** Pass your own as `idempotencyKey`, or `idempotency_key=` in Python. If a check fails quickly, they retry it at most twice with the same key, as long as there’s still time before they stop waiting. If a reservation’s check gets no response in time, your work runs under the limit’s fail mode. Afterwards, `reserve` asks again with the same key and releases any reservation Limitry made, so it isn’t held until it expires.
* **`guard` finishes a check that timed out.** When its check gets no response in time and the limit fails open, `guard` sends it once more, with the same key and the header `limitry-finish-only: 1`. TypeScript sends it in the background. Python sends it after the block, within `timeout`. Limitry then finishes the check if it had started it. Otherwise it decides nothing and returns `404`.
* **Committing and releasing are safe to repeat without a key.** The same commit or release gets the same response. Committing again with a different cost gets a `400`.
## The rules
[Section titled “The rules”](#the-rules)
* **Writes only.** The header applies to `POST`, `PUT`, `PATCH` and `DELETE`. Reads ignore it, since they’re already safe to repeat.
* **One key per request.** A key belongs to one request: the same endpoint with the same body. Sending it with a different request fails with `409 idempotency_key_reused`. Generate a new key for each operation, and reuse one only to retry that operation.
* **A retry during the first request waits.** If the first request is still running, a retry gets `409 idempotency_in_progress` with a `Retry-After` header. Wait that many seconds, then retry.
* **We store only final responses.** A final response is a success, or an error a retry would get again, such as a `400` or a `404`. Every retry gets that same response back. We don’t store errors a retry might get past. For these, a retry with the same key runs the request again:
* a `5xx`
* a `402`, once you’ve upgraded your plan
* a `409`
* a `429`, once there’s room again
* **How long a key lasts depends on the request.** After that, the same key starts a new request.
| Request | The key lasts |
| ------------------------------ | ------------- |
| A check | 1 hour |
| A commit, a release or a reset | 24 hours |
| A credit | For ever |
If you send a new credit with a key you’ve already used for a credit, Limitry ignores it, however long ago that was. Never reuse a credit’s key.
* **A key belongs to the API key or token that sent it,** so two integrations never collide. A personal access token’s keys are also separate in each workspace and each environment.
* **We protect stored responses.** We keep a hash of your key, never the key itself, and encrypt the stored response with a key derived from yours. Only a retry that sends your key can read it back.
Sending a key yourself is optional. The SDKs, the CLI and the MCP server send one on every write.
# limitry.json
> The file that keeps your limits in your repository, every field it takes, and how a sync applies it.
`limitry.json` is optional. Use it if you want your limits in your repository, changed through pull requests. Otherwise, create them in the app, from the API or with the CLI, as [Limits](/docs/limits/) shows. The file lists the limits you want. `limitry sync` reads `./limitry.json`, or another path you pass, and makes your limits match it. To run that on every merge, see [Sync limits from GitHub](/docs/guides/sync-from-github/).
## Three ways to sync
[Section titled “Three ways to sync”](#three-ways-to-sync)
A sync makes your limits match a list. You can send that list three ways:
1. **Keep `limitry.json` in your repository and run `limitry sync`.** This is the default, and the rest of this page describes it.
2. **Generate `limitry.json` from your plans or code, then run `limitry sync`.** Your build writes the file, for example from your own plan catalog, and the CLI syncs it as in the first way. See [A generated file](#a-generated-file).
3. **Call `limits.sync` from your code.** Use this only if you can’t write a file. See [From your code](#from-your-code).
Each way locks the limits it sets in the app, and names where they came from. See [When the file is the source of truth](#when-the-file-is-the-source-of-truth).
```json
{
"limits": [
{
"name": "AI budget",
"subject": { "kind": "user" },
"action": "ai-call",
"amount": 200,
"unit": "cents",
"window": "month",
"failMode": "closed"
},
{
"name": "API burst",
"subject": { "kind": "apikey" },
"action": "api-request",
"amount": 60,
"window": "minute",
"rolling": true
},
{
"name": "Exports at once",
"subject": { "kind": "workspace" },
"action": "export",
"amount": 3,
"window": "concurrent"
}
]
}
```
## The file
[Section titled “The file”](#the-file)
| Field | Description |
| -------------------------- | ----------------------------------------------------------------------------------------------- |
| `limits` (array, required) | Every limit you want, at most 200. Each entry takes the fields below, and its `name` is unique. |
| `kinds` (array) | Optional. How the app names your kinds, from the top level down. See [Kinds](#kinds). |
## Kinds
[Section titled “Kinds”](#kinds)
`kinds` is optional. It names the kinds your checks send, and puts them in order from the top level down, as the **Kinds** card in Settings does. A subject’s page uses the order to split the subjects it’s checked with into **Above** and **Below**.
```json
{
"limits": [],
"kinds": [
{ "kind": "account" },
{
"kind": "cost-center",
"displayName": "Cost center",
"plural": "Cost centers"
},
{ "kind": "user" }
]
}
```
| Field | Description |
| ------------- | --------------------------------------------------------------------------- |
| `kind` | The kind, as your checks send it. Each kind appears once. |
| `displayName` | Optional. How the app names it. Default: the kind, starting with a capital. |
| `plural` | Optional. Its plural. Default: one made from the name. |
A sync with `kinds` replaces the workspace’s kinds, for test and live alike, so only owners and admins (or a workspace API key) can send it. The **Kinds** card is then locked, with the same override as a limit, and names the sync’s source in the same way. A sync whose file has no `kinds` keeps the kinds as they are and makes them editable in the app again. The kinds are labels only: your checks and the API keep using the kinds themselves.
Subject names and labels don’t go in `limitry.json`. They’re your users’ data, and often personal. A repository keeps every version in its history, so a name erased with `DELETE /v1/subjects/{subjectKind}/{subjectId}/names` would stay there. Set them with the API, an import or the CLI instead (see [Subjects, names and links](/docs/subjects/)).
## Each limit
[Section titled “Each limit”](#each-limit)
Each entry takes the same fields as creating a limit. Every entry needs a `name`, because a sync matches limits by name.
| Field | Description |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` string | The limit's name, unique among the environment's active limits. By default, it's the sentence the limit reads as, such as "200 cents per user per month". If another limit already has that name, you get a 409, so send a name of your own. |
| `subject` object, required | Who the limit applies to. `{"kind": "user"}` covers every user, and `{"kind": "user", "id": "user_123"}` covers one. |
| `action` string | The action to limit. Default: `*`, every action. |
| `amount` number, required | How many units each subject may use per window. |
| `unit` string | What the amount counts, in words. Default: units. |
| `window` string, required | The kind of period. `minute`, `hour`, `day`, `week`, `month` and `year` count a period of `every` windows, which resets where `start` says, or rolls when `rolling` is true. `total` is a balance that never resets, and credits raise it. `concurrent` allows at most `amount` open reservations at once. |
| `every` number | How many `window` units one period lasts. For example, `window: "month", every: 3` is a quarter, and `window: "hour", every: 5` is five hours. Default: 1. |
| `start` string | Where each period begins. `calendar` uses UTC boundaries: midnight, Monday, the 1st or 1 January. `billing_date` counts from the subject's billing date. You set it with `subjects.update`. An annual plan can then still reset monthly. Until a subject has a billing date, its first check stands in for it. `first_use` starts a period at the first check after the previous one ended. Default: calendar. |
| `rolling` boolean | Whether to count the last `every` windows up to the moment of each check, rather than fixed periods. Only `minute`, `hour` and `day` limits can roll. Default: false. |
| `enabled` boolean | Whether checks enforce the limit. Default: true. |
| `failMode` string | What your code should do when it can't reach Limitry. `open` allows and `closed` refuses. Default: open. |
From the API's [Create a limit](/docs/reference/limits/#create-a-limit).
A sync matches each entry to a limit by name:
* When the environment has no limit with that name, the sync creates one.
* When a limit has that name but different fields, the sync changes it.
* When a limit already matches, the sync leaves it alone.
Each entry describes its limit in full. A field you leave out means its default, as when you create a limit. If you remove `"failMode": "closed"` from the file, the next sync sets it back to `open`.
## Changing what a limit counts
[Section titled “Changing what a limit counts”](#changing-what-a-limit-counts)
A sync can change a limit’s `amount`, `failMode` and `enabled`. Once a limit exists, you can’t change what it counts: its `subject`, `action`, `unit`, `window`, `every`, `start` and `rolling`. See [What can change](/docs/limits/#what-can-change). If an entry changes one of those under the same name, the sync changes nothing and says which entry to fix.
To change one, rename the entry. The sync then creates a new limit under the new name. It leaves the old limit as it is, or archives it when you add `--archive-missing`. The old limit’s history stays.
## Syncing
[Section titled “Syncing”](#syncing)
```bash
limitry sync --dry-run # what a sync would change; changes nothing
limitry sync # make your limits match the file
limitry sync other.json # read another file
limitry sync - # read the file from stdin
```
A key acts in its own environment, so a test key syncs your test limits and a live key your live ones. Limitry checks the whole file before it changes anything. If one entry is wrong, nothing changes, and the error says which entry to fix. Add `--json` to see the API’s response as JSON.
## When the file is the source of truth
[Section titled “When the file is the source of truth”](#when-the-file-is-the-source-of-truth)
Once you sync, the file decides. Each limit the file names is locked in the app and in the API. Its page says **Set by limitry.json**, and `PATCH /v1/limits/{limitId}` answers `409 conflict` with a message that names the file. Change the file and sync instead. A limit the file stops naming can be changed in the app again.
The lock names the sync’s `source`. The limit’s `setIn` holds it, and the audit log records it.
| How you sync | The lock says |
| ---------------------------------------- | ---------------------------- |
| `limitry sync` | Set by limitry.json |
| `limitry sync config/limits.json` | Set by config/limits.json |
| `limitry sync --source "Billing deploy"` | Set by Billing deploy |
| `limitry sync -` (stdin) | Set by a sync |
| `limits.sync` with `source` | Set by the `source` you sent |
| `limits.sync` without `source` | Set by a sync |
In an emergency, an owner or admin can override a locked limit until the next sync. On the limit’s page, choose **Override until next sync**, change it, and give a reason. From the API, send `override` with a `reason` in the same `PATCH`. The audit log keeps the reason, and the limit’s page says the next sync will restore the file’s values. You can’t rename a locked limit, because the sync finds it by its name.
The next sync puts the file’s values back. `limitry sync --dry-run` lists each override it would end, and the sync’s answer lists them in `restored`. The person who made each override gets a notification.
| What | In the app and the API |
| ----------------------------------------------------------- | -------------------------------------------- |
| Limits the file names | Locked. An owner or admin can override one. |
| Limits the file doesn’t name | Editable. |
| Kinds, when the file has `kinds` | Locked. An owner or admin can override them. |
| Kinds, when the file has no `kinds` | Editable. |
| Subject names and labels, billing dates, resets and credits | Editable. A file never sets them. |
A sync doesn’t touch limits the file doesn’t name, so limits you manage in the app keep working beside the file. To make the file the whole list, add `--archive-missing` to both commands in the workflow. A sync then archives every active limit that isn’t in the file. Archiving keeps a limit’s usage history and credits, and you can restore it from the **Limits** page or with `limitry limits restore `. Before you merge, run `limitry sync --dry-run` to list the limits a sync would archive.
## A generated file
[Section titled “A generated file”](#a-generated-file)
If your limits come from your plans or code, write `limitry.json` in your build or deploy, then run `limitry sync` as usual. The CLI checks the file the same way, and the lock names the file. To name your deploy instead, add `--source`:
```bash
# After your build writes build/limitry.json
limitry sync build/limitry.json --dry-run
limitry sync build/limitry.json --source "Billing deploy"
```
A script that prints the file can pipe it in with `-`. Piped in, the file has no name, so add `--source` to name it in the lock:
```bash
node scripts/limits.mjs | limitry sync - --source "Billing deploy"
```
If you can, commit the generated file too. Then a pull request shows each change to your limits before it’s synced.
## From your code
[Section titled “From your code”](#from-your-code)
If you can’t write a file, call `limits.sync` from your code. The SDKs have the same operation as `limitry sync`. Send `source` to name where the limits come from. Without it, the lock says **Set by a sync**.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.limits.sync({
source: "Billing deploy",
limits: [
{
name: "AI budget",
subject: { kind: "user" },
action: "ai-call",
amount: 200,
unit: "cents",
window: "month",
},
],
dryRun: true,
});
console.log(result.created, result.updated, result.archived);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.limits.sync(
source="Billing deploy",
limits=[
{
"name": "AI budget",
"subject": {"kind": "user"},
"action": "ai-call",
"amount": 200,
"unit": "cents",
"window": "month",
}
],
dry_run=True,
)
print(result.created, result.updated, result.archived)
```
Leave out `dryRun` (`dry_run` in Python) to apply the list. To archive limits the list doesn’t name, pass `archiveMissing`, or `archive_missing` in Python. The response lists the names it created, updated, archived and left unchanged. Each updated name comes with each field’s old and new value.
# Limits
> How much each subject may use in each window, how several limits combine, and what you can change once a limit exists.
A limit says how much a subject may use per window. It reads as one sentence: *each user may use 200 cents per month*. Subjects are whoever acts in your product, such as your users, teams, API keys or AI agents. You choose the labels, and Limitry only matches them.
## The three kinds
[Section titled “The three kinds”](#the-three-kinds)
| Kind | Reads as | `window` |
| --------------- | --------------------------------------------------- | --------------------------------------------------------------------------------- |
| Per period | each user may use 100 credits per month | `minute`, `hour`, `day`, `week`, `month` or `year` |
| Balance | each user starts with 500 credits, and you add more | `total`, a balance that never resets |
| Running at once | each user may run 3 at the same time | `concurrent`: a slot per running job (a reservation), given back when it finishes |
In the app, **Add limit** on the **Limits** page asks for the kind, then the sentence: *Each \[user] may use \[100] \[credits] per \[month].* Everything else is under **More options**, with the defaults listed below. A preview shows what a subject would see. After you save, **Add another limit** opens a new one with the same unit and period filled in.
## Fields
[Section titled “Fields”](#fields)
A limit needs only `subject.kind`, `amount` and `window`.
| Field | Meaning |
| ---------- | -------------------------------------------------------------------------------------------------------------------------- |
| `subject` | Who it applies to. `{"kind": "user"}` is every user. Add `"id": "user_123"` for one subject. |
| `amount` | How many units per window. For `concurrent`, how many at once. |
| `window` | `minute`, `hour`, `day`, `week`, `month`, `year`, `total` or `concurrent`. See below. |
| `action` | The action it limits. Default `*`, every action. |
| `unit` | What the amount counts (`calls`, `credits`, `cents`), in words. Default `units`. |
| `name` | Your label, unique among the environment’s active limits. Default: the sentence, such as “100 credits per user per month”. |
| `every` | How many windows a period lasts: `every: 3` with `month` is a quarter. Default `1`. |
| `start` | Where a period begins: `calendar` (the default), `billing_date` or `first_use`. See [When limits reset](/docs/resets/). |
| `rolling` | With `minute`, `hour` or `day`: count the last `every` windows up to each check, such as any 60 minutes. Default `false`. |
| `failMode` | What your code should do when it can’t reach Limitry: `open` (allow, the default) or `closed` (refuse). |
| `enabled` | Whether checks enforce it. Default `true`. |
A name made from the sentence names the action when it isn’t `*`: “100 credits per user per month for ai-call”. If another active limit already has that name, the API returns `409` with `conflict` and creates nothing. Send a `name` of its own.
Limitry saves every count before it returns a decision, whatever the limit. There is no faster mode that could lose a count.
## Windows
[Section titled “Windows”](#windows)
* `minute`, `hour`, `day`, `week`, `month` and `year` reset at the end of each period. By default a period ends on a UTC boundary. It can instead end on each subject’s billing date, or a set time after its first use. A period can also be several windows long, such as every 3 months or every 5 hours. See [When limits reset](/docs/resets/).
* `minute`, `hour` and `day` can also be [rolling](/docs/rolling-and-concurrency/): they count the last 60 seconds, minutes or 24 hours.
* `total` is a balance that never resets, for prepaid credits. See [Pools, balances and budgets](/docs/pools-and-budgets/).
* `concurrent` allows at most `amount` at once. See [Rolling windows and concurrency](/docs/rolling-and-concurrency/).
When several limits match a subject and action, all of them apply. That is how you give each of your users a $2 AI budget a month and at most 50 cents a day, so one day can’t use up the month. You make two limits, and a check has to fit both.
There’s one exception. A limit set for one subject, with `subject.id`, replaces the limit for its whole kind that has the same action and window. Use it to give one customer more or less than everyone else. The kind’s other limits still apply to that customer. A subject with its own `minute` limit is still held to the kind’s `day` limit.
To limit a user, their team and their tenant at once, make one limit for each and name all three in the check. See [Budgets at several levels](/docs/guides/several-levels/).
## Creating a limit
[Section titled “Creating a limit”](#creating-a-limit)
In the app, limits are on the **Limits** page. Everyone in the workspace can see them. The owner and admins can change them, and members can in test. From your code or the CLI, a key or token needs the `limits:read` or `limits:write` scope.
[   ](/docs/_astro/limits.Yx4KQJdi.png "Open the screenshot at full size")
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
// Named "200 cents per user per month for ai-call"
const limit = await limitry.limits.create({
subject: { kind: "user" },
action: "ai-call",
amount: 200,
unit: "cents",
window: "month",
failMode: "closed",
});
console.log(limit.id);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
# Named "200 cents per user per month for ai-call"
limit = limitry.limits.create(
subject={"kind": "user"},
action="ai-call",
amount=200,
unit="cents",
window="month",
fail_mode="closed",
)
print(limit.id)
```
* CLI
```bash
limitry limits create --subject '{"kind":"user"}' --action ai-call \
--amount 200 --unit cents --window month --fail-mode closed
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/limits \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"subject":{"kind":"user"},"action":"ai-call","amount":200,
"unit":"cents","window":"month","failMode":"closed"}'
```
An AI agent can do the same through the [MCP server](/docs/mcp/). The workspace’s audit log records every change, and a change reaches [checks](/docs/checks/) at once.
## What can change
[Section titled “What can change”](#what-can-change)
You can change a limit’s name, amount and fail mode at any time, and turn it off or on. Once a limit exists, you can’t change what it counts: its `subject` kind and id, `action`, `unit`, `window`, `every`, `start` and `rolling`. A change to one of them would start the limit’s counts over, or compare counts in the wrong unit. Limitry refuses it with `400 invalid_request` and a message saying what to do instead.
To change what a limit counts, create a new limit with the new values, then archive the old one. The old limit’s history stays. In the app, the edit view shows the fixed fields as text, with “Create a new limit to change this”. In a [`limitry.json`](/docs/limitry-json/), give the entry a new name.
A limit that’s off (`enabled: false`) never refuses, but checks still count against it. When you turn it on again, it starts from what your subjects actually used, not from zero.
## A limit no check reaches
[Section titled “A limit no check reaches”](#a-limit-no-check-reaches)
Each limit’s `lastCheckedAt` says when a check last reached it, to the hour. When no check has reached a limit in 7 days, the **Limits** page flags it and names the subject kind it’s waiting for. This usually means your checks send a different subject kind or action than the limit has, such as `teams` instead of `team`. Fix the check, or create a limit that matches it.
## A limit’s page
[Section titled “A limit’s page”](#a-limits-page)
On the **Limits** page, each limit shows how many checks reached it and how many it refused. A rate limit counts today. A weekly limit counts this week. A monthly or yearly limit, and a balance, count this month. Click a limit’s name to open its page.
| Part | What it shows |
| -------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Last 30 days | The checks the limit allowed and refused each day, and what they used. |
| Closest to the limit | The subjects that used the most in the current window, each against its allowance. |
| Refused lately | The subjects the limit refused in the last 7 days, the most refused first. |
| Settings | The allowance, who and which action it applies to, when it resets, and what happens if your code can’t reach Limitry. |
A balance’s page also has **Credits**, which lists every credit added to it. When your plan keeps less history, the chart shows fewer days.
## Who’s told
[Section titled “Who’s told”](#whos-told)
When a live limit refuses one of your users, Limitry tells the workspace’s owners and admins. It also tells them when one of your users passes 80% or 100% of a live limit. Each limit sends each notification at most once a day. Each person chooses whether it reaches them in the app, by email or on their phone. See [Notifications](/docs/notifications/).
## Managing limits
[Section titled “Managing limits”](#managing-limits)
Test and live each have their own limits. The app shows the environment you picked at the top right. A key manages the limits of its own environment. Set limits up in test, then click **Copy to live** to create or update them in live. See [Test and live](/docs/test-and-live/).
Every call about one limit takes its name in place of its ID, such as `GET /v1/limits/AI%20budget` or `limitry limits get "AI budget"`. A name matches an active limit in the same environment. An exact match comes first. Otherwise, the name matches whatever its case. When two limits match that way, the call fails with a 400 that names both. Restoring a limit by name looks among the archived ones.
To keep your limits in your repository instead, list them in a [`limitry.json`](/docs/limitry-json/) and run `limitry sync`. It matches your limits to the file by name, creating and changing them as needed. It archives limits that aren’t in the file only when you ask it to. You can run it from your machine or from CI. See [Sync limits from GitHub](/docs/guides/sync-from-github/). A limit the file names is locked in the app and the API, except for an override until the next sync. Its page says **Set by limitry.json**, or names whatever else the sync came from (see [When the file is the source of truth](/docs/limitry-json/#when-the-file-is-the-source-of-truth)). You can also generate the file from your plans, or sync from your code (see [Three ways to sync](/docs/limitry-json/#three-ways-to-sync)).
## Trying a limit in the app
[Section titled “Trying a limit in the app”](#trying-a-limit-in-the-app)
In test, the **Limits** page has **Try a check**. Pick a limit, type a subject id such as `user_123`, and click **Check**. You get the same response your code would get from a check with a test key: allowed or refused, and what’s left on every limit that applies. To see a refusal, keep clicking until a limit says no. These checks count against your test allowance, and we don’t bill them. Owners, admins and members can try checks, and only in test. In live, every check would count for real.
## Examples to start from
[Section titled “Examples to start from”](#examples-to-start-from)
While a workspace has no limits in test, the **Limits** page offers **Add example limits**. It adds three limits, each named “Example: …”. They cap images per user per day, set an AI budget per user per month, and allow API calls per key per minute. **Simulate traffic** then sends a few hundred test checks from pretend users and keys, enough for some to get a no. The [Usage](/docs/usage/) page shows them within a minute. **Remove examples** archives the example limits and nothing else. Examples are for test only.
## Archiving a limit
[Section titled “Archiving a limit”](#archiving-a-limit)
Limitry never erases a limit. When you no longer need one, archive it. On the Limits page, open the limit’s ⋮ menu and choose **Archive**, or run `limitry limits archive `. The API’s `POST /v1/limits/{limitId}/archive` answers with the archived limit. Checks stop enforcing it at once and don’t count against it while it’s archived. It leaves the list, but its usage history and credits stay. The [Usage](/docs/usage/) page still shows it, marked archived. **Archived limits** on the Limits page lists them, and **Restore** (or `limitry limits restore `) brings one back. An archived limit’s name is free, so a new limit can take it. You can’t restore a limit while another active limit has its name.
# MCP server
> Connect Claude, ChatGPT, Claude Code, Codex or another MCP client to your workspace, and see what it can do there and how you stay in control.
Chat apps such as Claude and ChatGPT, and coding agents such as Claude Code and Codex, support the Model Context Protocol (MCP). Any of them can work in your workspace through our MCP server:
```text
https://mcp.limitry.com/mcp
```
## Connect
[Section titled “Connect”](#connect)
Add the address above to your agent as a remote MCP server:
* **Claude:** **Customize → Connectors → + Add → Add custom connector**. On a Team or Enterprise plan, an owner adds it under **Organization settings → Connectors**, and each person then clicks **Connect** under **Customize → Connectors**.
* **ChatGPT:** go to [chatgpt.com/plugins](https://chatgpt.com/plugins), click **+**, then **Add custom MCP server**. Enter the address, click **Create as a plugin** and install it. On a Business or Enterprise plan, an admin allows custom MCP servers first.
* **Claude Code:** run `claude mcp add --transport http limitry https://mcp.limitry.com/mcp`, then `/mcp` in Claude Code to sign in.
* **Codex:** run `codex mcp add limitry --url https://mcp.limitry.com/mcp`, then `codex mcp login limitry`.
* **Cursor, GitHub Copilot in VS Code, Windsurf, Gemini CLI, or another app that supports remote MCP servers:** add the address in its MCP settings, and sign in when it asks.
The first time the agent connects, your browser opens:
1. Sign in, if you aren’t already.
2. Choose the **one workspace** the agent will work in.
3. Choose what the agent may do. Anything that can change data starts unticked, so tick only what the agent needs.
4. Click **Allow**.
There’s nothing to copy and no key to store. The agent gets its own sign-in, which works only for the workspace and the access you chose.
## Test and live
[Section titled “Test and live”](#test-and-live)
When you sign in, you choose where the agent works by default: **Test** (practice data your developers use) or **Live** (your real customers). It starts on Test. Test limits and counts are separate from live ones, so an agent trying things out can’t refuse your real customers by mistake. To switch, reconnect and choose the other. Your choice shows in **Account → Apps and agents**.
An address ending in `?environment=live` or `?environment=test` overrides the choice, for example to keep a second connector for live:
```text
https://mcp.limitry.com/mcp?environment=live
```
Every tool result ends with `Environment: test` or `Environment: live`, so you and the agent can always tell which side it used. See [Test and live](/docs/test-and-live/).
## What the agent can do
[Section titled “What the agent can do”](#what-the-agent-can-do)
The agent’s tools are the [API](/docs/reference/) operations you allowed, such as reading the workspace or listing webhook deliveries. It always acts as **you**, with your role in the workspace. It can do only what you could do in the app. Everything it changes shows up in the workspace’s audit log under your name.
Even with full access, an agent can’t send your workspace’s data somewhere new or hand out access by itself, for example by creating a webhook endpoint or a credential. It can **ask** instead, and you approve or deny the request in the app. If the action creates a secret, the app shows it to you, never to the agent. [Approvals](/docs/approvals/) explains how.
## Staying in control
[Section titled “Staying in control”](#staying-in-control)
* **Account → Apps and agents** lists every agent you’ve connected. Disconnect one and it stops working at once.
* The workspace’s **audit log** records what each agent did.
* If you’re removed from the workspace, your agents lose access too.
## For developers
[Section titled “For developers”](#for-developers)
The server follows the MCP authorization specification. A request without a token gets a `401` that points to `/.well-known/oauth-protected-resource/mcp`, which names the authorization server, `https://api.limitry.com/auth`. That server supports dynamic client registration and PKCE, and issues tokens for the MCP server only.
Every tool that changes something takes an optional `idempotencyKey`. If an agent calls the tool again after an error or a timeout, the same key makes sure the change happens only once. Within a single call, the server also retries a failed attempt with that call’s key. [Idempotency](/docs/idempotency/) has the details.
For your own scripts, the [CLI](/docs/cli/) or the [SDK](/docs/typescript/) is simpler. For the agent skill, see [Build with AI agents](/docs/agents/).
# Notifications
> Hear in the app, by email or on your phone when a live limit refuses one of your users or nears its end.
Limitry tells your team when a live limit needs attention. You don’t need any code for it: it works as soon as your app checks a live limit.
## What Limitry sends
[Section titled “What Limitry sends”](#what-limitry-sends)
| Notification | Sent when | Starts as |
| -------------------------------------- | ------------------------------------------------------------------- | ---------------- |
| A user hit their limit | A live limit refuses one of your users. | In app and email |
| A user used 80% or 100% of their limit | One of your users passes 80% or 100% of a live limit. | In app and email |
| A sync put back a limit you overrode | A [sync](/docs/limitry-json/) ends an override you made in the app. | In app and email |
Each limit sends each of the first two notifications at most once a day. The notification names the first user it happened to. Opening it shows that limit’s page, in live.
Limits in test send none of the first two. A sync sends the third in test and live alike.
## Who gets them
[Section titled “Who gets them”](#who-gets-them)
Limitry sends the first two to the workspace’s owners and admins. See [Plan allowances](/docs/plans/#people-and-roles) for the roles. The third goes only to the person who made the override.
## Choosing how they reach you
[Section titled “Choosing how they reach you”](#choosing-how-they-reach-you)
Each person chooses for themselves. Open **Account**, then **Notifications**, then **Settings**. Each notification has a switch for **In app**, **Email** and **Push**.
Push is off to start with. To get push on a phone or computer, click **Turn on push** on that device and allow notifications when your browser asks. Do it once on each device.
On an iPhone or iPad, push only reaches apps on the Home Screen. Open Limitry in Safari, tap **Share**, then choose **Add to Home Screen**. Open it from there and turn on push.
## In your own app
[Section titled “In your own app”](#in-your-own-app)
Notifications tell your team. To tell your users, or to act in your own code, use the `limit.reached` and `limit.threshold_crossed` webhooks. They arrive for every subject, in test and live. See [Webhooks](/docs/webhooks/).
# Pagination
> How list endpoints return results a page at a time.
List endpoints return results newest first, a page at a time. Each page comes with a cursor that points to the next one.
```bash
curl \
-H "Authorization: Bearer YOUR_API_KEY" \
"https://api.limitry.com/v1/workspace/audit-events?limit=25"
```
```json
{
"items": [
{
"id": "aud_6b2f9e1c-3d4a-4f8b-9e7c-1a2b3c4d5e6f",
"action": "workspace.member.invited",
"createdAt": "2026-08-19T12:00:00.000Z"
}
],
"nextCursor": "eyJ0IjoiMjAyNi0wOC0uLi4ifQ"
}
```
To get the next page, send the cursor back as it is:
```bash
curl \
-H "Authorization: Bearer YOUR_API_KEY" \
"https://api.limitry.com/v1/workspace/audit-events?limit=25&cursor=eyJ0IjoiMjAyNi0wOC0uLi4ifQ"
```
Keep going until `nextCursor` is `null`, which means you’ve reached the last page.
## Start from a date
[Section titled “Start from a date”](#start-from-a-date)
To start from a moment in the past, send `before` with an ISO time. You get the items older than it, newest first:
```bash
curl \
-H "Authorization: Bearer YOUR_API_KEY" \
"https://api.limitry.com/v1/checks?before=2026-11-20T00:00:00Z"
```
From there, page on with `nextCursor` as usual. When you send a cursor, `before` is ignored. Audit events, checks, a limit’s credits and webhook deliveries take `before`.
## Filter a list
[Section titled “Filter a list”](#filter-a-list)
Some lists take filters. Each filter is named after the field it narrows:
| List | Filter | Keeps |
| ------------------ | ------------- | -------------------------------------------------------------------------------------------------------------------- |
| Checks | `subject` | Checks that named one subject, as `kind:id` |
| Checks | `refused` | Only refused checks, with `true` |
| Limits | `subjectKind` | Limits for one subject kind |
| Limits | `action` | Limits for one action |
| Limits | `archived` | The archived limits instead, with `true` |
| Subjects | `kind` | Subjects of one kind |
| Subjects | `label` | Subjects with one label, as `key:value` |
| Subjects | `q` | Subjects whose name or ID contains the text |
| A limit’s credits | `subjectId` | One subject’s credits |
| Audit events | `action` | Events of one action, such as `workspace.member.invited` |
| Audit events | `actor` | What one person did (`user:` and the item’s `actor.id`), or one key or token (`credential:` and its `credential.id`) |
| Webhook deliveries | `status` | Deliveries that are `pending`, `delivered` or `failed` |
Filters combine with `before` and with paging. Send the same filters with every page.
## Good to know
[Section titled “Good to know”](#good-to-know)
* `limit` can be from 1 to 100. It’s 25 if you don’t set it.
* Don’t build or change a cursor yourself. Sending one we didn’t give you returns `invalid_request`.
* Items added while you’re paging won’t make you skip or repeat any.
* Items may gain new fields over time, but we won’t rename existing ones.
* A few lists are always short, such as webhook endpoints and event types. They come back as one page, and their `nextCursor` is `null`. They have the same shape as every other list, so the same code reads them.
* One list works differently. `GET /v1/usage/subjects` ranks a limit’s subjects, most used first, in a single response with no cursor. It answers them as `subjects`. Its `top` can be from 1 to 50, and it’s 50 if you don’t set it.
# Plan usage
> How much of your plan the workspace used this period, and its limits.
We count some things each month, starting from your billing date. On a paid plan, that’s the day your subscription started. On the free plan, it’s the day you created the workspace. Counts reset every month on that day, even on an annual plan. Each count comes with your plan’s limit for it. You can see them under **Settings → Billing**, or through the API:
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.limitry.com/v1/workspace/plan-usage
```
```json
{
"periodStart": "2026-10-17T14:30:00.000Z",
"periodEnd": "2026-11-17T14:30:00.000Z",
"state": "within",
"counts": [
{
"id": "webhook_deliveries",
"label": "Webhook deliveries",
"description": "Webhook deliveries this month (each event, each endpoint)",
"used": 1520,
"limit": null,
"stopsAt": null,
"state": "within"
},
{
"id": "checks",
"label": "Allowed live checks",
"unit": "per month",
"description": "Allowed live checks this month",
"used": 41230,
"limit": 100000,
"stopsAt": 110000,
"state": "within"
},
{
"id": "test_checks",
"label": "Test checks",
"unit": "per month",
"description": "Test checks this month, not billed",
"used": 880,
"limit": 10000,
"stopsAt": 10000,
"state": "within"
}
],
"notices": ["A check counts once, however many budgets it touches."]
}
```
| Count | What it counts |
| -------------------- | ---------------------------------------------------------------------------- |
| `checks` | Allowed checks made with live keys. Refused checks don’t count. |
| `test_checks` | Checks made with test keys, against their own allowance. They aren’t billed. |
| `webhook_deliveries` | Each event delivered to each endpoint. We count these but don’t limit them. |
`limit` is `null` when the plan has no limit for that count. A `limit` of `0` means your plan includes none of it. Counts start again at `periodEnd`, a month after `periodStart`, and a new subscription starts a new period. `notices` lists things to know about the numbers. The key needs the `workspace:read` scope. Every environment sees the same counts, because the plan covers the whole workspace. [Plan allowances](/docs/plans/) has each plan’s numbers.
## Where a count stands
[Section titled “Where a count stands”](#where-a-count-stands)
Each count has a `state`, and the response has one for the whole workspace. The workspace’s `state` is its most limited count’s.
| `state` | What it means |
| --------- | ------------------------------------------------------------------------------------------------ |
| `within` | The count is under its limit, or it has no limit. |
| `overage` | The count is past its limit, and we bill the extras. It keeps running until it passes `stopsAt`. |
| `grace` | The count is past its limit. It keeps running until it passes `stopsAt`. |
| `stopped` | We refuse new use until `periodEnd`. |
| `over` | The count is past its limit, but we never refuse it. |
`stopsAt` is where we start refusing new use. When a count stops at its limit, `stopsAt` equals `limit`. On a plan without extra checks, such as Free, live checks keep running for 10% past their limit, so their `stopsAt` is higher. On Pro and Business, `stopsAt` is where your spend cap stops the extra checks. If we never refuse a count, `stopsAt` is `null`.
# Plan allowances
> What each plan includes, what counts toward it, and why your product keeps working when you reach it.
Every plan has every feature: pools, credits, budgets, reservations, rolling and concurrent limits, webhooks, the SDK and the MCP server. Plans differ in how much you can use.
Prices are on the [Pricing page](/pricing/).
| | Free | Pro | Business | Enterprise |
| -------------------------------- | ------- | ------- | --------- | ---------- |
| Allowed checks a month | 100,000 | 500,000 | 5 million | Agreed |
| Test checks a month (not billed) | 10,000 | 50,000 | 500,000 | Agreed |
| Usage history | 7 days | 90 days | 13 months | Agreed |
| People | Up to 2 | Up to 5 | Up to 25 | Agreed |
## What counts
[Section titled “What counts”](#what-counts)
* **Allowed checks, with a live key.** A no is free, so someone hammering a limit they’ve already used up doesn’t use up your plan. A check that draws from a user and a team pool counts once. A reservation counts once, when you commit it. A reservation that you release, or that expires, is free.
* **Test checks.** Checks made with a test key have their own allowance of 10% of the plan’s allowed checks, and we don’t bill them. They never count toward your allowed checks. See [Test and live](/docs/test-and-live/).
You can see your usage in **Settings → Billing**, or with `GET /v1/workspace/plan-usage`. It’s about a minute behind live checks.
A check counts once however many subjects it draws from. A check on a user that also draws from their team’s pool and their account’s budget is one check.
## People and roles
[Section titled “People and roles”](#people-and-roles)
Each plan includes up to a number of people. Everyone in the workspace counts, guests included, and people never cost extra.
Each person has one role:
| Role | What they can do |
| ------ | ------------------------------------------------------------------------------------------------------------------------ |
| Owner | Everything, plus billing, transferring the workspace and deleting it |
| Admin | Everything else: limits and credits in live, members, live API keys and webhooks, the audit log, the region and settings |
| Member | Changes limits and credits in test, and manages test API keys and webhooks. Looks at live, but can’t change it |
| Guest | Looks at limits and usage, but can’t change anything |
To invite someone or change their role, go to **Settings → Members**.
## When you reach your plan’s limit
[Section titled “When you reach your plan’s limit”](#when-you-reach-your-plans-limit)
Your product keeps working. At 80% and 100% of a monthly allowance, your workspace’s owners get an email and a notification, and the app shows a notice. They’re told again when checks start returning `402 plan_limit_reached`.
What happens past your plan’s allowed checks depends on the plan:
| Plan | Past the allowed checks |
| -------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Pro | Checks keep working. Extras cost $40 per million checks, billed monthly. You set a monthly cap on extras. It starts at your plan’s price. |
| Business | Checks keep working. Extras cost $25 per million checks, billed monthly. You set a monthly cap on extras. It starts at your plan’s price. |
| Free | You get 10% grace. Beyond that, checks return `402 plan_limit_reached` until you upgrade or the next period starts. |
A paid plan past its cap stops the same way Free does after its grace. Its `402 plan_limit_reached` carries `reason: "spend_cap"`.
* A `402 plan_limit_reached` comes instead of a decision. The SDK treats it the same as Limitry being unreachable, so each limit’s fail mode applies. With `open`, the default, your product keeps working, but Limitry stops enforcing its limits for now. With `closed`, it says no.
* Test checks have no grace and no extras, on any plan. Once they use up their allowance, test checks return `402 plan_limit_reached`.
* Upgrading, or raising your cap, lifts the stop within a minute. Otherwise it ends on your billing date. That’s the day your subscription started, or the day you created the workspace on Free. Annual plans reset every month on that day.
If you call the API directly, handle a 402 the way you’d handle a timeout, by applying your fail mode. The SDK’s `guard` and `reserve` do this for you.
# Pools, balances and budgets
> Share an allowance across a team, sell prepaid credits, and cap what an agent can spend.
Pools, balances and budgets aren’t separate features. Each one is an ordinary limit, used in a particular way. Pools and balances use one example. Customers buy credits that their whole team spends, at 25 credits a report.
## Pools: an allowance a team shares
[Section titled “Pools: an allowance a team shares”](#pools-an-allowance-a-team-shares)
Put the limit on the shared subject, for example 5,000 credits a month for each `team`. Then name the team on each user’s check.
```json
{
"subject": { "kind": "user", "id": "user_123" },
"shared": [{ "kind": "team", "id": "team_42" }],
"action": "report",
"cost": 25
}
```
The check must fit every limit on the user and every limit on the team. It charges all of them, or none. However many of the team’s users check at the same moment, nobody can overspend the pool. This holds even when Limitry spreads a busy workspace’s counts across several of its servers. A check whose subjects sit on different servers is still all or nothing. It takes about 40 to 60 milliseconds longer, because it saves on each server in turn. You can name up to 4 shared subjects, such as a team, its organization and a project.
When a shared subject’s limit refuses the check, `reason.subject` in the answer names it, and `reason.message` says so. On the Usage page, the user’s row names it too. A check counts once on your plan, however many subjects it names.
## Balances: prepaid credits
[Section titled “Balances: prepaid credits”](#balances-prepaid-credits)
Set the window to `total`. The amount is the starting balance, and it never resets. When a team buys 5,000 credits, add them to its balance.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const credit = await limitry.limits.credits.create("lmt_3f0c…", {
subject: { kind: "team", id: "team_42" },
amount: 5000,
note: "October credits",
});
console.log(credit);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
credit = limitry.limits.credits.create(
"lmt_3f0c…",
subject={"kind": "team", "id": "team_42"},
amount=5000,
note="October credits",
)
print(credit)
```
* CLI
```bash
limitry limits credits create lmt_3f0c… --subject '{"kind":"team","id":"team_42"}' \
--amount 5000 --note "October credits"
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/limits/$LIMIT_ID/credits \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "subject": { "kind": "team", "id": "team_42" }, "amount": 5000, "note": "October credits" }'
```
In the app, open the balance’s ⋮ menu on the **Limits** page and choose **Credits**. Limitry keeps a record of every credit you add or take back. The dialog shows the latest five, and **See all credits** lists every one by day. `limitry limits credits list ` lists them too.
When a balance runs out, the check’s `retryAfterSeconds` is `null`, because waiting won’t help and only more credits will. The owner and admins can add credits, and members can in test. An AI agent connected through MCP asks instead, and someone who could add the credits approves the `limit.credit` request. A coding agent that uses your own token or the command line acts as you.
To take credits back after a refund or a chargeback, send a negative amount with a note that says why.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const credit = await limitry.limits.credits.create("lmt_3f0c…", {
subject: { kind: "team", id: "team_42" },
amount: -5000,
note: "Refund of order 1042",
});
console.log(credit);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
credit = limitry.limits.credits.create(
"lmt_3f0c…",
subject={"kind": "team", "id": "team_42"},
amount=-5000,
note="Refund of order 1042",
)
print(credit)
```
* CLI
```bash
limitry limits credits create lmt_3f0c… --subject '{"kind":"team","id":"team_42"}' \
--amount -5000 --note "Refund of order 1042"
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/limits/$LIMIT_ID/credits \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "subject": { "kind": "team", "id": "team_42" }, "amount": -5000, "note": "Refund of order 1042" }'
```
If the customer already spent those credits, the balance goes below zero. Checks then get a no until more credits bring it back above zero. In the app, choose **Take back** in the **Credits** dialog.
## Top-ups: more for this period
[Section titled “Top-ups: more for this period”](#top-ups-more-for-this-period)
A limit that resets can take credits too. Say each team gets 5,000 runs a month, and a team buys a pack of 5,000 more. Add the pack to the limit the same way, and it tops up the team’s current month.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const topUp = await limitry.limits.credits.create(
"lmt_9a2e…",
{
subject: { kind: "team", id: "team_42" },
amount: 5000,
note: "Pack of 5,000 runs",
},
{ idempotencyKey: "cs_live_a1B2c3" },
);
console.log(topUp.periodEnd);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
top_up = limitry.limits.credits.create(
"lmt_9a2e…",
subject={"kind": "team", "id": "team_42"},
amount=5000,
note="Pack of 5,000 runs",
idempotency_key="cs_live_a1B2c3",
)
print(top_up.period_end)
```
* CLI
```bash
limitry limits credits create lmt_9a2e… --subject '{"kind":"team","id":"team_42"}' \
--amount 5000 --note "Pack of 5,000 runs" --idempotency-key cs_live_a1B2c3
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/limits/$LIMIT_ID/credits \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: cs_live_a1B2c3" \
-d '{ "subject": { "kind": "team", "id": "team_42" }, "amount": 5000, "note": "Pack of 5,000 runs" }'
```
| Rule | What happens |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Which period | The subject’s current one, the period that holds when Limitry adds the credits. On a limit that starts on a billing date, it’s the subject’s own period. |
| What it adds | The credits add to that period alone. What the team already used still counts: 4,800 used of 5,000, plus a 5,000 top-up, leaves 5,200. |
| When it ends | At the period’s reset. Credits left over don’t carry into the next period. `periodEnd` in the answer says when that is. |
| Bought near the end | The credits still end at the reset. If you sell packs, tell your customer when they end. |
| Paying twice | Use the payment’s id as the idempotency key, such as a Stripe Checkout Session’s id. Limitry keeps the key, so a webhook delivered twice adds the credits once. |
| Which limits | A limit with a fixed period, such as `day`, `month` or `year`. A rolling or concurrent limit can’t take credits. On a limit that starts at first use, the period must have started. |
A subject’s standing (`limitry.standing()`) keeps `amount` as the limit’s own number and adds `credited`, this period’s top-ups. The period allows `amount` plus `credited`, and `remaining` already counts them. To show “4,800 of 10,000 runs used”, show `used` of `amount + credited`.
On the **Usage** page, what each team used stays the same after a top-up, and its credits show in what’s left. The **Credits** dialog on the limit’s ⋮ menu lists each top-up with the day it ends. To take a top-up back after a refund, send a negative amount with a note, as for a balance. It comes off the current period.
## Budgets: a spending cap for an agent
[Section titled “Budgets: a spending cap for an agent”](#budgets-a-spending-cap-for-an-agent)
A budget is a limit counted in money. For example, you might give every AI agent in your product $5 a day, across everything it spends on models and paid tools.
| Field | Value |
| ------- | ----------------------------- |
| Subject | `agent` (every agent, or one) |
| Action | `*` |
| Unit | `cents` |
| Amount | `500` |
| Window | `day`, or `total` for one-off |
Each check passes the step’s price in cents as `cost`, with an action such as `tool`. When you don’t know the price up front, [reserve](/docs/reservations/) what it will probably cost and commit what the call actually cost. Once the agent has used up its budget, every check gets a no until the window resets. For a balance, that lasts until you add credits. With a `total` budget, the agent can ask a person for more credits through the `limit.credit` approval.
The [Give AI agents a budget](/docs/guides/agent-budgets/) guide puts this together end to end.
# Python SDK
> Guard costly work with a with block, and call every API operation from Python, typed from the API itself.
The Python SDK is a small typed client for Python 3.10 and later. `guard` and `reserve` put a limit around your code in a `with` block. Every API operation is also a typed method, and its shape comes from the same definitions the API uses to validate requests. The SDK always matches the [API reference](/docs/reference/).
## Install
[Section titled “Install”](#install)
```bash
pip install limitry
```
## Your key
[Section titled “Your key”](#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**.
* `Limitry()` reads your key from the `LIMITRY_API_KEY` environment variable. If that isn’t set, it reads `LIMITRY_TOKEN`, the variable the CLI uses. If you set neither, it raises an error naming the variable.
* To pass the key yourself, use `Limitry(api_key=key)`.
* A test key (`lim_test_…`) acts in test, and a live key (`lim_live_…`) acts in live. [Test and live](/docs/test-and-live/) explains the difference.
* With a **personal access token**, pass it as `token` and name the workspace. The token acts in test unless you name live: `Limitry(token=token, workspace="acme", environment="live")`.
## Guard costly work
[Section titled “Guard costly work”](#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 the block, then charges what it actually cost. If the block raises, `reserve` releases the hold:
```python
from limitry import LimitReachedError, Limitry, UnavailableError
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
try:
with limitry.reserve(
subject={"kind": "user", "id": "user_123"}, action="ai-call", cost=5
) as reservation:
response = call_model(prompt)
reservation.cost = price_cents(response.usage) # your prices, in cents
print(response.text)
except LimitReachedError as error:
print(f"Try again in {error.retry_after_seconds} seconds")
except UnavailableError as error:
print(f"No decision ({error.reason}), and this limit fails closed")
```
A refusal raises `LimitReachedError`. Its `reason` is `limit_reached` or `too_many_reservations`. It also carries `limit_id`, `limit_name`, `retry_after_seconds` and the whole `decision`.
Both errors share the base class `LimitryError`, as every error the SDK raises does. A mistake in your request, such as an action name that isn’t valid, raises the API’s error instead, such as `BadRequestError`.
When every request costs the same, `guard` is simpler. It checks the limit, then runs the block only if Limitry allows it. Here it counts one request to your API against a limit of 60 a minute for each key:
```python
from limitry import Limitry
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
with limitry.guard(subject={"kind": "apikey", "id": "key_42"}, action="api-request"):
response = handle_request(request)
print(response)
```
## If your code can’t reach Limitry
[Section titled “If your code can’t reach Limitry”](#if-your-code-cant-reach-limitry)
If `guard` or `reserve` gets no decision, each limit’s fail mode decides. With `open`, the work runs. With `closed`, they raise `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` raises `UnavailableError`. [Concurrency](/docs/rolling-and-concurrency/#concurrency) explains why.
The commit or release after the block gets the same time as the check. If a commit doesn’t get through in that time, the SDK lets it go. The block’s work stands. 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.
* `guard` and `reserve` take `timeout=`, the most a check adds to your request, its tries included. It’s in seconds.
* They also take `fail_mode=` to fix the fail mode for every limit, `idempotency_key=` and `extra_headers=`.
* When a guard’s check times out and its limits fail open, the block runs. The guard then finishes the check after the block, within `timeout`, so it counts once.
* `reservation.cost = n` sets what the work used. It takes a whole number from 0 to 1,000,000,000. It raises `ValueError` for anything else, before the work’s usage could be lost.
* `reservation.extend()` raises the API’s error, for example when the reservation has already expired.
## Methods
[Section titled “Methods”](#methods)
Every API operation is a method, named after the operation in the [API reference](/docs/reference/). For example, `limits.create` is `limitry.limits.create()`:
```python
from limitry import Limitry
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
limit = limitry.limits.create(
name="AI budget",
subject={"kind": "user"},
action="ai-call",
amount=200,
unit="cents",
window="month",
)
limits = limitry.limits.list()
print(limit.id, len(limits.items))
```
* Ids in the path are arguments, and everything else is a keyword argument in Python’s style, so `failMode` becomes `fail_mode=`.
* Because the types come from the API itself, your editor completes every method, keyword argument and response field.
Here is every method. Each one links to its fields and a full example under **Endpoints**:
### Checks
* [`checks.create()`](/docs/reference/checks/#check-whether-a-subject-may-act)
Check whether a subject may act
* [`checks.list()`](/docs/reference/checks/#list-checks)
List checks
### Reservations
* [`reservations.commit()`](/docs/reference/reservations/#commit-a-reservation)
Commit a reservation
* [`reservations.extend()`](/docs/reference/reservations/#extend-a-reservation)
Extend a reservation
* [`reservations.get()`](/docs/reference/reservations/#get-a-reservation)
Get a reservation
* [`reservations.release()`](/docs/reference/reservations/#release-a-reservation)
Release a reservation
### Limits
* [`limits.archive()`](/docs/reference/limits/#archive-a-limit)
Archive a limit
* [`limits.create()`](/docs/reference/limits/#create-a-limit)
Create a limit
* [`limits.credits.create()`](/docs/reference/limits/#add-credits-to-a-balance)
Add credits to a balance
* [`limits.credits.get()`](/docs/reference/limits/#get-a-credit)
Get a credit
* [`limits.credits.list()`](/docs/reference/limits/#list-a-balances-credits)
List a balance's credits
* [`limits.get()`](/docs/reference/limits/#get-a-limit)
Get a limit
* [`limits.list()`](/docs/reference/limits/#list-limits)
List limits
* [`limits.restore()`](/docs/reference/limits/#restore-an-archived-limit)
Restore an archived limit
* [`limits.sync()`](/docs/reference/limits/#sync-limits-from-a-list)
Sync limits from a list
* [`limits.update()`](/docs/reference/limits/#change-a-limit)
Change a limit
### Subjects
* [`subjects.get()`](/docs/reference/subjects/#get-a-subject)
Get a subject
* [`subjects.import_()`](/docs/reference/subjects/#name-many-subjects)
Name many subjects
* [`subjects.list()`](/docs/reference/subjects/#list-subjects)
List subjects
* [`subjects.names.delete()`](/docs/reference/subjects/#erase-a-subjects-name-and-labels)
Erase a subject's name and labels
* [`subjects.reset()`](/docs/reference/subjects/#reset-a-subjects-limits)
Reset a subject's limits
* [`subjects.standing()`](/docs/reference/subjects/#get-where-a-subject-stands)
Get where a subject stands
* [`subjects.update()`](/docs/reference/subjects/#update-a-subject)
Update a subject
### Usage
* [`usage.overview()`](/docs/reference/usage/#get-every-limits-usage-at-once)
Get every limit's usage at once
* [`usage.query()`](/docs/reference/usage/#get-a-limits-usage-over-time)
Get a limit's usage over time
* [`usage.subjects()`](/docs/reference/usage/#list-who-is-using-a-limit)
List who is using a limit
### Workspace
* [`workspace.get()`](/docs/reference/workspace/#get-the-current-workspace)
Get the current workspace
* [`workspace.invitations.list()`](/docs/reference/workspace/#list-pending-invitations)
List pending invitations
* [`workspace.members.list()`](/docs/reference/workspace/#list-workspace-members)
List workspace members
* [`workspace.plan_usage.get()`](/docs/reference/workspace/#get-your-plans-usage-this-period)
Get your plan's usage this period
* [`workspace.teams.list()`](/docs/reference/workspace/#list-teams)
List teams
### Webhooks
* [`workspace.event_types.list()`](/docs/reference/webhooks/#list-event-types)
List event types
* [`workspace.webhook_deliveries.list()`](/docs/reference/webhooks/#list-an-endpoints-deliveries)
List an endpoint's deliveries
* [`workspace.webhook_deliveries.redeliver()`](/docs/reference/webhooks/#redeliver-an-event)
Redeliver an event
* [`workspace.webhook_endpoints.create()`](/docs/reference/webhooks/#add-a-webhook-endpoint)
Add a webhook endpoint
* [`workspace.webhook_endpoints.delete()`](/docs/reference/webhooks/#remove-a-webhook-endpoint)
Remove a webhook endpoint
* [`workspace.webhook_endpoints.enable()`](/docs/reference/webhooks/#re-enable-a-webhook-endpoint)
Re-enable a webhook endpoint
* [`workspace.webhook_endpoints.get()`](/docs/reference/webhooks/#get-a-webhook-endpoint)
Get a webhook endpoint
* [`workspace.webhook_endpoints.list()`](/docs/reference/webhooks/#list-webhook-endpoints)
List webhook endpoints
* [`workspace.webhook_endpoints.test()`](/docs/reference/webhooks/#send-a-test-event)
Send a test event
* [`workspace.webhook_endpoints.update()`](/docs/reference/webhooks/#update-a-webhook-endpoint)
Update a webhook endpoint
### Approvals
* [`workspace.approval_actions.list()`](/docs/reference/approvals/#list-the-actions-you-can-ask-approval-for)
List the actions you can ask approval for
* [`workspace.approval_requests.create()`](/docs/reference/approvals/#ask-a-person-to-approve-an-action)
Ask a person to approve an action
* [`workspace.approval_requests.get()`](/docs/reference/approvals/#check-an-approval-request)
Check an approval request
* [`workspace.approval_requests.redeem()`](/docs/reference/approvals/#redeem-an-approved-request)
Redeem an approved request
### Audit events
* [`workspace.audit_events.list()`](/docs/reference/audit-events/#list-workspace-audit-events)
List workspace audit events
### Personal access tokens
* [`user.me()`](/docs/reference/personal-access-tokens/#get-the-current-user)
Get the current user
* [`user.revoke_token()`](/docs/reference/personal-access-tokens/#revoke-the-token-making-this-request)
Revoke the token making this request
## Responses
[Section titled “Responses”](#responses)
A method returns a model of the response. Its fields are attributes in Python’s style, so the API’s `failMode` is `limit.fail_mode`.
```python
from limitry import Limitry
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
limit = limitry.limits.get("lmt_123")
print(limit.name, limit.fail_mode)
print(limit.to_dict()) # the API's own field names
print(limit.to_json())
```
* `to_dict()` and `to_json()` return the fields the API sent, with the API’s field names.
* The models are in `limitry.types`, such as `limitry.types.Limit`. Each one is a pydantic model.
* The SDK keeps a field the API adds later. You can read it by its API name until you update the SDK.
* The SDK also keeps a value it doesn’t know yet, such as a new status, as it came. It never raises an error.
* Timestamps are `datetime` objects.
## Lists
[Section titled “Lists”](#lists)
A list method returns its first page. When you iterate over the page, the SDK fetches the next pages as it goes, so the loop sees every item:
```python
for limit in limitry.limits.list():
print(limit.name)
```
To work one page at a time, use the page itself:
```python
page = limitry.limits.list(limit=10)
print(page.items, page.next_cursor)
if page.has_next_page():
page = page.get_next_page()
```
Read more about [pagination](/docs/pagination/).
## Errors
[Section titled “Errors”](#errors)
Every error the SDK raises is a `LimitryError`, including `LimitReachedError` and `UnavailableError`. When the API returns an [error](/docs/errors/), the SDK raises an `APIError` of the class for its HTTP status:
| Status | Error |
| ------------ | -------------------------- |
| 400 | `BadRequestError` |
| 401 | `AuthenticationError` |
| 402 | `PlanLimitError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 409 | `ConflictError` |
| 422 | `UnprocessableEntityError` |
| 429 | `RateLimitError` |
| 500 or above | `InternalServerError` |
| Any other | `APIError` |
An `APIError` carries these attributes:
| Attribute | What it holds |
| ------------- | ----------------------------------------------------------------- |
| `status_code` | The HTTP status. |
| `code` | The error’s code, such as `not_found`. |
| `message` | What went wrong. |
| `request_id` | The request’s id. Quote it when you contact us. |
| `details` | What was wrong with each field, as `{"path", "message"}` entries. |
| `docs` | A link to the code’s entry on the Errors page. |
| `headers` | The response’s headers, such as `Retry-After`. |
When the SDK can’t reach the API, it raises an `APIConnectionError`. An attempt that runs out of time raises an `APITimeoutError`, a kind of `APIConnectionError`. Either one keeps the network error as its `__cause__`.
```python
from limitry import APIConnectionError, Limitry, NotFoundError
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
try:
limit = limitry.limits.get("lmt_123")
print(limit.name)
except NotFoundError:
print("No such limit")
except APIConnectionError:
print("The API couldn't be reached. Try again later.")
```
## Retries and timeouts
[Section titled “Retries and timeouts”](#retries-and-timeouts)
These apply to every method. `guard` and `reserve` keep their own, shorter `timeout=`, as [If your code can’t reach Limitry](#if-your-code-cant-reach-limitry) shows.
The SDK retries a failed attempt twice: after a network error, a timeout, or a `408`, `429`, `500`, `502`, `503` or `504`. It doesn’t retry a `501`.
* It waits as long as `Retry-After` asks, up to 60 seconds. When the API asks for longer, the SDK raises the error instead.
* Every write sends an [idempotency key](/docs/idempotency/), the same on each retry, so the write happens only once.
* To make your own retries safe too, pass your key: `idempotency_key=key`.
* To change how often it retries, pass `max_retries=` to the client or to `with_options()`.
Each attempt waits up to 60 seconds for a response. The SDK retries a timed-out attempt with the same key. To change the limit, pass `timeout=` in seconds to the client, to one call, or to `with_options()` for the calls made through it:
```python
limitry.limits.list(timeout=5)
limitry.with_options(timeout=5, max_retries=0).limits.list()
```
To limit a whole `AsyncLimitry` call, retries included, wrap it in `asyncio.timeout()`. Past it, the call stops at once, even while it waits to retry, and raises a `TimeoutError`.
## Client options
[Section titled “Client options”](#client-options)
| Option | What it does |
| ----------------- | ------------------------------------------------------------------------------------ |
| `api_key` | Your API key. Without it, `LIMITRY_API_KEY`. |
| `token` | A personal access token, used with `workspace`. Without it, `LIMITRY_TOKEN`. |
| `workspace` | The workspace a personal access token acts in. |
| `environment` | `test` or `live`, for a personal access token. Without it, test. |
| `base_url` | The API’s address, without `/v1`. Without it, `LIMITRY_BASE_URL`, then the live API. |
| `timeout` | The seconds each attempt may take. 60 by default. |
| `max_retries` | How many times to retry a failed attempt. 2 by default. |
| `default_headers` | Headers to send with every call. |
| `http_client` | Your own `httpx.Client`, or `httpx.AsyncClient` for `AsyncLimitry`. |
Every method also takes these keyword arguments:
| Argument | What it does |
| ----------------- | ----------------------------------------------- |
| `idempotency_key` | Your key for this write. Writes only. |
| `extra_headers` | Headers to send with this call only. |
| `timeout` | The seconds each attempt of this call may take. |
`with_options()` takes `timeout`, `max_retries` and `default_headers`. It returns the same client with those defaults. Its `default_headers` go with the client’s own, not in place of them.
## Async
[Section titled “Async”](#async)
`AsyncLimitry` has the same methods, and you `await` each call. `guard` and `reserve` become `async with`:
```python
import asyncio
from limitry import AsyncLimitry
async def main() -> None:
async with AsyncLimitry() as limitry:
async with limitry.reserve(
subject={"kind": "user", "id": "user_123"}, action="ai-call", cost=5
) as reservation:
response = await call_model(prompt)
reservation.cost = price_cents(response.usage)
print(response.text)
asyncio.run(main())
```
Cancelling the task stops the check at once, for example with `asyncio.timeout()` around the `async with`. The block never runs, and no fail mode applies.
A list is the exception to `await`. You `await` it for its first page, or use `async for` to go through every item:
```python
from limitry import AsyncLimitry
async def print_limits(limitry: AsyncLimitry) -> None:
async for limit in limitry.limits.list():
print(limit.name)
```
`async with` closes the client when the block ends. Without it, call `await limitry.close()` when you’re done.
# Quickstart
> Create a limit and make your first check, in about five minutes.
By the end of this page, each of your users will have a $2 AI budget a month. Your code will check it before each AI reply, then charge what the reply actually cost.
## 1. Create a workspace
[Section titled “1. Create a workspace”](#1-create-a-workspace)
[Sign up](https://app.limitry.com/sign-up), verify your email and create a workspace. Limits, keys and usage all belong to a workspace.
## 2. Get a test key
[Section titled “2. Get a test key”](#2-get-a-test-key)
Every workspace has a test side and a live side, and you start in test. Test keys have their own limits and counts, and we don’t bill their checks. [Test and live](/docs/test-and-live/) explains the difference.
Create a key with **Manage limits** under **Settings → Developers**. Choose **Test** for its side. **Manage limits** can create limits and make checks, so every step in this guide works with it.
The key starts with `lim_test_`. Copy the secret now, because we show it only once. Keep it in your secret manager or environment rather than in your code.
```bash
export LIMITRY_API_KEY="lim_test_…" # the SDKs read this
export LIMITRY_TOKEN="$LIMITRY_API_KEY" # the CLI reads this
```
Workspace owners and admins can create keys, and members can create test keys. If you add your first limit in the app instead, the dashboard offers **Create a test key** as your next step, with the access this guide needs already set.
Then install the client you’ll use. curl needs nothing:
* TypeScript
```bash
npm install @limitry/sdk
```
* Python
```bash
pip install limitry
```
* CLI
```bash
npm install -g @limitry/cli
```
## 3. Create a limit
[Section titled “3. Create a limit”](#3-create-a-limit)
Count in cents, so $2 is 200. In the app, open **Limits** while you’re in test, and add a limit of 200 cents a month for subjects of kind `user` and the action `ai-call`. You can also create it from your code or a terminal:
* TypeScript
```ts
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",
});
console.log(limit.id);
```
* Python
```python
from limitry import Limitry
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
limit = limitry.limits.create(
name="AI budget",
subject={"kind": "user"},
action="ai-call",
amount=200,
unit="cents",
window="month",
)
print(limit.id)
```
* CLI
```bash
limitry limits create --name "AI budget" --subject '{"kind":"user"}' \
--action ai-call --amount 200 --unit cents --window month
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/limits \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"AI budget","subject":{"kind":"user"},"action":"ai-call",
"amount":200,"unit":"cents","window":"month"}'
```
The limit applies in test to every subject of kind `user`, starting with the next check. To try it with the CLI, run this. It spends 5 of the user’s cents:
```bash
limitry check user:user_123 ai-call --cost 5
# Allowed. AI budget: 195 cents left, resets 2026-11-01T00:00:00.000Z
```
## 4. Check before the work
[Section titled “4. Check before the work”](#4-check-before-the-work)
Ask whether user `user_123` may make an AI request that costs 5 cents:
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable
const decision = await limitry.checks.create({
subject: { kind: "user", id: "user_123" },
action: "ai-call",
cost: 5,
});
console.log(decision);
```
* Python
```python
from limitry import Limitry
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
decision = limitry.checks.create(
subject={"kind": "user", "id": "user_123"},
action="ai-call",
cost=5,
)
print(decision)
```
* CLI
```bash
limitry check user:user_123 ai-call --cost 5
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/checks \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"subject":{"kind":"user","id":"user_123"},"action":"ai-call","cost":5}'
```
The response, after the CLI’s check in step 3:
```json
{
"allowed": true,
"reason": null,
"reservation": null,
"limits": [
{
"limitId": "lmt_…",
"limitName": "AI budget",
"unit": "cents",
"window": "month",
"rolling": false,
"failMode": "open",
"amount": 200,
"remaining": 190,
"resetsAt": "2026-11-01T00:00:00.000Z"
}
],
"retryAfterSeconds": null
}
```
When a check costs more than the user has left, it returns `"allowed": false` and spends nothing. Its `retryAfterSeconds` tells you when the budget resets. A “no” is a normal result, not an error.
## 5. Use it from your code
[Section titled “5. Use it from your code”](#5-use-it-from-your-code)
You don’t know what a reply costs until it’s done. So in your code, the SDK’s `reserve` holds what the reply will probably cost, runs your request, then charges what it actually cost. Whatever the reply didn’t use goes straight back to the user. The [TypeScript](/docs/typescript/) and [Python](/docs/python/) SDK pages have the details.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable
// Your prices, in cents per million tokens.
const priceCents = (usage: { inputTokens: number; outputTokens: number }) =>
Math.ceil((usage.inputTokens * 300 + usage.outputTokens * 1500) / 1_000_000);
const reply = await limitry.reserve(
{ subject: { kind: "user", id: user.id }, action: "ai-call", cost: 5 },
async (reservation) => {
const res = await callModel(prompt);
reservation.cost(priceCents(res.usage));
return res.text;
},
);
console.log(reply);
```
* Python
```python
import math
from limitry import Limitry
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
# Your prices, in cents per million tokens.
def price_cents(usage) -> int:
return math.ceil((usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000)
with limitry.reserve(
subject={"kind": "user", "id": user.id}, action="ai-call", cost=5
) as reservation:
res = call_model(prompt)
reservation.cost = price_cents(res.usage)
print(res.text)
```
When the user’s budget can’t cover the hold, `reserve` throws `LimitReachedError`, or raises it in Python. The reply is never generated, so you don’t pay for it. If your request fails, `reserve` gives the hold back, so a failed reply costs the user nothing.
[Limit AI spend per user](/docs/guides/limit-ai-spend/) goes further: what to tell a user Limitry refuses, what to do when your code can’t reach Limitry, and a budget for each model. When every request costs the same, `guard` checks and runs your code in one step, without a hold.
## 6. Go live
[Section titled “6. Go live”](#6-go-live)
When your limits work in test, move them to production:
1. On the **Limits** page, still in test, click **Copy to live**. Check what it will create, then confirm.
2. Create a key with **Check limits** under **Settings → Developers**, and choose **Live** for its side. Your production code only checks, and that’s what **Check limits** allows. The key starts with `lim_live_`.
3. Give your production code the live key. Nothing else changes. The same code now uses your live limits, and its checks count toward your plan.
Next, [Checks](/docs/checks/) covers everything a check can do. The [introduction](/docs/#what-are-you-building) lists guides for what you might be building. Two good next steps are [Show users where they stand](/docs/guides/show-usage/) and [Warn your users before they hit a limit](/docs/guides/warn-users/).
# API reference
> Every endpoint of the Limitry API, by area, each in TypeScript, Python, the CLI and curl.
Every endpoint of the Limitry API, by area. Each one shows the same call in TypeScript, Python, the CLI and curl, with its fields.
* To try a call in your browser, use the [API playground (opens in a new tab)](https://api.limitry.com/v1/docs). Each endpoint below links to its own place there.
* For tools that read OpenAPI, the document is at .
* Before your first call, see [Authentication](/docs/authentication/) and [Errors and rate limits](/docs/errors/).
## Checks
[Section titled “Checks”](#checks)
* [Check whether a subject may act](/docs/reference/checks/#check-whether-a-subject-may-act): `checks.create()`
* [List checks](/docs/reference/checks/#list-checks): `checks.list()`
## Reservations
[Section titled “Reservations”](#reservations)
* [Commit a reservation](/docs/reference/reservations/#commit-a-reservation): `reservations.commit()`
* [Extend a reservation](/docs/reference/reservations/#extend-a-reservation): `reservations.extend()`
* [Get a reservation](/docs/reference/reservations/#get-a-reservation): `reservations.get()`
* [Release a reservation](/docs/reference/reservations/#release-a-reservation): `reservations.release()`
## Limits
[Section titled “Limits”](#limits)
* [Archive a limit](/docs/reference/limits/#archive-a-limit): `limits.archive()`
* [Create a limit](/docs/reference/limits/#create-a-limit): `limits.create()`
* [Add credits to a balance](/docs/reference/limits/#add-credits-to-a-balance): `limits.credits.create()`
* [Get a credit](/docs/reference/limits/#get-a-credit): `limits.credits.get()`
* [List a balance’s credits](/docs/reference/limits/#list-a-balances-credits): `limits.credits.list()`
* [Get a limit](/docs/reference/limits/#get-a-limit): `limits.get()`
* [List limits](/docs/reference/limits/#list-limits): `limits.list()`
* [Restore an archived limit](/docs/reference/limits/#restore-an-archived-limit): `limits.restore()`
* [Sync limits from a list](/docs/reference/limits/#sync-limits-from-a-list): `limits.sync()`
* [Change a limit](/docs/reference/limits/#change-a-limit): `limits.update()`
## Subjects
[Section titled “Subjects”](#subjects)
* [Get a subject](/docs/reference/subjects/#get-a-subject): `subjects.get()`
* [Name many subjects](/docs/reference/subjects/#name-many-subjects): `subjects.import()`
* [List subjects](/docs/reference/subjects/#list-subjects): `subjects.list()`
* [Erase a subject’s name and labels](/docs/reference/subjects/#erase-a-subjects-name-and-labels): `subjects.names.delete()`
* [Reset a subject’s limits](/docs/reference/subjects/#reset-a-subjects-limits): `subjects.reset()`
* [Get where a subject stands](/docs/reference/subjects/#get-where-a-subject-stands): `subjects.standing()`
* [Update a subject](/docs/reference/subjects/#update-a-subject): `subjects.update()`
## Usage
[Section titled “Usage”](#usage)
* [Get every limit’s usage at once](/docs/reference/usage/#get-every-limits-usage-at-once): `usage.overview()`
* [Get a limit’s usage over time](/docs/reference/usage/#get-a-limits-usage-over-time): `usage.query()`
* [List who is using a limit](/docs/reference/usage/#list-who-is-using-a-limit): `usage.subjects()`
## Workspace
[Section titled “Workspace”](#workspace)
* [Get the current workspace](/docs/reference/workspace/#get-the-current-workspace): `workspace.get()`
* [List pending invitations](/docs/reference/workspace/#list-pending-invitations): `workspace.invitations.list()`
* [List workspace members](/docs/reference/workspace/#list-workspace-members): `workspace.members.list()`
* [Get your plan’s usage this period](/docs/reference/workspace/#get-your-plans-usage-this-period): `workspace.planUsage.get()`
* [List teams](/docs/reference/workspace/#list-teams): `workspace.teams.list()`
## Webhooks
[Section titled “Webhooks”](#webhooks)
* [List event types](/docs/reference/webhooks/#list-event-types): `workspace.eventTypes.list()`
* [List an endpoint’s deliveries](/docs/reference/webhooks/#list-an-endpoints-deliveries): `workspace.webhookDeliveries.list()`
* [Redeliver an event](/docs/reference/webhooks/#redeliver-an-event): `workspace.webhookDeliveries.redeliver()`
* [Add a webhook endpoint](/docs/reference/webhooks/#add-a-webhook-endpoint): `workspace.webhookEndpoints.create()`
* [Remove a webhook endpoint](/docs/reference/webhooks/#remove-a-webhook-endpoint): `workspace.webhookEndpoints.delete()`
* [Re-enable a webhook endpoint](/docs/reference/webhooks/#re-enable-a-webhook-endpoint): `workspace.webhookEndpoints.enable()`
* [Get a webhook endpoint](/docs/reference/webhooks/#get-a-webhook-endpoint): `workspace.webhookEndpoints.get()`
* [List webhook endpoints](/docs/reference/webhooks/#list-webhook-endpoints): `workspace.webhookEndpoints.list()`
* [Send a test event](/docs/reference/webhooks/#send-a-test-event): `workspace.webhookEndpoints.test()`
* [Update a webhook endpoint](/docs/reference/webhooks/#update-a-webhook-endpoint): `workspace.webhookEndpoints.update()`
## Approvals
[Section titled “Approvals”](#approvals)
* [List the actions you can ask approval for](/docs/reference/approvals/#list-the-actions-you-can-ask-approval-for): `workspace.approvalActions.list()`
* [Ask a person to approve an action](/docs/reference/approvals/#ask-a-person-to-approve-an-action): `workspace.approvalRequests.create()`
* [Check an approval request](/docs/reference/approvals/#check-an-approval-request): `workspace.approvalRequests.get()`
* [Redeem an approved request](/docs/reference/approvals/#redeem-an-approved-request): `workspace.approvalRequests.redeem()`
## Audit events
[Section titled “Audit events”](#audit-events)
* [List workspace audit events](/docs/reference/audit-events/#list-workspace-audit-events): `workspace.auditEvents.list()`
## Personal access tokens
[Section titled “Personal access tokens”](#personal-access-tokens)
* [Get the current user](/docs/reference/personal-access-tokens/#get-the-current-user): `user.me()`
* [Revoke the token making this request](/docs/reference/personal-access-tokens/#revoke-the-token-making-this-request): `user.revokeToken()`
# Approvals API
> The approvals endpoints, each in TypeScript, Python, the CLI and curl.
The approvals endpoints, each in TypeScript, Python, the CLI and curl.
## Set up
[Section titled “Set up”](#set-up)
* TypeScript
```bash
npm install @limitry/sdk
export LIMITRY_API_KEY="lim_test_…"
```
* Python
```bash
pip install limitry
export LIMITRY_API_KEY="lim_test_…"
```
* CLI
```bash
npm install -g @limitry/cli
limitry login
```
* curl
```bash
export LIMITRY_API_KEY="lim_test_…"
```
To pass the key yourself, use `createClient({ apiKey: key })` in TypeScript or `Limitry(api_key=key)` in Python.
## List the actions you can ask approval for
[Section titled “List the actions you can ask approval for”](#list-the-actions-you-can-ask-approval-for)
`GET /v1/workspace/approval-actions`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/approvals/GET/workspace/approval-actions)
Scope: `workspace.approvals:read`.
Lists the actions a credential can’t take itself but can ask a person to approve.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const approvalActions = await limitry.workspace.approvalActions.list();
console.log(approvalActions);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
approval_actions = limitry.workspace.approval_actions.list()
print(approval_actions)
```
* CLI
```bash
limitry workspace approval-actions list
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/approval-actions" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"id": "workspace.apiKey.create",
"title": "Create a workspace API key",
"approverRoles": [
"owner"
],
"createsSecret": true,
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
},
"required": [
"name"
]
}
}
],
"nextCursor": null
}
```
More about this endpoint
Each action comes with its input as a JSON Schema (`inputSchema`), who can approve it and whether it creates a secret. Every action fits on one page, so `nextCursor` is null.
## Ask a person to approve an action
[Section titled “Ask a person to approve an action”](#ask-a-person-to-approve-an-action)
`POST /v1/workspace/approval-requests`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/approvals/POST/workspace/approval-requests)
Scope: `workspace.approvals:write`.
Creates a request for an action you can’t take yourself and notifies everyone who can approve it.
This takes a [personal access token](/docs/authentication/), not an API key. In the SDKs, pass it as `token`, with `workspace`.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
const limitry = createClient({ token: process.env.LIMITRY_TOKEN, workspace: "" });
const approvalRequest = await limitry.workspace.approvalRequests.create({
action: "workspace.apiKey.create",
input: {
name: "acme-web",
scopes: [
"workspace:read",
],
},
reason: "A key for the deploy pipeline.",
});
console.log(approvalRequest);
```
* Python
```python
import os
from limitry import Limitry
limitry = Limitry(token=os.environ["LIMITRY_TOKEN"], workspace="")
approval_request = limitry.workspace.approval_requests.create(
action="workspace.apiKey.create",
input={
"name": "acme-web",
"scopes": ["workspace:read"],
},
reason="A key for the deploy pipeline.",
)
print(approval_request)
```
* CLI
```bash
limitry workspace approval-requests create \
--action workspace.apiKey.create \
--input '{"name":"acme-web","scopes":["workspace:read"]}' \
--reason 'A key for the deploy pipeline.'
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/workspace/approval-requests" \
-H "Authorization: Bearer $LIMITRY_TOKEN" \
-H "X-Workspace: " \
-H "Content-Type: application/json" \
-d '{"action":"workspace.apiKey.create","input":{"name":"acme-web","scopes":["workspace:read"]},"reason":"A key for the deploy pipeline."}'
```
**Returns:**
```json
{
"id": "apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d",
"action": "workspace.apiKey.create",
"title": "Create a workspace API key",
"summary": "Create the API key “acme-web” with workspace:read",
"input": {
"name": "acme-web",
"scopes": [
"workspace:read"
]
},
"reason": "I'm connecting acme-web and need an API key that can read the workspace.",
"status": "pending",
"requestedBy": "Claude",
"expiresAt": "2026-08-20T12:00:00.000Z",
"createdAt": "2026-08-19T12:00:00.000Z",
"decidedAt": null,
"result": null,
"secret": {
"name": "API key",
"envVar": "LIMITRY_API_KEY"
},
"approveUrl": "https://app.limitry.com/approvals/apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d"
}
```
| Field | Description |
| ------------------------- | ------------------------------------------------------------- |
| `action` string, required | An action id from approval-actions. |
| `input` object, required | The action's input. It must match the action's JSON Schema. |
| `reason` string, required | Why you need the action. The person reads it before deciding. |
More about this endpoint
The actions you can ask for are in approval-actions. Show the person `approveUrl` and why you need the action. Then check the request until a person decides. A request expires after 24 hours. A personal access token or an app a person connected can ask. A workspace API key can’t.
## Check an approval request
[Section titled “Check an approval request”](#check-an-approval-request)
`GET /v1/workspace/approval-requests/{approvalRequestId}`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/approvals/GET/workspace/approval-requests/{approvalRequestId})
Scope: `workspace.approvals:read`.
Returns an approval request you created, with its status.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const approvalRequest = await limitry.workspace.approvalRequests.get("apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d");
console.log(approvalRequest);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
approval_request = limitry.workspace.approval_requests.get(
"apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d",
)
print(approval_request)
```
* CLI
```bash
limitry workspace approval-requests get \
apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/approval-requests/apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"id": "apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d",
"action": "workspace.apiKey.create",
"title": "Create a workspace API key",
"summary": "Create the API key “acme-web” with workspace:read",
"input": {
"name": "acme-web",
"scopes": [
"workspace:read"
]
},
"reason": "I'm connecting acme-web and need an API key that can read the workspace.",
"status": "pending",
"requestedBy": "Claude",
"expiresAt": "2026-08-20T12:00:00.000Z",
"createdAt": "2026-08-19T12:00:00.000Z",
"decidedAt": null,
"result": null,
"secret": {
"name": "API key",
"envVar": "LIMITRY_API_KEY"
},
"approveUrl": "https://app.limitry.com/approvals/apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d"
}
```
| Field | Description |
| ------------------------------------------ | -------------------------- |
| `approvalRequestId` string, path, required | The approval request's id. |
More about this endpoint
A `pending` request is waiting for a person to decide. A `completed` request’s action ran, and `result` holds the outcome. An `approved` request is waiting for the CLI to redeem it. A request can also be `denied`, `failed` or `expired`.
## Redeem an approved request
[Section titled “Redeem an approved request”](#redeem-an-approved-request)
`POST /v1/workspace/approval-requests/{approvalRequestId}/redeem`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/approvals/POST/workspace/approval-requests/{approvalRequestId}/redeem)
Scope: `workspace.approvals:write`.
Runs an approved action that creates a secret, and returns the secret.
This takes a [personal access token](/docs/authentication/), not an API key. In the SDKs, pass it as `token`, with `workspace`.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
const limitry = createClient({ token: process.env.LIMITRY_TOKEN, workspace: "" });
const secret = await limitry.workspace.approvalRequests.redeem("apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d");
console.log(secret);
```
* Python
```python
import os
from limitry import Limitry
limitry = Limitry(token=os.environ["LIMITRY_TOKEN"], workspace="")
secret = limitry.workspace.approval_requests.redeem(
"apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d",
)
print(secret)
```
* CLI
```bash
limitry workspace approval-requests redeem \
apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/workspace/approval-requests/apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d/redeem" \
-H "Authorization: Bearer $LIMITRY_TOKEN" \
-H "X-Workspace: "
```
**Returns:**
```json
{
"request": {
"id": "apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d",
"action": "workspace.apiKey.create",
"title": "Create a workspace API key",
"summary": "Create the API key “acme-web” with workspace:read",
"input": {
"name": "acme-web",
"scopes": [
"workspace:read"
]
},
"reason": "I'm connecting acme-web and need an API key that can read the workspace.",
"status": "pending",
"requestedBy": "Claude",
"expiresAt": "2026-08-20T12:00:00.000Z",
"createdAt": "2026-08-19T12:00:00.000Z",
"decidedAt": null,
"result": null,
"secret": {
"name": "API key",
"envVar": "LIMITRY_API_KEY"
},
"approveUrl": "https://app.limitry.com/approvals/apr_7c2e9b4d-1f3a-4e5b-8c6d-7e8f9a0b1c2d"
},
"secret": "sk_limitry_Xk2mP9qR4tV7wY1zB3cD5fG8hJ0kL6nQXk2mP9qR4tV7wY1zB3cD5fG8hJ0kL6nQ",
"envVar": "LIMITRY_API_KEY"
}
```
| Field | Description |
| ------------------------------------------ | -------------------------- |
| `approvalRequestId` string, path, required | The approval request's id. |
More about this endpoint
The action runs only once. Only the personal access token that asked can redeem it. The CLI writes the secret to a file without printing it.
# Audit events API
> The audit events endpoints, each in TypeScript, Python, the CLI and curl.
The audit events endpoints, each in TypeScript, Python, the CLI and curl.
## Set up
[Section titled “Set up”](#set-up)
* TypeScript
```bash
npm install @limitry/sdk
export LIMITRY_API_KEY="lim_test_…"
```
* Python
```bash
pip install limitry
export LIMITRY_API_KEY="lim_test_…"
```
* CLI
```bash
npm install -g @limitry/cli
limitry login
```
* curl
```bash
export LIMITRY_API_KEY="lim_test_…"
```
To pass the key yourself, use `createClient({ apiKey: key })` in TypeScript or `Limitry(api_key=key)` in Python.
## List workspace audit events
[Section titled “List workspace audit events”](#list-workspace-audit-events)
`GET /v1/workspace/audit-events`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/audit-events/GET/workspace/audit-events)
Scope: `workspace.audit:read`.
Lists the workspace’s audit events, newest first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const auditEvents = await limitry.workspace.auditEvents.list();
console.log(auditEvents);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
audit_events = limitry.workspace.audit_events.list()
print(audit_events)
```
* CLI
```bash
limitry workspace audit-events list
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/audit-events" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"id": "aud_6b2f9e1c-3d4a-4f8b-9e7c-1a2b3c4d5e6f",
"action": "workspace.member.invited",
"actorType": "user",
"actor": {
"id": "usr_4f8a2c1e-7b3d-4e9f-a6c5-2d1b0e9f8a7c"
},
"credential": {
"id": "pat_8a1b2c3d-4e5f-4061-8a7b-9c0d1e2f3a4b",
"type": "pat",
"name": "ci"
},
"createdAt": "2026-08-19T12:00:00.000Z"
}
],
"nextCursor": null
}
```
| Field | Description |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `limit` number, query | Items per page, 1–100 (default 25). |
| `cursor` string, query | Opaque token from a previous page's nextCursor. |
| `before` string, query | Start from this moment: items older than it, newest first. Ignored with `cursor`, which already says where to go on. |
| `action` string, query | Only events of this action. |
| `actor` string, query | Only what one person did (`user:` and the item's `actor.id`), or one key or token (`credential:` and the item's `credential.id`). |
More about this endpoint
Paginate with the opaque `nextCursor` token. `limit` takes 1 to 100 and defaults to 25. `before` starts from a moment. `action` keeps one kind of event, and `actor` what one person, key or token did. With a personal access token, only workspace owners and admins can call this, as with the audit page in the app. A workspace API key always can, because it acts as the workspace itself.
# Checks API
> The checks endpoints, each in TypeScript, Python, the CLI and curl.
The checks endpoints, each in TypeScript, Python, the CLI and curl.
## Set up
[Section titled “Set up”](#set-up)
* TypeScript
```bash
npm install @limitry/sdk
export LIMITRY_API_KEY="lim_test_…"
```
* Python
```bash
pip install limitry
export LIMITRY_API_KEY="lim_test_…"
```
* CLI
```bash
npm install -g @limitry/cli
limitry login
```
* curl
```bash
export LIMITRY_API_KEY="lim_test_…"
```
To pass the key yourself, use `createClient({ apiKey: key })` in TypeScript or `Limitry(api_key=key)` in Python.
## Check whether a subject may act
[Section titled “Check whether a subject may act”](#check-whether-a-subject-may-act)
`POST /v1/checks`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/checks/POST/checks)
Scope: `checks:write`.
Asks whether `subject` may do `action` at `cost`, given every enabled limit that applies.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const check = await limitry.checks.create({
subject: {
kind: "user",
id: "user_123",
},
action: "ai-call",
cost: 5,
});
console.log(check);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
check = limitry.checks.create(
subject={"kind": "user", "id": "user_123"},
action="ai-call",
cost=5,
)
print(check)
```
* CLI
Day to day: `limitry check : `. This endpoint’s own command:
```bash
limitry checks create \
--subject '{"kind":"user","id":"user_123"}' \
--action ai-call \
--cost 5
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/checks" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"subject":{"kind":"user","id":"user_123"},"action":"ai-call","cost":5}'
```
**Returns:**
```json
{
"allowed": true,
"reason": null,
"limits": [
{
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"limitName": "AI budget",
"unit": "cents",
"window": "month",
"rolling": false,
"failMode": "open",
"amount": 200,
"remaining": 195,
"resetsAt": "2026-12-01T00:00:00.000Z"
}
],
"retryAfterSeconds": null,
"reservation": {
"id": "rsv_WyJ1c2VyIiwidXNlcl8xMjMiXQ_9f2c4e1a7b3d4c8e9a0f1b2c3d4e5f6a",
"expiresAt": "2026-11-06T12:05:00.000Z"
}
}
```
| Field | Description |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `subject` object, required | Who is acting, such as `{"kind": "user", "id": "user_123"}`. |
| `shared` array | Shared subjects the check also draws from, such as a team's, an organization's or a project's pool. Send at most 4. Every limit on every subject must fit, and Limitry charges either all of them or none. |
| `action` string, required | What the subject wants to do. |
| `cost` number | The units the action would use. Default: 1. |
| `mode` string | How the check counts. `consume` decides and counts, and is the default. `preview` decides without counting anything. `reserve` decides and holds `cost`, your estimate, until you commit the actual amount or release it. The response's `reservation` names what it holds. Only a reservation takes a slot of a `concurrent` limit. |
| `ttlSeconds` number | With `reserve`, how many seconds the reservation lasts before it releases itself. Default: 300. At most 3600. |
More about this endpoint
In `consume` mode, it also counts the use. Every decision returns 200, whether it’s allowed or refused, so read `allowed`. `limits` shows what’s left on each limit, and `retryAfterSeconds` says when to try again. With an `Idempotency-Key` header, a retried check gets the same decision for an hour and counts only once. We cache its API key check briefly for speed. A revoked key can keep working here for up to 60 seconds.
## List checks
[Section titled “List checks”](#list-checks)
`GET /v1/checks`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/checks/GET/checks)
Scope: `limits:read`.
Lists the checks of the last 3 days, newest first, with every subject each one named and whether Limitry allowed it.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const checks = await limitry.checks.list();
console.log(checks);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
checks = limitry.checks.list()
print(checks)
```
* CLI
```bash
limitry checks list
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/checks" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"checkedAt": "2026-11-21T14:32:08.000Z",
"action": "ai-call",
"cost": 5,
"unit": "cents",
"mode": "consume",
"subjects": [
{
"kind": "user",
"id": "user_123",
"name": "Sara Khan"
}
],
"allowed": false,
"refusedBy": {
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"limitName": "Team AI budget",
"subject": {
"kind": "user",
"id": "user_123",
"name": "Sara Khan"
}
}
}
],
"nextCursor": null
}
```
| Field | Description |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `limit` number, query | Items per page, 1–100 (default 25). |
| `cursor` string, query | Opaque token from a previous page's nextCursor. |
| `before` string, query | Start from this moment: items older than it, newest first. Ignored with `cursor`, which already says where to go on. |
| `subject` string, query | Only checks that named this subject, as `kind:id`. |
| `refused` string, query | `true` for only refused checks. |
More about this endpoint
A refused check says whose budget refused it. Name a `subject` as `kind:id` for only the checks that named it, or set `refused` for only refused ones. Send `before` to start from a moment. Limitry keeps the last 3 days, and at most 100,000 checks in each environment. Results come a page at a time.
# Limits API
> The limits endpoints, each in TypeScript, Python, the CLI and curl.
The limits endpoints, each in TypeScript, Python, the CLI and curl.
## Set up
[Section titled “Set up”](#set-up)
* TypeScript
```bash
npm install @limitry/sdk
export LIMITRY_API_KEY="lim_test_…"
```
* Python
```bash
pip install limitry
export LIMITRY_API_KEY="lim_test_…"
```
* CLI
```bash
npm install -g @limitry/cli
limitry login
```
* curl
```bash
export LIMITRY_API_KEY="lim_test_…"
```
To pass the key yourself, use `createClient({ apiKey: key })` in TypeScript or `Limitry(api_key=key)` in Python.
## List limits
[Section titled “List limits”](#list-limits)
`GET /v1/limits`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/limits/GET/limits)
Scope: `limits:read`.
Lists this environment’s active limits, newest first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const limits = await limitry.limits.list();
console.log(limits);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limits = limitry.limits.list()
print(limits)
```
* CLI
```bash
limitry limits list
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/limits" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"id": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"name": "AI budget",
"subject": {
"kind": "user",
"id": null
},
"action": "ai-call",
"amount": 200,
"unit": "cents",
"window": "month",
"every": 1,
"start": "calendar",
"rolling": false,
"enabled": true,
"archivedAt": null,
"failMode": "open",
"lastCheckedAt": "2026-11-06T12:00:00.000Z",
"setIn": null,
"override": null,
"createdAt": "2026-10-04T12:00:00.000Z",
"updatedAt": "2026-10-04T12:00:00.000Z"
}
],
"nextCursor": null
}
```
| Field | Description |
| --------------------------- | ------------------------------------------------ |
| `limit` number, query | Items per page, 1–100 (default 25). |
| `cursor` string, query | Opaque token from a previous page's nextCursor. |
| `subjectKind` string, query | Only limits for this subject kind. |
| `action` string, query | Only limits for this action. |
| `archived` string, query | Send `true` to list the archived limits instead. |
More about this endpoint
With `archived=true`, it lists the archived ones instead. Filter by `subjectKind` and `action`, and page through the results with the opaque `nextCursor` token.
## Create a limit
[Section titled “Create a limit”](#create-a-limit)
`POST /v1/limits`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/limits/POST/limits)
Scope: `limits:write`.
Creates a limit on how much a subject may use per window, such as 200 cents a month for every `user`.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const limit = await limitry.limits.create({
name: "AI budget",
subject: {
kind: "user",
},
action: "ai-call",
amount: 200,
unit: "cents",
window: "month",
every: 1,
start: "calendar",
});
console.log(limit);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limit = limitry.limits.create(
name="AI budget",
subject={"kind": "user"},
action="ai-call",
amount=200,
unit="cents",
window="month",
every=1,
start="calendar",
)
print(limit)
```
* CLI
```bash
limitry limits create \
--name 'AI budget' \
--subject '{"kind":"user"}' \
--action ai-call \
--amount 200 \
--unit cents \
--window month \
--every 1 \
--start calendar
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/limits" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"AI budget","subject":{"kind":"user"},"action":"ai-call","amount":200,"unit":"cents","window":"month","every":1,"start":"calendar"}'
```
**Returns:**
```json
{
"id": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"name": "AI budget",
"subject": {
"kind": "user",
"id": null
},
"action": "ai-call",
"amount": 200,
"unit": "cents",
"window": "month",
"every": 1,
"start": "calendar",
"rolling": false,
"enabled": true,
"archivedAt": null,
"failMode": "open",
"lastCheckedAt": "2026-11-06T12:00:00.000Z",
"setIn": null,
"override": null,
"createdAt": "2026-10-04T12:00:00.000Z",
"updatedAt": "2026-10-04T12:00:00.000Z"
}
```
| Field | Description |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` string | The limit's name, unique among the environment's active limits. By default, it's the sentence the limit reads as, such as "200 cents per user per month". If another limit already has that name, you get a 409, so send a name of your own. |
| `subject` object, required | Who the limit applies to. `{"kind": "user"}` covers every user, and `{"kind": "user", "id": "user_123"}` covers one. |
| `action` string | The action to limit. Default: `*`, every action. |
| `amount` number, required | How many units each subject may use per window. |
| `unit` string | What the amount counts, in words. Default: units. |
| `window` string, required | The kind of period. `minute`, `hour`, `day`, `week`, `month` and `year` count a period of `every` windows, which resets where `start` says, or rolls when `rolling` is true. `total` is a balance that never resets, and credits raise it. `concurrent` allows at most `amount` open reservations at once. |
| `every` number | How many `window` units one period lasts. For example, `window: "month", every: 3` is a quarter, and `window: "hour", every: 5` is five hours. Default: 1. |
| `start` string | Where each period begins. `calendar` uses UTC boundaries: midnight, Monday, the 1st or 1 January. `billing_date` counts from the subject's billing date. You set it with `subjects.update`. An annual plan can then still reset monthly. Until a subject has a billing date, its first check stands in for it. `first_use` starts a period at the first check after the previous one ended. Default: calendar. |
| `rolling` boolean | Whether to count the last `every` windows up to the moment of each check, rather than fixed periods. Only `minute`, `hour` and `day` limits can roll. Default: false. |
| `enabled` boolean | Whether checks enforce the limit. Default: true. |
| `failMode` string | What your code should do when it can't reach Limitry. `open` allows and `closed` refuses. Default: open. |
More about this endpoint
You only need to send `subject.kind`, `amount` and `window`. `action` defaults to every action (`*`), `unit` to units, and `name` to the sentence the limit reads as. The next check enforces the new limit. You can’t change a limit’s subject, action, unit, window, every, start or rolling after you create it. With a personal access token, the owner and admins can call this. Members can call it in test only, and guests can’t. A workspace API key with this scope can.
## Get a limit
[Section titled “Get a limit”](#get-a-limit)
`GET /v1/limits/{limitId}`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/limits/GET/limits/{limitId})
Scope: `limits:read`.
Returns one limit, with who it applies to, its action, its amount and its window.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const limit = await limitry.limits.get("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34");
console.log(limit);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limit = limitry.limits.get("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34")
print(limit)
```
* CLI
```bash
limitry limits get lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/limits/lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"id": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"name": "AI budget",
"subject": {
"kind": "user",
"id": null
},
"action": "ai-call",
"amount": 200,
"unit": "cents",
"window": "month",
"every": 1,
"start": "calendar",
"rolling": false,
"enabled": true,
"archivedAt": null,
"failMode": "open",
"lastCheckedAt": "2026-11-06T12:00:00.000Z",
"setIn": null,
"override": null,
"createdAt": "2026-10-04T12:00:00.000Z",
"updatedAt": "2026-10-04T12:00:00.000Z"
}
```
| Field | Description |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `limitId` string, path, required | The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case. |
## Change a limit
[Section titled “Change a limit”](#change-a-limit)
`PATCH /v1/limits/{limitId}`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/limits/PATCH/limits/{limitId})
Scope: `limits:write`.
Changes a limit’s name, amount, fail mode or whether it’s enabled.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const limit = await limitry.limits.update("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34", {
name: "AI budget",
amount: 300,
subject: {
kind: "user",
},
override: {
reason: "Support incident: raised for a customer",
},
});
console.log(limit);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limit = limitry.limits.update(
"lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
name="AI budget",
amount=300,
subject={"kind": "user"},
override={
"reason": "Support incident: raised for a customer",
},
)
print(limit)
```
* CLI
```bash
limitry limits update \
lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34 \
--name 'AI budget' \
--amount 300 \
--subject '{"kind":"user"}' \
--override '{"reason":"Support incident: raised for a customer"}'
```
* curl
```bash
curl -X PATCH "https://api.limitry.com/v1/limits/lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"AI budget","amount":300,"subject":{"kind":"user"},"override":{"reason":"Support incident: raised for a customer"}}'
```
**Returns:**
```json
{
"id": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"name": "AI budget",
"subject": {
"kind": "user",
"id": null
},
"action": "ai-call",
"amount": 200,
"unit": "cents",
"window": "month",
"every": 1,
"start": "calendar",
"rolling": false,
"enabled": true,
"archivedAt": null,
"failMode": "open",
"lastCheckedAt": "2026-11-06T12:00:00.000Z",
"setIn": null,
"override": null,
"createdAt": "2026-10-04T12:00:00.000Z",
"updatedAt": "2026-10-04T12:00:00.000Z"
}
```
| Field | Description |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `limitId` string, path, required | The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case. |
| `name` string | A new name, unique among the environment's active limits. |
| `amount` number | How many units each subject may use per window. |
| `enabled` boolean | Whether checks enforce the limit. |
| `failMode` string | What your code should do when it can't reach Limitry. `open` allows and `closed` refuses. |
| `subject` object | Who the limit applies to. You set it when you create the limit. To change it later, create a new limit and archive this one. |
| `action` string | The action the limit applies to. You set it when you create the limit. To change it later, create a new limit and archive this one. |
| `unit` string | What the amount counts. You set it when you create the limit. To change it later, create a new limit and archive this one. |
| `window` string | The kind of period. You set it when you create the limit. To change it later, create a new limit and archive this one. |
| `every` number | How many windows one period lasts. You set it when you create the limit. To change it later, create a new limit and archive this one. |
| `start` string | Where each period begins. You set it when you create the limit. To change it later, create a new limit and archive this one. |
| `rolling` boolean | Whether the limit counts the last windows up to each check. You set it when you create the limit. To change it later, create a new limit and archive this one. |
| `override` object | Changes a limit a sync sets, until the next sync puts its values back. Only owners and admins, or a workspace API key, can override. Without it, changing such a limit gets a 409. You can't rename it, because the sync finds it by name. |
More about this endpoint
Checks use the new rule at once. You can’t change a limit’s subject, action, unit, window, every, start or rolling, and a request that tries gets a 400. To count something different, create a new limit and archive this one. A limit a sync sets (its `setIn`) changes only through the sync. A request to change one gets a 409 that names where the sync came from, unless it sends `override` with a reason. An override lasts until the next sync. With a personal access token, the owner and admins can call this. Members can call it in test only, and guests can’t. A workspace API key with this scope can.
## Archive a limit
[Section titled “Archive a limit”](#archive-a-limit)
`POST /v1/limits/{limitId}/archive`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/limits/POST/limits/{limitId}/archive)
Scope: `limits:write`.
Archives a limit, so checks stop enforcing it at once and it leaves the list.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.limits.archive("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34");
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.limits.archive("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34")
print(result)
```
* CLI
```bash
limitry limits archive lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/limits/lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34/archive" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"id": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"name": "AI budget",
"subject": {
"kind": "user",
"id": null
},
"action": "ai-call",
"amount": 200,
"unit": "cents",
"window": "month",
"every": 1,
"start": "calendar",
"rolling": false,
"enabled": true,
"archivedAt": null,
"failMode": "open",
"lastCheckedAt": "2026-11-06T12:00:00.000Z",
"setIn": null,
"override": null,
"createdAt": "2026-10-04T12:00:00.000Z",
"updatedAt": "2026-10-04T12:00:00.000Z"
}
```
| Field | Description |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `limitId` string, path, required | The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case. |
More about this endpoint
Archiving erases nothing. Limitry keeps the limit’s usage history and credits, and `POST /v1/limits/{limitId}/restore` brings it back. With a personal access token, the owner and admins can call this. Members can call it in test only, and guests can’t. A workspace API key with this scope can.
## Restore an archived limit
[Section titled “Restore an archived limit”](#restore-an-archived-limit)
`POST /v1/limits/{limitId}/restore`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/limits/POST/limits/{limitId}/restore)
Scope: `limits:write`.
Brings an archived limit back.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.limits.restore("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34");
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.limits.restore("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34")
print(result)
```
* CLI
```bash
limitry limits restore lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/limits/lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34/restore" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"id": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"name": "AI budget",
"subject": {
"kind": "user",
"id": null
},
"action": "ai-call",
"amount": 200,
"unit": "cents",
"window": "month",
"every": 1,
"start": "calendar",
"rolling": false,
"enabled": true,
"archivedAt": null,
"failMode": "open",
"lastCheckedAt": "2026-11-06T12:00:00.000Z",
"setIn": null,
"override": null,
"createdAt": "2026-10-04T12:00:00.000Z",
"updatedAt": "2026-10-04T12:00:00.000Z"
}
```
| Field | Description |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `limitId` string, path, required | The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case. |
More about this endpoint
Checks enforce it again if it’s enabled. The API refuses it while an active limit has the same name. With a personal access token, the owner and admins can call this. Members can call it in test only, and guests can’t. A workspace API key with this scope can.
## Sync limits from a list
[Section titled “Sync limits from a list”](#sync-limits-from-a-list)
`POST /v1/limits/sync`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/limits/POST/limits/sync)
Scope: `limits:write`.
Makes the environment’s limits match the list in `limits`, pairing them up by name.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.limits.sync({
limits: [
{
name: "AI budget",
subject: {
kind: "user",
},
action: "ai-call",
amount: 200,
unit: "cents",
window: "month",
},
],
source: "limitry.json",
});
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.limits.sync(
limits=[
{
"name": "AI budget",
"subject": {"kind": "user"},
"action": "ai-call",
"amount": 200,
"unit": "cents",
"window": "month",
},
],
source="limitry.json",
)
print(result)
```
* CLI
Day to day: `limitry sync [file]`. This endpoint’s own command:
```bash
limitry limits sync \
--limits '[{"name":"AI budget","subject":{"kind":"user"},"action":"ai-call","amount":200,"unit":"cents","window":"month"}]' \
--source limitry.json
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/limits/sync" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"limits":[{"name":"AI budget","subject":{"kind":"user"},"action":"ai-call","amount":200,"unit":"cents","window":"month"}],"source":"limitry.json"}'
```
**Returns:**
```json
{
"dryRun": false,
"created": [
"Team credits"
],
"updated": [
{
"name": "AI budget",
"changes": {
"amount": {
"from": 200,
"to": 300
}
}
}
],
"archived": [],
"unchanged": [
"API requests per minute"
],
"restored": [],
"kinds": null
}
```
| Field | Description |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `limits` array, required | Every limit you want, each described in full. An omitted field takes its default, as on create. A sync matches limits by name, so each name must be unique in the list. You can't change a limit's subject, action, unit, window, every, start or rolling under the same name. To change one of them, rename the entry, which creates a new limit. The list holds at most 200 limits. |
| `archiveMissing` boolean | Whether to archive the environment's active limits whose names aren't in `limits`. You can restore them later. Default: false, which leaves them alone. |
| `dryRun` boolean | Whether to report what the sync would do without changing anything. Default: false. |
| `source` string | Where these limits come from, such as the file's name or your deploy's. The app and the 409 name it on every limit the sync sets, as in "Set by limitry.json". The CLI sends the file's name. Default: `a sync`. |
| `kinds` array | The workspace's kinds, from the top level down: how the app names each and the order its subject pages use for Above and Below. They replace the workspace's kinds, for test and live alike, so only owners and admins (or a workspace key) can send them. Leave this out to leave the kinds alone. Labels only: checks and the API keep using the kinds themselves. |
More about this endpoint
It creates the limits that are missing and changes the ones that differ, where an omitted field means its default. With `archiveMissing`, it also archives the active limits the list doesn’t name. Running it twice changes nothing the second time. Limitry checks the whole list before writing anything. If any entry has a problem, nothing changes, and the 400 lists each problem in `details`. Otherwise Limitry writes every change at once. You can’t change a limit’s subject, action, unit, window, every, start or rolling under the same name, so rename the entry to do that. With `dryRun`, it returns what it would do without writing anything. What a sync sets is locked in the app until the next sync, which names its `source`. This is the call behind `limitry sync`, for keeping your limits in a file in your repository. With a personal access token, the owner and admins can call this. Members can call it in test only, and guests can’t. A workspace API key with this scope can.
## Get a credit
[Section titled “Get a credit”](#get-a-credit)
`GET /v1/limits/{limitId}/credits/{creditId}`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/limits/GET/limits/{limitId}/credits/{creditId})
Scope: `limits:read`.
Returns one credit added to a subject’s balance on this limit.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const credit = await limitry.limits.credits.get("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34", "crd_5a8d3f2b-9c1e-4b7a-8f6d-2e0c9b4a1d73");
console.log(credit);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
credit = limitry.limits.credits.get(
"lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"crd_5a8d3f2b-9c1e-4b7a-8f6d-2e0c9b4a1d73",
)
print(credit)
```
* CLI
```bash
limitry limits credits get \
lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34 \
crd_5a8d3f2b-9c1e-4b7a-8f6d-2e0c9b4a1d73
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/limits/lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34/credits/crd_5a8d3f2b-9c1e-4b7a-8f6d-2e0c9b4a1d73" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"id": "crd_5a8d3f2b-9c1e-4b7a-8f6d-2e0c9b4a1d73",
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"subject": {
"kind": "user",
"id": "user_123"
},
"amount": 5000,
"note": "October credits",
"createdByUserId": "usr_9b1d4e7a-2c5f-4a8b-b3e6-7f0d1c2a5e94",
"createdAt": "2026-11-05T09:00:00.000Z",
"periodStart": "2026-11-01T00:00:00.000Z",
"periodEnd": "2026-12-01T00:00:00.000Z"
}
```
| Field | Description |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `limitId` string, path, required | The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case. |
| `creditId` string, path, required | The credit's ID. |
## List a balance’s credits
[Section titled “List a balance’s credits”](#list-a-balances-credits)
`GET /v1/limits/{limitId}/credits`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/limits/GET/limits/{limitId}/credits)
Scope: `limits:read`.
Lists the credits added to subjects’ balances on this limit, including any taken back, newest first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const credits = await limitry.limits.credits.list("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34");
console.log(credits);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
credits = limitry.limits.credits.list("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34")
print(credits)
```
* CLI
```bash
limitry limits credits list lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/limits/lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34/credits" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"id": "crd_5a8d3f2b-9c1e-4b7a-8f6d-2e0c9b4a1d73",
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"subject": {
"kind": "user",
"id": "user_123"
},
"amount": 5000,
"note": "October credits",
"createdByUserId": "usr_9b1d4e7a-2c5f-4a8b-b3e6-7f0d1c2a5e94",
"createdAt": "2026-11-05T09:00:00.000Z",
"periodStart": "2026-11-01T00:00:00.000Z",
"periodEnd": "2026-12-01T00:00:00.000Z"
}
],
"nextCursor": null
}
```
| Field | Description |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `limitId` string, path, required | The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case. |
| `limit` number, query | Items per page, 1–100 (default 25). |
| `cursor` string, query | Opaque token from a previous page's nextCursor. |
| `before` string, query | Start from this moment: items older than it, newest first. Ignored with `cursor`, which already says where to go on. |
| `subjectId` string, query | Only the credits for this subject. |
More about this endpoint
Page through them with the opaque `nextCursor`. `before` starts from a moment, and `subjectId` keeps one subject’s credits.
## Add credits to a balance
[Section titled “Add credits to a balance”](#add-credits-to-a-balance)
`POST /v1/limits/{limitId}/credits`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/limits/POST/limits/{limitId}/credits)
Scope: `limits:write`.
Adds `amount` credits for one subject on a limit.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const credit = await limitry.limits.credits.create("lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34", {
subject: {
kind: "team",
id: "team_42",
},
amount: 5000,
note: "October credits",
});
console.log(credit);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
credit = limitry.limits.credits.create(
"lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
subject={"kind": "team", "id": "team_42"},
amount=5000,
note="October credits",
)
print(credit)
```
* CLI
```bash
limitry limits credits create \
lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34 \
--subject '{"kind":"team","id":"team_42"}' \
--amount 5000 \
--note 'October credits'
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/limits/lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34/credits" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"subject":{"kind":"team","id":"team_42"},"amount":5000,"note":"October credits"}'
```
**Returns:**
```json
{
"id": "crd_5a8d3f2b-9c1e-4b7a-8f6d-2e0c9b4a1d73",
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"subject": {
"kind": "user",
"id": "user_123"
},
"amount": 5000,
"note": "October credits",
"createdByUserId": "usr_9b1d4e7a-2c5f-4a8b-b3e6-7f0d1c2a5e94",
"createdAt": "2026-11-05T09:00:00.000Z",
"periodStart": "2026-11-01T00:00:00.000Z",
"periodEnd": "2026-12-01T00:00:00.000Z"
}
```
| Field | Description |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `limitId` string, path, required | The limit's ID, or its name, such as `AI budget` (URL-encoded). A name matches an active limit in this environment, exactly or else ignoring case. |
| `subject` object, required | Who gets the credits, such as `{"kind": "team", "id": "team_42"}`. |
| `amount` number, required | The credits to add, or a negative number to take them back. It can't be 0. |
| `note` string | Why you added or took back credits. It's required when `amount` is negative. |
More about this endpoint
On a balance, a limit whose window is `total`, the credits stay until they’re spent. On a limit that resets, such as one with a `month` window, the credits top up the subject’s current period and end when it resets. That period follows the subject’s billing date when the limit starts there, and the answer’s `periodEnd` says when it ends. A rolling or concurrent limit can’t take credits. A negative `amount` takes credits back, such as after a refund or a chargeback, and needs a `note` saying why. The balance can go below zero, and Limitry then refuses checks until you add more credits. With a personal access token, the owner and admins can add credits. Members can add them in test only. A workspace API key with this scope can add them too. An agent connected through MCP asks a person instead, through the `limit.credit` approval. Limitry keeps a credit’s `Idempotency-Key` forever, so never reuse one for a new credit.
# Personal access tokens API
> The personal access tokens endpoints, each in TypeScript, Python, the CLI and curl.
The personal access tokens endpoints, each in TypeScript, Python, the CLI and curl.
## Set up
[Section titled “Set up”](#set-up)
This takes a [personal access token](/docs/authentication/), not an API key. In the SDKs, pass it as `token`.
* TypeScript
```bash
npm install @limitry/sdk
export LIMITRY_TOKEN=""
```
* Python
```bash
pip install limitry
export LIMITRY_TOKEN=""
```
* CLI
```bash
npm install -g @limitry/cli
limitry login
```
* curl
```bash
export LIMITRY_TOKEN=""
```
## Get the current user
[Section titled “Get the current user”](#get-the-current-user)
`GET /v1/user/me`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/personal-access-tokens/GET/user/me)
Returns the user the personal access token belongs to, and their workspace memberships.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
const limitry = createClient({ token: process.env.LIMITRY_TOKEN });
const me = await limitry.user.me();
console.log(me);
```
* Python
```python
import os
from limitry import Limitry
limitry = Limitry(token=os.environ["LIMITRY_TOKEN"])
me = limitry.user.me()
print(me)
```
* CLI
```bash
limitry user me
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/user/me" \
-H "Authorization: Bearer $LIMITRY_TOKEN"
```
**Returns:**
```json
{
"id": "usr_4f8a2c1e-7b3d-4e9f-a6c5-2d1b0e9f8a7c",
"name": "Casey Customer",
"email": "casey@example.com",
"workspaces": [
{
"id": "ws_9418b705-3720-48ca-b2bf-f726d1456684",
"name": "Acme Inc.",
"slug": "acme",
"role": "owner"
}
]
}
```
More about this endpoint
Use it as a smoke test for an integration (“who am I?”).
## Revoke the token making this request
[Section titled “Revoke the token making this request”](#revoke-the-token-making-this-request)
`DELETE /v1/user/token`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/personal-access-tokens/DELETE/user/token)
Revokes the personal access token that makes the request.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
const limitry = createClient({ token: process.env.LIMITRY_TOKEN });
await limitry.user.revokeToken();
```
* Python
```python
import os
from limitry import Limitry
limitry = Limitry(token=os.environ["LIMITRY_TOKEN"])
limitry.user.revoke_token()
```
* CLI
```bash
limitry user revoke-token --yes
```
* curl
```bash
curl -X DELETE "https://api.limitry.com/v1/user/token" \
-H "Authorization: Bearer $LIMITRY_TOKEN"
```
**Returns** nothing (`204`).
More about this endpoint
Use it to sign out from a script or the CLI (`logout`). The token stops working immediately. Your other tokens keep working.
# Reservations API
> The reservations endpoints, each in TypeScript, Python, the CLI and curl.
The reservations endpoints, each in TypeScript, Python, the CLI and curl.
## Set up
[Section titled “Set up”](#set-up)
* TypeScript
```bash
npm install @limitry/sdk
export LIMITRY_API_KEY="lim_test_…"
```
* Python
```bash
pip install limitry
export LIMITRY_API_KEY="lim_test_…"
```
* CLI
```bash
npm install -g @limitry/cli
limitry login
```
* curl
```bash
export LIMITRY_API_KEY="lim_test_…"
```
To pass the key yourself, use `createClient({ apiKey: key })` in TypeScript or `Limitry(api_key=key)` in Python.
## Get a reservation
[Section titled “Get a reservation”](#get-a-reservation)
`GET /v1/reservations/{reservationId}`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/reservations/GET/reservations/{reservationId})
Scope: `checks:write`.
Returns a reservation as it stands: held, committed, released or expired, with what it reserved and what it finally used.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const reservation = await limitry.reservations.get("");
console.log(reservation);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
reservation = limitry.reservations.get("")
print(reservation)
```
* CLI
```bash
limitry reservations get ''
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/reservations/" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"id": "rsv_WyJ1c2VyIiwidXNlcl8xMjMiXQ_9f2c4e1a7b3d4c8e9a0f1b2c3d4e5f6a",
"status": "committed",
"reserved": 5,
"cost": 3,
"expiresAt": "2026-11-06T12:05:00.000Z"
}
```
| Field | Description |
| -------------------------------------- | --------------------- |
| `reservationId` string, path, required | The reservation's ID. |
More about this endpoint
A reservation past its expiry that nobody committed or released reads as expired. Reading it changes nothing.
## Extend a reservation
[Section titled “Extend a reservation”](#extend-a-reservation)
`POST /v1/reservations/{reservationId}/extend`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/reservations/POST/reservations/{reservationId}/extend)
Scope: `checks:write`.
Keeps a reservation open for longer work, so it expires `ttlSeconds` from now.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.reservations.extend("", {
ttlSeconds: 600,
});
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.reservations.extend("", ttl_seconds=600)
print(result)
```
* CLI
```bash
limitry reservations extend '' --ttl-seconds 600
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/reservations//extend" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"ttlSeconds":600}'
```
**Returns:**
```json
{
"id": "rsv_WyJ1c2VyIiwidXNlcl8xMjMiXQ_9f2c4e1a7b3d4c8e9a0f1b2c3d4e5f6a",
"status": "committed",
"reserved": 5,
"cost": 3,
"expiresAt": "2026-11-06T12:05:00.000Z"
}
```
| Field | Description |
| -------------------------------------- | --------------------------------------------------------------------------- |
| `reservationId` string, path, required | The reservation's ID. |
| `ttlSeconds` number | Seconds from now until the reservation expires. Default: 300. At most 3600. |
More about this endpoint
Call it again as a heartbeat while the work runs. You can only extend a reservation that’s still held. We cache its API key check briefly for speed. A revoked key can keep working here for up to 60 seconds.
## Commit a reservation
[Section titled “Commit a reservation”](#commit-a-reservation)
`POST /v1/reservations/{reservationId}/commit`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/reservations/POST/reservations/{reservationId}/commit)
Scope: `checks:write`.
Commits a reservation with the amount actually used (`cost`).
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.reservations.commit("", {
cost: 3,
});
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.reservations.commit("", cost=3)
print(result)
```
* CLI
```bash
limitry reservations commit '' --cost 3
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/reservations//commit" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"cost":3}'
```
**Returns:**
```json
{
"id": "rsv_WyJ1c2VyIiwidXNlcl8xMjMiXQ_9f2c4e1a7b3d4c8e9a0f1b2c3d4e5f6a",
"status": "committed",
"reserved": 5,
"cost": 3,
"expiresAt": "2026-11-06T12:05:00.000Z"
}
```
| Field | Description |
| -------------------------------------- | ------------------------- |
| `reservationId` string, path, required | The reservation's ID. |
| `cost` number, required | The amount actually used. |
More about this endpoint
If `cost` is less than the amount reserved, the rest goes back at once. If it’s more, Limitry charges the whole `cost`, since the work happened. A commit up to 24 hours after the reservation expired still charges `cost`. Repeating a commit with the same `cost` returns the same result, and a different `cost` gets a 400. Committing a released reservation gets a 409. We cache its API key check briefly for speed. A revoked key can keep working here for up to 60 seconds.
## Release a reservation
[Section titled “Release a reservation”](#release-a-reservation)
`POST /v1/reservations/{reservationId}/release`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/reservations/POST/reservations/{reservationId}/release)
Scope: `checks:write`.
Gives the whole reservation back, because the work didn’t happen.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.reservations.release("");
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.reservations.release("")
print(result)
```
* CLI
```bash
limitry reservations release ''
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/reservations//release" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"id": "rsv_WyJ1c2VyIiwidXNlcl8xMjMiXQ_9f2c4e1a7b3d4c8e9a0f1b2c3d4e5f6a",
"status": "committed",
"reserved": 5,
"cost": 3,
"expiresAt": "2026-11-06T12:05:00.000Z"
}
```
| Field | Description |
| -------------------------------------- | --------------------- |
| `reservationId` string, path, required | The reservation's ID. |
More about this endpoint
Repeating a release within 24 hours returns the same result. You can’t release a reservation you’ve already committed. We cache its API key check briefly for speed. A revoked key can keep working here for up to 60 seconds.
# Subjects API
> The subjects endpoints, each in TypeScript, Python, the CLI and curl.
The subjects endpoints, each in TypeScript, Python, the CLI and curl.
## Set up
[Section titled “Set up”](#set-up)
* TypeScript
```bash
npm install @limitry/sdk
export LIMITRY_API_KEY="lim_test_…"
```
* Python
```bash
pip install limitry
export LIMITRY_API_KEY="lim_test_…"
```
* CLI
```bash
npm install -g @limitry/cli
limitry login
```
* curl
```bash
export LIMITRY_API_KEY="lim_test_…"
```
To pass the key yourself, use `createClient({ apiKey: key })` in TypeScript or `Limitry(api_key=key)` in Python.
## Get a subject
[Section titled “Get a subject”](#get-a-subject)
`GET /v1/subjects/{subjectKind}/{subjectId}`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/subjects/GET/subjects/{subjectKind}/{subjectId})
Scope: `limits:read`.
Returns a subject: its billing date, the day its `billing_date` limits start each new period, its name and labels if you gave it any, its budgets, and the subjects it’s checked with.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const subject = await limitry.subjects.get("team", "team_42");
console.log(subject);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
subject = limitry.subjects.get("team", "team_42")
print(subject)
```
* CLI
```bash
limitry subjects get team team_42
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/subjects/team/team_42" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"subject": {
"kind": "user",
"id": "user_123"
},
"billingAnchorAt": "2026-03-17T14:30:00.000Z",
"name": "Sara Khan",
"labels": {
"plan": "pro"
},
"budgets": [
{
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"limitName": "AI budget",
"unit": "cents",
"window": "month",
"amount": 200,
"used": 120,
"remaining": 80,
"credited": 0,
"resetsAt": "2026-12-01T00:00:00.000Z"
}
],
"links": [
{
"subject": {
"kind": "user",
"id": "user_123",
"name": "Sara Khan"
},
"direction": "within",
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"limitName": "Team AI budget",
"unit": "cents",
"periodStart": "2026-11-01T00:00:00.000Z",
"spent": 120,
"allowed": 4,
"refused": 1
}
]
}
```
| Field | Description |
| ------------------------------------ | ---------------------- |
| `subjectKind` string, path, required | The subject kind's ID. |
| `subjectId` string, path, required | The subject's ID. |
More about this endpoint
A subject is one of yours, such as a user, a team or an agent. It exists once a check names it. Its links say what was spent within each budget this period: within another subject’s budget, or another subject within its own.
## Update a subject
[Section titled “Update a subject”](#update-a-subject)
`PATCH /v1/subjects/{subjectKind}/{subjectId}`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/subjects/PATCH/subjects/{subjectKind}/{subjectId})
Scope: `limits:write`.
Sets a subject’s billing date, its name, its labels, or any of them.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const subject = await limitry.subjects.update("team", "team_42", {
billingAnchorAt: "2026-03-17T14:30:00Z",
name: "Design team",
labels: {
plan: "pro",
},
});
console.log(subject);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
subject = limitry.subjects.update(
"team",
"team_42",
billing_anchor_at="2026-03-17T14:30:00Z",
name="Design team",
labels={"plan": "pro"},
)
print(subject)
```
* CLI
```bash
limitry subjects update \
team \
team_42 \
--billing-anchor-at 2026-03-17T14:30:00Z \
--name 'Design team' \
--labels '{"plan":"pro"}'
```
* curl
```bash
curl -X PATCH "https://api.limitry.com/v1/subjects/team/team_42" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"billingAnchorAt":"2026-03-17T14:30:00Z","name":"Design team","labels":{"plan":"pro"}}'
```
**Returns:**
```json
{
"subject": {
"kind": "user",
"id": "user_123"
},
"billingAnchorAt": "2026-03-17T14:30:00.000Z",
"name": "Sara Khan",
"labels": {
"plan": "pro"
}
}
```
| Field | Description |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `subjectKind` string, path, required | The subject kind's ID. |
| `subjectId` string, path, required | The subject's ID. |
| `billingAnchorAt` string | The moment the subject's periods start from, in ISO 8601, such as a subscription's start. |
| `name` string | A name people can read, up to 200 characters. Optional. Names don't have to be unique. Send null to clear it. |
| `labels` object | Labels to filter by, such as a plan or a region: up to 20 keys of up to 40 characters, with values of up to 200. Optional. They replace the subject's labels. Send null to clear them. |
More about this endpoint
A field you leave out stays as it is, and null clears a name or labels. Labels you send replace the subject’s labels. The billing date is the moment the subject’s `billing_date` limits count their periods from, usually the subscription’s start, set from your billing system’s webhook. The subject’s allowance then resets on its own billing day, and a monthly limit still resets monthly on an annual plan. A name and labels are optional, and checks never need them. With a personal access token, the owner and admins can call this. Members can call it in test only, and guests can’t. A workspace API key with this scope can.
## Get where a subject stands
[Section titled “Get where a subject stands”](#get-where-a-subject-stands)
`GET /v1/subjects/{subjectKind}/{subjectId}/standing`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/subjects/GET/subjects/{subjectKind}/{subjectId}/standing)
Scope: `limits:read`.
Returns where one subject stands on every enabled limit, exact as of now.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.subjects.standing("team", "team_42");
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.subjects.standing("team", "team_42")
print(result)
```
* CLI
```bash
limitry subjects standing team team_42
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/subjects/team/team_42/standing" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"subject": {
"kind": "user",
"id": "user_123"
},
"limits": [
{
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"limitName": "AI budget",
"subject": {
"kind": "user",
"id": "user_123"
},
"action": "ai-call",
"unit": "cents",
"window": "month",
"rolling": false,
"amount": 200,
"used": 5,
"remaining": 195,
"credited": 0,
"resetsAt": "2026-12-01T00:00:00.000Z"
}
]
}
```
| Field | Description |
| ------------------------------------ | ----------------------------------------------------------------------------- |
| `subjectKind` string, path, required | The subject kind's ID. |
| `subjectId` string, path, required | The subject's ID. |
| `shared` string, query | Shared subjects to include, as comma-separated `kind:id` pairs. Send up to 4. |
More about this endpoint
It covers the subject’s own limits and the limits on its shared subjects. List the shared subjects in `shared`, such as `team:team_42`. Each limit shows what’s used, what’s left and when it resets. Use it to show your users where they stand. Call it from your server with your key, never from a browser. It isn’t a check, so it counts nothing. A subject with no limits returns an empty `limits` list.
## Reset a subject’s limits
[Section titled “Reset a subject’s limits”](#reset-a-subjects-limits)
`POST /v1/subjects/{subjectKind}/{subjectId}/reset`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/subjects/POST/subjects/{subjectKind}/{subjectId}/reset)
Scope: `limits:write`.
Resets one limit on a subject now, or every limit on it.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.subjects.reset("team", "team_42", {
limitId: "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
});
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.subjects.reset(
"team",
"team_42",
limit_id="lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
)
print(result)
```
* CLI
```bash
limitry subjects reset \
team \
team_42 \
--limit-id lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/subjects/team/team_42/reset" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"limitId":"lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34"}'
```
**Returns:**
```json
{
"subject": {
"kind": "user",
"id": "user_123"
},
"limitIds": [
"lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34"
]
}
```
| Field | Description |
| ------------------------------------ | ------------------------------------------------------------ |
| `subjectKind` string, path, required | The subject kind's ID. |
| `subjectId` string, path, required | The subject's ID. |
| `limitId` string | The one limit to reset. Default: every limit on the subject. |
More about this endpoint
Send `limitId` for one limit, or `{}` for all of them. Use it for goodwill, a promotion or support. The schedule doesn’t move, so the next reset still happens when it normally would. A balance goes back to its amount, and the reset skips concurrent limits. With an Idempotency-Key, a repeated request resets only once. With a personal access token, the owner and admins can call this. Members can call it in test only, and guests can’t. A workspace API key with this scope can.
## Erase a subject’s name and labels
[Section titled “Erase a subject’s name and labels”](#erase-a-subjects-name-and-labels)
`DELETE /v1/subjects/{subjectKind}/{subjectId}/names`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/subjects/DELETE/subjects/{subjectKind}/{subjectId}/names)
Scope: `limits:write`.
Erases the name and labels you gave a subject.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
await limitry.subjects.names.delete("team", "team_42");
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limitry.subjects.names.delete("team", "team_42")
```
* CLI
```bash
limitry subjects names delete team team_42 --yes
```
* curl
```bash
curl -X DELETE "https://api.limitry.com/v1/subjects/team/team_42/names" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns** nothing (`204`).
| Field | Description |
| ------------------------------------ | ---------------------- |
| `subjectKind` string, path, required | The subject kind's ID. |
| `subjectId` string, path, required | The subject's ID. |
More about this endpoint
Its limits, usage and billing date stay, because they’re kept by its ID. Use it when one of your users asks you to delete their data. Erasing a subject with no name or labels succeeds too. With a personal access token, the owner and admins can call this. Members can call it in test only, and guests can’t. A workspace API key with this scope can.
## Name many subjects
[Section titled “Name many subjects”](#name-many-subjects)
`POST /v1/subjects/import`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/subjects/POST/subjects/import)
Scope: `limits:write`.
Sets the name and labels of up to 1,000 subjects at once, such as when you first connect your user list.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.subjects.import({
items: [
{
kind: "team",
id: "team_42",
name: "Design team",
labels: {
plan: "pro",
},
},
],
});
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.subjects.import_(
items=[
{
"kind": "team",
"id": "team_42",
"name": "Design team",
"labels": {"plan": "pro"},
},
],
)
print(result)
```
* CLI
```bash
limitry subjects import \
--items '[{"kind":"team","id":"team_42","name":"Design team","labels":{"plan":"pro"}}]'
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/subjects/import" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"items":[{"kind":"team","id":"team_42","name":"Design team","labels":{"plan":"pro"}}]}'
```
**Returns:**
```json
{
"imported": 1
}
```
| Field | Description |
| ----------------------- | ---------------------------------------------------------------------------------------------- |
| `items` array, required | The subjects to name, from 1 to 1,000: each its kind and ID, and its name, its labels or both. |
More about this endpoint
Each item works like updating that subject’s name and labels: a field you leave out stays as it is, and null clears it. Limitry checks every item before it saves any, so a bad item saves nothing. With a personal access token, the owner and admins can call this. Members can call it in test only, and guests can’t. A workspace API key with this scope can.
## List subjects
[Section titled “List subjects”](#list-subjects)
`GET /v1/subjects`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/subjects/GET/subjects)
Scope: `limits:read`.
Lists every subject your checks have named in this environment, and every one you named, most recently checked first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const subjects = await limitry.subjects.list();
console.log(subjects);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
subjects = limitry.subjects.list()
print(subjects)
```
* CLI
```bash
limitry subjects list
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/subjects" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"subject": {
"kind": "user",
"id": "user_123"
},
"name": "Sara Khan",
"labels": {
"plan": "pro"
},
"lastCheckedAt": "2026-11-21T14:00:00.000Z"
}
],
"nextCursor": null
}
```
| Field | Description |
| ---------------------- | --------------------------------------------------------------- |
| `limit` number, query | Items per page, 1–100 (default 25). |
| `cursor` string, query | Opaque token from a previous page's nextCursor. |
| `kind` string, query | Only subjects of this kind. |
| `label` string, query | Only subjects with this label, as `key:value`. |
| `q` string, query | Only subjects whose name or ID contains this text, in any case. |
More about this endpoint
Filter by `kind` or by one `label`, and search the name or the ID with `q`. Results come a page at a time.
# Usage API
> The usage endpoints, each in TypeScript, Python, the CLI and curl.
The usage endpoints, each in TypeScript, Python, the CLI and curl.
## Set up
[Section titled “Set up”](#set-up)
* TypeScript
```bash
npm install @limitry/sdk
export LIMITRY_API_KEY="lim_test_…"
```
* Python
```bash
pip install limitry
export LIMITRY_API_KEY="lim_test_…"
```
* CLI
```bash
npm install -g @limitry/cli
limitry login
```
* curl
```bash
export LIMITRY_API_KEY="lim_test_…"
```
To pass the key yourself, use `createClient({ apiKey: key })` in TypeScript or `Limitry(api_key=key)` in Python.
## List who is using a limit
[Section titled “List who is using a limit”](#list-who-is-using-a-limit)
`GET /v1/usage/subjects`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/usage/GET/usage/subjects)
Scope: `limits:read`.
Lists a limit’s subjects in its current window, most used first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.usage.subjects();
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.usage.subjects()
print(result)
```
* CLI
```bash
limitry usage subjects
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/usage/subjects" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"limitName": "AI budget",
"unit": "cents",
"amount": 200,
"window": "month",
"periodStart": "2026-11-01T00:00:00.000Z",
"resetsAt": "2026-12-01T00:00:00.000Z",
"range": null,
"subjects": [
{
"subject": {
"kind": "user",
"id": "user_123"
},
"used": 120,
"remaining": 80,
"refused": 2
}
]
}
```
| Field | Description |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `limitId` string, query | The limit's ID. Send this or `limitName`. |
| `limitName` string, query | The limit's name, instead of its ID. It matches an active limit in this environment, exactly or else ignoring case. |
| `period` string, query | A named range instead of `from` and `to`, in UTC: `today`, `this_week` or `last_week` (weeks start on Monday), `this_month` or `last_month`. A current one ends now. |
| `from` string, query | The start of the range, in ISO 8601. |
| `to` string, query | The end of the range, in ISO 8601. Default: now. |
| `sort` string, query | `used` lists the most used first, and `refused` the most refused first. Default: used. |
| `top` number, query | How many subjects to rank, up to 50. Default: 50. A `concurrent` limit ranks at most 25. |
More about this endpoint
Each one shows the units used, what’s left and how many checks the limit refused. The amounts are exact, but a subject first checked in the last minute may not appear yet. For a `concurrent` limit, it lists the slots each subject holds now, among the subjects checked in the last hour. Name the limit by `limitId` or `limitName`. For a past range, send `period`, such as `last_month`, or `from` and `to`. The subjects are then ranked by their use in that range, from history. Each one’s `remaining` is then null. Set `sort` to `refused` to list the most refused first. The current window is whole on every plan. A past range reaches no further back than your plan’s history.
## Get a limit’s usage over time
[Section titled “Get a limit’s usage over time”](#get-a-limits-usage-over-time)
`GET /v1/usage`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/usage/GET/usage)
Scope: `limits:read`.
Returns one limit’s usage over time: the units used, and the checks allowed and refused, with the range’s `total` beside the buckets.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.usage.query();
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.usage.query()
print(result)
```
* CLI
```bash
limitry usage query
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/usage" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"limitName": "AI budget",
"unit": "cents",
"amount": 200,
"window": "month",
"granularity": "day",
"from": "2026-10-01T00:00:00.000Z",
"to": "2026-11-01T00:00:00.000Z",
"total": {
"used": 12480,
"allowed": 2396,
"refused": 214
},
"points": [
{
"start": "2026-10-05T00:00:00.000Z",
"used": 1250,
"allowed": 248,
"refused": 3
}
]
}
```
| Field | Description |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `limitId` string, query | The limit's ID. Send this or `limitName`. |
| `limitName` string, query | The limit's name, instead of its ID. It matches an active limit in this environment, exactly or else ignoring case. |
| `subject` string, query | One subject, as `kind:id`, to see its usage instead of every subject's. |
| `period` string, query | A named range instead of `from` and `to`, in UTC: `today`, `this_week` or `last_week` (weeks start on Monday), `this_month` or `last_month`. A current one ends now. |
| `from` string, query | The start of the range, in ISO 8601. Default: 30 days before `to`. |
| `to` string, query | The end of the range, in ISO 8601. Default: now. |
| `granularity` string, query | Whether each bucket is an `hour` or a `day`, in UTC. Default: day. |
More about this endpoint
It covers every subject, or one subject named in `subject` as `kind:id`. Name the limit by `limitId` or `limitName`. Choose the range with `period` (such as `last_month`) or `from` and `to`. Usage comes in hourly or daily buckets in UTC, and the response includes every bucket in the range. It can be up to about a minute behind live checks. By default, it covers the last 30 days, by day. A request returns at most 2,000 buckets. Usage older than your plan’s history isn’t returned.
## Get every limit’s usage at once
[Section titled “Get every limit’s usage at once”](#get-every-limits-usage-at-once)
`GET /v1/usage/overview`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/usage/GET/usage/overview)
Scope: `limits:read`.
Returns every active limit’s usage in one answer, for a question that names no limit.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.usage.overview();
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.usage.overview()
print(result)
```
* CLI
```bash
limitry usage overview
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/usage/overview" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"range": {
"from": "2026-10-01T00:00:00.000Z",
"to": "2026-11-01T00:00:00.000Z"
},
"limits": [
{
"limitId": "lmt_6f1c2a9e-4b7d-4e3a-9c5f-8d2b1a0e7c34",
"limitName": "AI budget",
"unit": "cents",
"amount": 200,
"window": "month",
"periodStart": "2026-10-01T00:00:00.000Z",
"resetsAt": null,
"total": {
"used": 12480,
"allowed": 2396,
"refused": 214
},
"subjects": [
{
"subject": {
"kind": "user",
"id": "user_123"
},
"used": 200,
"remaining": null,
"refused": 6
}
],
"credits": {
"added": 500,
"takenBack": 0,
"latest": [
{
"subject": {
"kind": "user",
"id": "user_123"
},
"amount": 500,
"note": "Credit pack",
"createdAt": "2026-11-03T01:07:05.959Z"
}
]
}
}
]
}
```
| Field | Description |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `period` string, query | A named range instead of `from` and `to`, in UTC: `today`, `this_week` or `last_week` (weeks start on Monday), `this_month` or `last_month`. A current one ends now. |
| `from` string, query | The start of the range, in ISO 8601. |
| `to` string, query | The end of the range, in ISO 8601. Default: now. |
| `sort` string, query | `used` lists each limit's most used subjects first, and `refused` only its refused subjects, the most refused first. Default: used. |
| `top` number, query | How many subjects to list for each limit, up to 20. Default: 5. |
More about this endpoint
Each limit comes with its name, unit, amount and window, its `total` (units used, checks allowed and refused) and its top subjects. By default, it covers each limit’s current window, with exact amounts. For a past range, send `period`, such as `last_month`, or `from` and `to`. The totals and subjects then come from history, and each subject’s `remaining` is null. Set `sort` to `refused` to list only the subjects each limit refused, the most refused first. A balance lists the credits added to it, and a limit that resets lists its top-ups. The current window is whole on every plan. A past range reaches no further back than your plan’s history.
# Webhooks API
> The webhooks endpoints, each in TypeScript, Python, the CLI and curl.
The webhooks endpoints, each in TypeScript, Python, the CLI and curl.
## Set up
[Section titled “Set up”](#set-up)
* TypeScript
```bash
npm install @limitry/sdk
export LIMITRY_API_KEY="lim_test_…"
```
* Python
```bash
pip install limitry
export LIMITRY_API_KEY="lim_test_…"
```
* CLI
```bash
npm install -g @limitry/cli
limitry login
```
* curl
```bash
export LIMITRY_API_KEY="lim_test_…"
```
To pass the key yourself, use `createClient({ apiKey: key })` in TypeScript or `Limitry(api_key=key)` in Python.
## List webhook endpoints
[Section titled “List webhook endpoints”](#list-webhook-endpoints)
`GET /v1/workspace/webhook-endpoints`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/webhooks/GET/workspace/webhook-endpoints)
Scope: `workspace.webhooks:read`.
Lists the workspace’s outgoing webhook endpoints, newest first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const webhookEndpoints = await limitry.workspace.webhookEndpoints.list();
console.log(webhookEndpoints);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
webhook_endpoints = limitry.workspace.webhook_endpoints.list()
print(webhook_endpoints)
```
* CLI
```bash
limitry workspace webhook-endpoints list
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/webhook-endpoints" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"id": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
"url": "https://example.com/hooks",
"description": "Order sync",
"enabled": true,
"eventTypes": [
"workspace.member.joined"
],
"environment": "live",
"consecutiveFailures": 0,
"lastHttpStatus": 200,
"lastAttemptAt": "2026-08-19T12:05:00.000Z",
"createdAt": "2026-08-19T12:00:00.000Z",
"secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
}
],
"nextCursor": null
}
```
More about this endpoint
The list leaves out their signing secrets. A workspace has at most 10 endpoints, so the list is a single page. Its `nextCursor` is null. With a personal access token, the workspace’s owners and admins can call this, and members on the test side. A workspace API key with this scope can.
## Add a webhook endpoint
[Section titled “Add a webhook endpoint”](#add-a-webhook-endpoint)
`POST /v1/workspace/webhook-endpoints`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/webhooks/POST/workspace/webhook-endpoints)
Scope: `workspace.webhooks:write`.
Registers an HTTPS URL to receive the workspace’s events.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const webhookEndpoint = await limitry.workspace.webhookEndpoints.create({
url: "https://example.com/hooks",
eventTypes: [
"workspace.member.joined",
],
});
console.log(webhookEndpoint);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
webhook_endpoint = limitry.workspace.webhook_endpoints.create(
url="https://example.com/hooks",
event_types=["workspace.member.joined"],
)
print(webhook_endpoint)
```
* CLI
```bash
limitry workspace webhook-endpoints create \
--url https://example.com/hooks \
--event-type workspace.member.joined
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/workspace/webhook-endpoints" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/hooks","eventTypes":["workspace.member.joined"]}'
```
**Returns:**
```json
{
"id": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
"url": "https://example.com/hooks",
"description": "Order sync",
"enabled": true,
"eventTypes": [
"workspace.member.joined"
],
"environment": "live",
"consecutiveFailures": 0,
"lastHttpStatus": 200,
"lastAttemptAt": "2026-08-19T12:05:00.000Z",
"createdAt": "2026-08-19T12:00:00.000Z",
"secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
}
```
| Field | Description |
| ---------------------- | ---------------------------------------------------------------------------- |
| `url` string, required | The HTTPS URL that receives the events. |
| `description` string | A note for people managing the endpoint. |
| `eventTypes` array | Send only these event types, from event-types. Leave it out for every event. |
More about this endpoint
Deliveries use the same signature format as Svix. The response is the new endpoint with its signing secret (`whsec_…`) in `secret`. You see it only once, so store it to verify deliveries. The API refuses private hosts and hosts without HTTPS. A workspace can have at most 10 endpoints. With a personal access token, the workspace’s owners and admins can call this, and members on the test side. A workspace API key with this scope can.
## Get a webhook endpoint
[Section titled “Get a webhook endpoint”](#get-a-webhook-endpoint)
`GET /v1/workspace/webhook-endpoints/{endpointId}`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/webhooks/GET/workspace/webhook-endpoints/{endpointId})
Scope: `workspace.webhooks:read`.
Returns one endpoint without its signing secret.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const webhookEndpoint = await limitry.workspace.webhookEndpoints.get("we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f");
console.log(webhookEndpoint);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
webhook_endpoint = limitry.workspace.webhook_endpoints.get(
"we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
)
print(webhook_endpoint)
```
* CLI
```bash
limitry workspace webhook-endpoints get \
we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/webhook-endpoints/we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"id": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
"url": "https://example.com/hooks",
"description": "Order sync",
"enabled": true,
"eventTypes": [
"workspace.member.joined"
],
"environment": "live",
"consecutiveFailures": 0,
"lastHttpStatus": 200,
"lastAttemptAt": "2026-08-19T12:05:00.000Z",
"createdAt": "2026-08-19T12:00:00.000Z",
"secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
}
```
| Field | Description |
| ----------------------------------- | ------------------ |
| `endpointId` string, path, required | The endpoint's ID. |
More about this endpoint
It shows whether the endpoint is on, its consecutive failures and its last delivery status. With a personal access token, the workspace’s owners and admins can call this, and members on the test side. A workspace API key with this scope can.
## Update a webhook endpoint
[Section titled “Update a webhook endpoint”](#update-a-webhook-endpoint)
`PATCH /v1/workspace/webhook-endpoints/{endpointId}`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/webhooks/PATCH/workspace/webhook-endpoints/{endpointId})
Scope: `workspace.webhooks:write`.
Changes an endpoint’s URL, description or event types in place.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const webhookEndpoint = await limitry.workspace.webhookEndpoints.update("we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f", {
url: "https://example.com/hooks",
eventTypes: [
"workspace.member.joined",
],
});
console.log(webhookEndpoint);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
webhook_endpoint = limitry.workspace.webhook_endpoints.update(
"we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
url="https://example.com/hooks",
event_types=["workspace.member.joined"],
)
print(webhook_endpoint)
```
* CLI
```bash
limitry workspace webhook-endpoints update \
we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f \
--url https://example.com/hooks \
--event-type workspace.member.joined
```
* curl
```bash
curl -X PATCH "https://api.limitry.com/v1/workspace/webhook-endpoints/we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f" \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/hooks","eventTypes":["workspace.member.joined"]}'
```
**Returns:**
```json
{
"id": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
"url": "https://example.com/hooks",
"description": "Order sync",
"enabled": true,
"eventTypes": [
"workspace.member.joined"
],
"environment": "live",
"consecutiveFailures": 0,
"lastHttpStatus": 200,
"lastAttemptAt": "2026-08-19T12:05:00.000Z",
"createdAt": "2026-08-19T12:00:00.000Z",
"secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
}
```
| Field | Description |
| ----------------------------------- | --------------------------------------------------------------------------------------- |
| `endpointId` string, path, required | The endpoint's ID. |
| `url` string | The HTTPS URL that receives the events. |
| `description` string | A note for people managing the endpoint. Null clears it. |
| `eventTypes` array | Send only these event types, from event-types. Null or an empty list means every event. |
More about this endpoint
Only the fields you send change. The endpoint keeps its signing secret, so receivers keep verifying deliveries. A new URL must pass the same checks as on create. It must use HTTPS and can’t be a private host. With a personal access token, the workspace’s owners and admins can call this, and members on the test side. A workspace API key with this scope can.
## Remove a webhook endpoint
[Section titled “Remove a webhook endpoint”](#remove-a-webhook-endpoint)
`DELETE /v1/workspace/webhook-endpoints/{endpointId}`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/webhooks/DELETE/workspace/webhook-endpoints/{endpointId})
Scope: `workspace.webhooks:write`.
Deletes the endpoint and its signing secret.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
await limitry.workspace.webhookEndpoints.delete("we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f");
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limitry.workspace.webhook_endpoints.delete(
"we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
)
```
* CLI
```bash
limitry workspace webhook-endpoints delete \
we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f \
--yes
```
* curl
```bash
curl -X DELETE "https://api.limitry.com/v1/workspace/webhook-endpoints/we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns** nothing (`204`).
| Field | Description |
| ----------------------------------- | ------------------ |
| `endpointId` string, path, required | The endpoint's ID. |
More about this endpoint
All deliveries to the endpoint stop. Its delivery history goes with it. With a personal access token, the workspace’s owners and admins can call this, and members on the test side. A workspace API key with this scope can.
## Re-enable a webhook endpoint
[Section titled “Re-enable a webhook endpoint”](#re-enable-a-webhook-endpoint)
`POST /v1/workspace/webhook-endpoints/{endpointId}/enable`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/webhooks/POST/workspace/webhook-endpoints/{endpointId}/enable)
Scope: `workspace.webhooks:write`.
Resumes deliveries to an endpoint that stopped after repeated failures.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const webhookEndpoint = await limitry.workspace.webhookEndpoints.enable("we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f");
console.log(webhookEndpoint);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
webhook_endpoint = limitry.workspace.webhook_endpoints.enable(
"we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
)
print(webhook_endpoint)
```
* CLI
```bash
limitry workspace webhook-endpoints enable \
we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/workspace/webhook-endpoints/we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f/enable" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"id": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
"url": "https://example.com/hooks",
"description": "Order sync",
"enabled": true,
"eventTypes": [
"workspace.member.joined"
],
"environment": "live",
"consecutiveFailures": 0,
"lastHttpStatus": 200,
"lastAttemptAt": "2026-08-19T12:05:00.000Z",
"createdAt": "2026-08-19T12:00:00.000Z",
"secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
}
```
| Field | Description |
| ----------------------------------- | ------------------ |
| `endpointId` string, path, required | The endpoint's ID. |
More about this endpoint
The endpoint keeps its signing secret. Its failure count resets. With a personal access token, the workspace’s owners and admins can call this, and members on the test side. A workspace API key with this scope can.
## Send a test event
[Section titled “Send a test event”](#send-a-test-event)
`POST /v1/workspace/webhook-endpoints/{endpointId}/test`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/webhooks/POST/workspace/webhook-endpoints/{endpointId}/test)
Scope: `workspace.webhooks:write`.
Sends a `ping` event to the endpoint, signed like every delivery.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const result = await limitry.workspace.webhookEndpoints.test("we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f");
console.log(result);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
result = limitry.workspace.webhook_endpoints.test(
"we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
)
print(result)
```
* CLI
```bash
limitry workspace webhook-endpoints test \
we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/workspace/webhook-endpoints/we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f/test" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"deliveryId": "del_8a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d",
"queued": false,
"ok": true,
"httpStatus": 200
}
```
| Field | Description |
| ----------------------------------- | ------------------ |
| `endpointId` string, path, required | The endpoint's ID. |
More about this endpoint
Use it to check that an integration verifies and accepts deliveries. It answers 200 when we attempted the delivery right away, with the endpoint’s answer, and 202 when it went to the queue. With a personal access token, the workspace’s owners and admins can call this, and members on the test side. A workspace API key with this scope can.
## List an endpoint’s deliveries
[Section titled “List an endpoint’s deliveries”](#list-an-endpoints-deliveries)
`GET /v1/workspace/webhook-endpoints/{endpointId}/deliveries`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/webhooks/GET/workspace/webhook-endpoints/{endpointId}/deliveries)
Scope: `workspace.webhooks:read`.
Lists one endpoint’s delivery history, newest first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const webhookDeliveries = await limitry.workspace.webhookDeliveries.list("we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f");
console.log(webhookDeliveries);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
webhook_deliveries = limitry.workspace.webhook_deliveries.list(
"we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
)
print(webhook_deliveries)
```
* CLI
```bash
limitry workspace webhook-deliveries list \
we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/webhook-endpoints/we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f/deliveries" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"id": "del_8a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d",
"eventId": "evt_51c2d3e4-f5a6-4b7c-8d9e-0f1a2b3c4d5e",
"eventType": "workspace.member.joined",
"status": "delivered",
"attempts": 1,
"lastHttpStatus": 200,
"lastAttemptAt": "2026-08-19T12:05:00.000Z",
"createdAt": "2026-08-19T12:05:00.000Z"
}
],
"nextCursor": null
}
```
| Field | Description |
| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `endpointId` string, path, required | The endpoint's ID. |
| `limit` number, query | Items per page, 1–100 (default 25). |
| `cursor` string, query | Opaque token from a previous page's nextCursor. |
| `before` string, query | Start from this moment: items older than it, newest first. Ignored with `cursor`, which already says where to go on. |
| `status` string, query | Only deliveries with this status. |
More about this endpoint
Each entry shows the delivery’s state, its attempts and the last HTTP status code. Payloads aren’t included. We keep the history for 30 days. Paginate with the opaque `nextCursor`. `before` starts from a moment, and `status` keeps one kind of delivery. With a personal access token, the workspace’s owners and admins can call this, and members on the test side. A workspace API key with this scope can.
## Redeliver an event
[Section titled “Redeliver an event”](#redeliver-an-event)
`POST /v1/workspace/webhook-endpoints/{endpointId}/deliveries/{deliveryId}/redeliver`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/webhooks/POST/workspace/webhook-endpoints/{endpointId}/deliveries/{deliveryId}/redeliver)
Scope: `workspace.webhooks:write`.
Sends a recorded delivery’s event again, as a new delivery.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const delivery = await limitry.workspace.webhookDeliveries.redeliver("we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f", "del_8a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d");
console.log(delivery);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
delivery = limitry.workspace.webhook_deliveries.redeliver(
"we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
"del_8a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d",
)
print(delivery)
```
* CLI
```bash
limitry workspace webhook-deliveries redeliver \
we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f \
del_8a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d
```
* curl
```bash
curl -X POST "https://api.limitry.com/v1/workspace/webhook-endpoints/we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f/deliveries/del_8a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d/redeliver" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"deliveryId": "del_8a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d",
"queued": false,
"ok": true,
"httpStatus": 200
}
```
| Field | Description |
| ----------------------------------- | ------------------ |
| `endpointId` string, path, required | The endpoint's ID. |
| `deliveryId` string, path, required | The delivery's ID. |
More about this endpoint
The new delivery gets its own history entry. The event id stays the same, so receivers can deduplicate. Redelivery only works on an enabled endpoint. It answers 200 when we attempted the delivery right away, with the endpoint’s answer, and 202 when it went to the queue. With a personal access token, the workspace’s owners and admins can call this, and members on the test side. A workspace API key with this scope can.
## List event types
[Section titled “List event types”](#list-event-types)
`GET /v1/workspace/event-types`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/webhooks/GET/workspace/event-types)
Scope: `workspace.webhooks:read`.
Lists every workspace event a webhook endpoint can subscribe to, and what each one means.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const eventTypes = await limitry.workspace.eventTypes.list();
console.log(eventTypes);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
event_types = limitry.workspace.event_types.list()
print(event_types)
```
* CLI
```bash
limitry workspace event-types list
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/event-types" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"type": "workspace.member.joined",
"description": "A person joined the workspace, by accepting an invitation or being added. `data.userId` says who."
}
],
"nextCursor": null
}
```
More about this endpoint
Pass some as `eventTypes` when you add an endpoint. An endpoint without a list receives every event. Every type fits on one page, so `nextCursor` is null.
# Workspace API
> The workspace endpoints, each in TypeScript, Python, the CLI and curl.
The workspace endpoints, each in TypeScript, Python, the CLI and curl.
## Set up
[Section titled “Set up”](#set-up)
* TypeScript
```bash
npm install @limitry/sdk
export LIMITRY_API_KEY="lim_test_…"
```
* Python
```bash
pip install limitry
export LIMITRY_API_KEY="lim_test_…"
```
* CLI
```bash
npm install -g @limitry/cli
limitry login
```
* curl
```bash
export LIMITRY_API_KEY="lim_test_…"
```
To pass the key yourself, use `createClient({ apiKey: key })` in TypeScript or `Limitry(api_key=key)` in Python.
## Get the current workspace
[Section titled “Get the current workspace”](#get-the-current-workspace)
`GET /v1/workspace`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/workspace/GET/workspace)
Scope: `workspace:read`.
Returns the workspace the credential acts in.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const workspace = await limitry.workspace.get();
console.log(workspace);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
workspace = limitry.workspace.get()
print(workspace)
```
* CLI
```bash
limitry workspace get
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"id": "ws_9418b705-3720-48ca-b2bf-f726d1456684",
"name": "Acme Inc.",
"slug": "acme",
"createdAt": "2026-08-19T12:00:00.000Z"
}
```
More about this endpoint
For an API key, that is the key’s own workspace. For a personal access token, it is the one named in `X-Workspace`. Use it as a smoke test for an integration (“who am I?”).
## List workspace members
[Section titled “List workspace members”](#list-workspace-members)
`GET /v1/workspace/members`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/workspace/GET/workspace/members)
Scope: `workspace.members:read`.
Lists the workspace’s members and their roles, newest first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const members = await limitry.workspace.members.list();
console.log(members);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
members = limitry.workspace.members.list()
print(members)
```
* CLI
```bash
limitry workspace members list
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/members" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"id": "mem_5070e1f6-5adf-4170-92bd-20cac815d34c",
"userId": "usr_4f8a2c1e-7b3d-4e9f-a6c5-2d1b0e9f8a7c",
"name": "Ana Lopez",
"email": "ana@example.com",
"role": "member",
"joinedAt": "2026-08-19T12:00:00.000Z"
}
],
"nextCursor": null
}
```
| Field | Description |
| ---------------------- | ----------------------------------------------- |
| `limit` number, query | Items per page, 1–100 (default 25). |
| `cursor` string, query | Opaque token from a previous page's nextCursor. |
More about this endpoint
Paginate with the opaque `nextCursor`. `limit` takes 1 to 100 and defaults to 25. Invite members, remove them and give them roles in the app.
## List pending invitations
[Section titled “List pending invitations”](#list-pending-invitations)
`GET /v1/workspace/invitations`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/workspace/GET/workspace/invitations)
Scope: `workspace.members:read`.
Lists the invitations that are not yet accepted, declined or expired, newest first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const invitations = await limitry.workspace.invitations.list();
console.log(invitations);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
invitations = limitry.workspace.invitations.list()
print(invitations)
```
* CLI
```bash
limitry workspace invitations list
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/invitations" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"id": "inv_c1d9e0a4-2b7f-4e3a-9f6d-8a5b4c3e2f10",
"email": "sam@example.com",
"role": "member",
"teamIds": [
"team_5cfbfbdc-bd74-4b1b-aacf-cc18a0ab960e"
],
"expiresAt": "2026-08-21T12:00:00.000Z",
"createdAt": "2026-08-19T12:00:00.000Z"
}
],
"nextCursor": null
}
```
| Field | Description |
| ---------------------- | ----------------------------------------------- |
| `limit` number, query | Items per page, 1–100 (default 25). |
| `cursor` string, query | Opaque token from a previous page's nextCursor. |
More about this endpoint
With a personal credential, only owners and admins can call this, as in the app. A workspace API key always can. Paginate with the opaque `nextCursor`.
## Get your plan’s usage this period
[Section titled “Get your plan’s usage this period”](#get-your-plans-usage-this-period)
`GET /v1/workspace/plan-usage`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/workspace/GET/workspace/plan-usage)
Scope: `workspace:read`.
Returns what the workspace used this period, with one entry for each thing its plan counts.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const planUsage = await limitry.workspace.planUsage.get();
console.log(planUsage);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
plan_usage = limitry.workspace.plan_usage.get()
print(plan_usage)
```
* CLI
```bash
limitry workspace plan-usage get
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/plan-usage" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"periodStart": "2026-10-17T14:30:00.000Z",
"periodEnd": "2026-11-17T14:30:00.000Z",
"state": "grace",
"counts": [
{
"id": "webhook_deliveries",
"label": "Webhook deliveries",
"unit": "per month",
"description": "Webhook deliveries this period",
"used": 10400,
"limit": 10000,
"stopsAt": 11000,
"state": "grace",
"overage": {
"label": "Extra checks",
"rate": "$40 per million checks",
"extraUnits": 700000,
"costCents": 2800,
"capCents": 3900,
"defaultCapCents": 3900,
"capIsDefault": true
}
}
],
"notices": []
}
```
More about this endpoint
Each entry has the plan’s limit, or null when there is no limit. Each entry also says where it stands and where we start refusing new use. A period is one month from the workspace’s billing date. That date comes from its subscription or, without one, from the day you created the workspace. On an annual plan, the counts still reset every month from the subscription’s start.
## List teams
[Section titled “List teams”](#list-teams)
`GET /v1/workspace/teams`[ Try it in the API playground (opens in a new tab)](https://api.limitry.com/v1/docs#tag/workspace/GET/workspace/teams)
Scope: `workspace.teams:read`.
Lists the workspace’s teams and their members’ user ids, newest first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const teams = await limitry.workspace.teams.list();
console.log(teams);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
teams = limitry.workspace.teams.list()
print(teams)
```
* CLI
```bash
limitry workspace teams list
```
* curl
```bash
curl -X GET "https://api.limitry.com/v1/workspace/teams" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
**Returns:**
```json
{
"items": [
{
"id": "team_5cfbfbdc-bd74-4b1b-aacf-cc18a0ab960e",
"name": "Engineering",
"isDefault": false,
"memberIds": [
"usr_4f8a2c1e-7b3d-4e9f-a6c5-2d1b0e9f8a7c"
],
"createdAt": "2026-08-19T12:00:00.000Z"
}
],
"nextCursor": null
}
```
| Field | Description |
| ---------------------- | ----------------------------------------------- |
| `limit` number, query | Items per page, 1–100 (default 25). |
| `cursor` string, query | Opaque token from a previous page's nextCursor. |
More about this endpoint
Paginate with the opaque `nextCursor`. `limit` takes 1 to 100 and defaults to 25. Create teams and add members to them in the app.
# Reservations
> Reserve what work will probably cost, then commit the actual amount when it finishes.
Some work only knows its cost afterwards, like an AI reply your product pays for by the token. A reservation sets aside what the work will probably cost while it runs, then you commit the actual amount. The examples on this page reserve 5 cents for a user’s `ai-call` against a budget of 200 cents a month, and commit what the call cost.
## In one step
[Section titled “In one step”](#in-one-step)
The SDKs’ `reserve` reserves `cost` and runs your code. It then commits the cost your code reports. If your code fails, it releases the reservation instead.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
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);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
with limitry.reserve(
subject={"kind": "user", "id": "user_123"}, action="ai-call", cost=5
) as reservation:
response = call_model(prompt)
reservation.cost = price_cents(response.usage) # your prices, in cents
print(response.text)
```
The steps below are what `reserve` does, for when you reserve, commit and release yourself.
## 1. Reserve
[Section titled “1. Reserve”](#1-reserve)
Make a check with `mode: "reserve"` and what the work will probably cost as the `cost`:
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const decision = await limitry.checks.create({
subject: { kind: "user", id: "user_123" },
action: "ai-call",
cost: 5,
mode: "reserve",
});
console.log(decision);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
decision = limitry.checks.create(
subject={"kind": "user", "id": "user_123"},
action="ai-call",
cost=5,
mode="reserve",
)
print(decision)
```
* CLI
```bash
limitry checks create --subject '{"kind":"user","id":"user_123"}' \
--action ai-call --cost 5 --mode reserve
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/checks \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "subject": { "kind": "user", "id": "user_123" }, "action": "ai-call",
"cost": 5, "mode": "reserve" }'
```
Limitry decides it like any other check. On a yes, Limitry reserves the cost, and other checks for that subject see it as used. The response includes the reservation.
```json
{
"allowed": true,
"limits": [{ "limitId": "lmt_…", "remaining": 195, "…": "…" }],
"reservation": { "id": "rsv_…", "expiresAt": "2026-10-04T12:05:00Z" }
}
```
On a no, Limitry reserves nothing, and `reservation` is `null`.
## 2. Commit or release
[Section titled “2. Commit or release”](#2-commit-or-release)
When the work finishes, commit what it actually used. Here it used 3 cents.
* TypeScript
```ts
await limitry.reservations.commit("rsv_…", { cost: 3 });
```
* Python
```python
limitry.reservations.commit("rsv_…", cost=3)
```
* CLI
```bash
limitry reservations commit rsv_… --cost 3
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/reservations/rsv_…/commit \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" -d '{ "cost": 3 }'
```
If the work used less than it reserved, Limitry gives the rest back at once. The user’s budget shows 197 cents left, not 195. If the work used more, Limitry records the actual cost in full, even past the limit, because the work did happen. The next check then sees the true total.
If the work didn’t happen, release the reservation instead. `reservations.release(id)` gives all of it back. On the CLI, that’s `limitry reservations release `.
A commit or release is safe to retry, and the same one gets the same response. Committing again with a different cost gets a `400`. Releasing a committed reservation, or committing a released one, gets a `409` with the code [`conflict`](/docs/errors/#conflict).
## Expiry
[Section titled “Expiry”](#expiry)
A reservation lasts the `ttlSeconds` you set on the check. The default is 300, and the most is 3,600. A reservation that nobody commits or releases gives itself back when it expires, so a crashed worker never keeps a subject blocked. If the work did finish after all, a late commit within 24 hours still charges the full cost it reports.
For longer work, extend the reservation as a heartbeat. Call `reservations.extend(id, { ttlSeconds: 600 })` to push its expiry to 600 seconds from now. Inside `reserve`, both SDKs give you `reservation.extend()` for this. You can only extend a reservation that’s still held. Extending one that’s committed, released or expired gets a `409` with the code `conflict`. A reservation can also take a slot of a [concurrent limit](/docs/rolling-and-concurrency/).
## Good to know
[Section titled “Good to know”](#good-to-know)
* A subject can have at most 1,000 open reservations. Beyond that, the check gets a no with `reason.code: "too_many_reservations"`.
* A reservation counts as one check on your plan when you commit it. A reservation that you release, or that expires, doesn’t count.
* `reservations.get(id)` shows where a reservation stands: held, committed, released or expired. It also shows what it reserved and what it finally used. Reading it changes nothing. On the CLI, that’s `limitry reservations get `.
* Reservations need the same `checks:write` scope as checks.
# When limits reset
> Reset a limit on the calendar, on each subject's billing date, or a set time after first use, over any period length, or reset it now.
A limit’s allowance resets at the end of each period. Three settings decide when:
| Setting | Decides | Example |
| -------- | ------------------------------------------------------------ | ----------------------------------------- |
| `window` | The unit: `minute`, `hour`, `day`, `week`, `month` or `year` | `month` |
| `every` | How many units a period lasts (default 1) | `every: 3` with `month` is a quarter |
| `start` | Where each period begins | `calendar`, `billing_date` or `first_use` |
How often your customers pay doesn’t matter here. An annual plan can still reset its allowance every month. You can’t change any of the three settings once a limit exists. To change one, create a new limit and archive the old one. See [What can change](/docs/limits/#what-can-change).
The examples on this page give each team credits that its members spend on reports, at 25 credits a report. These credits come back each period. A prepaid balance is different, because it never resets. See [Pools, balances and budgets](/docs/pools-and-budgets/).
## On the calendar
[Section titled “On the calendar”](#on-the-calendar)
`start: "calendar"` is the default. Periods begin on UTC boundaries, the same for every subject.
* `day` at midnight, `week` on Monday, `month` on the 1st, `year` on 1 January.
* `every: 3` with `month` resets on 1 January, April, July and October.
- TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const limit = await limitry.limits.create({
name: "Quarterly credits",
subject: { kind: "team" },
action: "report",
amount: 15000,
unit: "credits",
window: "month",
every: 3,
});
console.log(limit.id);
```
- Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limit = limitry.limits.create(
name="Quarterly credits",
subject={"kind": "team"},
action="report",
amount=15000,
unit="credits",
window="month",
every=3,
)
print(limit.id)
```
- CLI
```bash
limitry limits create --name "Quarterly credits" --subject '{"kind":"team"}' \
--action report --amount 15000 --unit credits --window month --every 3
```
- curl
```bash
curl -X POST https://api.limitry.com/v1/limits \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"Quarterly credits","subject":{"kind":"team"},"action":"report",
"amount":15000,"unit":"credits","window":"month","every":3}'
```
## On each subject’s billing date
[Section titled “On each subject’s billing date”](#on-each-subjects-billing-date)
`start: "billing_date"` resets each subject on its own date, its **billing date**. A team that subscribed on 17 March resets on the 17th of every month. Set a subject’s billing date when its subscription starts, usually from your billing webhook. Send it as `billingAnchorAt` to `PATCH /v1/subjects/{subjectKind}/{subjectId}`.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const limit = await limitry.limits.create({
name: "Monthly credits",
subject: { kind: "team" },
action: "report",
amount: 5000,
unit: "credits",
window: "month",
start: "billing_date",
});
console.log(limit.id);
// When the team's subscription starts (Stripe's start_date is in seconds)
const subject = await limitry.subjects.update("team", "team_42", {
billingAnchorAt: new Date(1773757800 * 1000).toISOString(),
});
console.log(subject);
```
* Python
```python
from datetime import datetime, timezone
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limit = limitry.limits.create(
name="Monthly credits",
subject={"kind": "team"},
action="report",
amount=5000,
unit="credits",
window="month",
start="billing_date",
)
print(limit.id)
# When the team's subscription starts (Stripe's start_date is in seconds)
subject = limitry.subjects.update(
"team",
"team_42",
billing_anchor_at=datetime.fromtimestamp(1773757800, tz=timezone.utc).isoformat(),
)
print(subject)
```
- **No billing date yet:** the day of the subject’s first counted check becomes its billing date, so `billing_date` limits work before you set one. A reservation counts as a check here, even one you release later.
- **Annual plans:** an annual subscription that started on 17 March still resets a monthly allowance on the 17th of every month. Set the billing date once, when the subscription starts.
- **Month ends:** a billing date on the 31st resets on the last day of shorter months, then on the 31st again. A billing date on 29 February resets on 28 February in other years.
- **A new billing date** never hands out a fresh allowance. The current period runs on until the new date, and what the subject used in it still counts. From then on, periods follow the new date. To start a fresh period now, for an upgrade or a re-subscribe, set the new date and then [reset now](#reset-now).
`limitry subjects get team team_42` shows a subject’s `billingAnchorAt`, the moment its periods start from. In the SDKs, it’s `limitry.subjects.get("team", "team_42")`.
## From first use
[Section titled “From first use”](#from-first-use)
`start: "first_use"` starts a period at a subject’s first check and resets it a period later. Nothing runs while the subject is idle. This is how AI chat products allow “45 messages per 5 hours, starting from your first message”.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const limit = await limitry.limits.create({
name: "Messages per 5 hours",
subject: { kind: "user" },
action: "chat",
amount: 45,
window: "hour",
every: 5,
start: "first_use",
});
console.log(limit.id);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limit = limitry.limits.create(
name="Messages per 5 hours",
subject={"kind": "user"},
action="chat",
amount=45,
window="hour",
every=5,
start="first_use",
)
print(limit.id)
```
Before a subject’s first check, its `resetsAt` is `null`. The check that starts the period already tells you when that period ends. A reservation starts the period too, even one you release later.
## Reset now
[Section titled “Reset now”](#reset-now)
Reset a subject’s allowance at once, for goodwill, a promotion or support. Name one limit, or send `{}` to reset every limit on the subject.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const reset = await limitry.subjects.reset(
"team",
"team_42",
{ limitId: "lmt_3f0c…" },
{ idempotencyKey: "ticket-8812" },
);
console.log(reset);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
reset = limitry.subjects.reset(
"team",
"team_42",
limit_id="lmt_3f0c…",
idempotency_key="ticket-8812",
)
print(reset)
```
- The schedule doesn’t move, and the next reset is still the usual one.
- A balance (`total`) goes back to its amount. Credits added before the reset no longer count.
- A reset leaves `concurrent` limits alone. Their slots belong to work that’s still running.
- With an idempotency key, a repeated request resets once.
In the app, the owner and admins can click **Reset** next to a subject on the [Usage](/docs/usage/) page, and members can in test.
## Stacking limits
[Section titled “Stacking limits”](#stacking-limits)
Every limit that matches a check applies, and each resets on its own schedule. A $2 AI budget a month with a daily cap against abuse is two limits.
| Limit | `amount` (cents) | `window` | `start` |
| --------- | ---------------- | -------- | -------------- |
| AI budget | 200 | `month` | `billing_date` |
| Daily cap | 50 | `day` | `calendar` |
Once a user has spent 50 cents in a day, Limitry says no until the next day. That’s true even with budget left for the month. See [Offer a free plan with a daily cap](/docs/guides/daily-cap/).
## What responses show
[Section titled “What responses show”](#what-responses-show)
A check’s `limits[].resetsAt` and [`subjects.standing`](/docs/guides/show-usage/) say when that subject’s own period ends. For `billing_date` and `first_use` limits, that’s different for every subject. The [Usage](/docs/usage/) page’s **Right now** table shows each subject’s use and refusals in its own current period, resets included.
# Rolling windows and concurrency
> Limits like "1,000 in any hour" and "at most 3 at once", which fixed windows can't express.
## Rolling windows
[Section titled “Rolling windows”](#rolling-windows)
By default, a `minute`, `hour` or `day` limit resets at the UTC boundary. Say each of your API’s customers may make 1,000 requests an hour with their key. A key could send 1,000 requests at 12:59 and 1,000 more at 13:01, and both bursts would get a yes. Set `rolling: true` and the limit counts the last 60 seconds, 60 minutes or 24 hours at the moment of each check instead.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const limit = await limitry.limits.create({
name: "API per hour",
subject: { kind: "apikey" },
action: "api-request",
amount: 1000,
window: "hour",
rolling: true,
});
console.log(limit.id);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limit = limitry.limits.create(
name="API per hour",
subject={"kind": "apikey"},
action="api-request",
amount=1000,
window="hour",
rolling=True,
)
print(limit.id)
```
* CLI
```bash
limitry limits create --name "API per hour" --subject '{"kind":"apikey"}' \
--action api-request --amount 1000 --window hour --rolling
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/limits \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"API per hour","subject":{"kind":"apikey"},"action":"api-request",
"amount":1000,"window":"hour","rolling":true}'
```
With `every`, a rolling limit counts the last `every` windows, such as any 5 hours. A rolling `minute` limit spans at most 60 minutes. An `hour` limit spans at most 24 hours, and a `day` limit at most 30 days. A rolling limit takes no `start`, because it always counts back from each check.
Limitry counts use in 60 slices of the window. With `every` at 1, a slice is a second for a minute, a minute for an hour, and 24 minutes for a day. The oldest slice counts in full, so a rolling limit never allows more than its amount. It may say no up to one slice early.
In a check’s response, `resetsAt` is when enough use has left the window for the subject to try again. On a no, `retryAfterSeconds` gives the same moment. Send it as `Retry-After` with your 429. The [Rate-limit your API’s customers](/docs/guides/api-rate-limits/) guide adds a second rolling limit of 60 in any minute, against bursts.
`week`, `month`, `year`, `total` and `concurrent` limits can’t be rolling. In the app, choose **In any 60 seconds**, **In any 60 minutes** or **In any 24 hours** as the window.
## Concurrency
[Section titled “Concurrency”](#concurrency)
A limit with the window `concurrent` caps work in progress, and its `amount` is how many may run at once. Say exports are heavy, and each workspace in your product may run at most 3 at the same time. Each [reservation](/docs/reservations/) takes one slot, whatever its `cost`. It gives the slot back when you commit or release it, or when it expires. The `cost` still counts against the subject’s other limits.
This limit allows at most 3 exports at once per workspace.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const limit = await limitry.limits.create({
name: "Exports at once",
subject: { kind: "workspace" },
action: "export",
amount: 3,
window: "concurrent",
});
console.log(limit.id);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
limit = limitry.limits.create(
name="Exports at once",
subject={"kind": "workspace"},
action="export",
amount=3,
window="concurrent",
)
print(limit.id)
```
* CLI
```bash
limitry limits create --name "Exports at once" --subject '{"kind":"workspace"}' \
--action export --amount 3 --window concurrent
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/limits \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"Exports at once","subject":{"kind":"workspace"},"action":"export",
"amount":3,"window":"concurrent"}'
```
Then reserve a slot while each export runs. Limitry says no to a 4th export until one of the 3 ends. `reserve` gives the slot back when the work finishes or fails.
* TypeScript
```ts
const file = await limitry.reserve(
{ subject: { kind: "workspace", id: "ws_42" }, action: "export" },
() => runExport(),
);
```
* Python
```python
with limitry.reserve(subject={"kind": "workspace", "id": "ws_42"}, action="export"):
run_export()
```
- While a slot is free, a `consume` or `preview` check against a concurrent limit gets a yes, but takes no slot.
- When work holds every slot, `retryAfterSeconds` is when the earliest reservation expires. A release can free one sooner.
- If you reserve, commit and release yourself (see [Reservations](/docs/reservations/)), release in a `finally` block. A reservation you never commit or release keeps its slot until it expires.
- When your code can’t reach Limitry and the limit’s fail mode is `open`, `reserve` still runs at most `amount` at once in your process for each subject and action. The SDK counts the reservations it has going, and remembers the amount from Limitry’s last response. Beyond that, `reserve` throws `UnavailableError`, as it would for a `closed` limit. The count is per process, so several servers together may run more until Limitry responds again. A process that hasn’t yet had a response for that subject and action doesn’t hold anything back, just as a plain `open` limit wouldn’t.
### Long-running work
[Section titled “Long-running work”](#long-running-work)
A reservation lasts `ttlSeconds`, which is 300 by default and 3,600 at most. For work that runs longer, extend it as a heartbeat.
* TypeScript
```ts
await limitry.reserve(
{ subject: { kind: "workspace", id: "ws_42" }, action: "export" },
async (reservation) => {
for (const part of parts) {
await exportPart(part);
await reservation.extend(600);
}
},
);
```
* Python
```python
with limitry.reserve(subject={"kind": "workspace", "id": "ws_42"}, action="export") as reservation:
for part in parts:
export_part(part)
reservation.extend(600)
```
* CLI
```bash
limitry reservations extend rsv_… --ttl-seconds 600
```
* curl
```bash
curl -X POST https://api.limitry.com/v1/reservations/rsv_…/extend \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" -d '{"ttlSeconds":600}'
```
If your worker dies, it stops extending, and the slot frees itself.
A limit can’t change to or from `concurrent`, because one counts use and the other counts open reservations. You can’t change a limit’s window once it exists, so create a new limit instead. See [What can change](/docs/limits/#what-can-change).
## In reports
[Section titled “In reports”](#in-reports)
Rolling limits report like any other. On the Usage page, **Right now** shows each subject’s use in the last window.
For a concurrent limit, the chart shows how much work the limit let start each day. **Right now** shows the slots each subject has reserved, for subjects checked in the last hour.
For both kinds, Limitry sends `limit.reached` at most once an hour per subject.
# Subjects, names and links
> Give subjects optional names and labels, see who your checks name, and walk from a subject to the ones it's checked with.
A subject is anyone or anything your checks name, such as a user, a team, an API key or an agent. A check names it by its kind and ID. A subject needs no setup: it exists once a check names it.
## Names and labels
[Section titled “Names and labels”](#names-and-labels)
You can give a subject a name people can read, and labels to filter by. Both are optional, and checks never need them. Names don’t have to be unique, so the app always shows the ID beside a name.
| Field | What it holds |
| -------- | ------------------------------------------------------------------------------------------ |
| `name` | Up to 200 characters, such as “Design team”. |
| `labels` | Up to 20 keys of up to 40 characters, each with a value of up to 200, such as `plan: pro`. |
Set them with `PATCH /v1/subjects/{subjectKind}/{subjectId}`, never on a check. A field you leave out stays as it is. `null` clears it. Labels you send replace the subject’s labels.
```bash
curl -X PATCH https://api.limitry.com/v1/subjects/team/team_42 \
-H "Authorization: Bearer $LIMITRY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "Design team", "labels": {"plan": "pro"}}'
```
From the CLI:
```bash
limitry subjects update team team_42 --name "Design team" --labels '{"plan": "pro"}'
```
To name many subjects at once, such as when you first connect your user list, send up to 1,000 to `POST /v1/subjects/import`. Limitry checks every item before it saves any.
## Erasing names and labels
[Section titled “Erasing names and labels”](#erasing-names-and-labels)
`DELETE /v1/subjects/{subjectKind}/{subjectId}/names` erases a subject’s name and labels. It answers `204`, with no body. Its limits, usage and billing date stay, because Limitry keeps them by its ID. Use it when one of your users asks you to delete their data.
You can leave names and labels out and send only IDs, such as `user_123`. Every limit works the same. Please don’t put email addresses or sensitive data in names or labels.
## Who
[Section titled “Who”](#who)
The **Who** page lists every subject your checks have named in the environment, and every one you named. The most recently checked come first. Filter it by kind or by a label, such as `plan:pro`, and search by name or ID. Click a subject to open its own page.
## A subject’s page
[Section titled “A subject’s page”](#a-subjects-page)
A subject’s page shows:
| Card | What it shows |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| Above and Below, or one card a kind | The subjects its checks name beside it, and what each spent within each budget this period. |
| Budgets | Every limit on it, and how much of each it has used. |
| Name and labels | Its name and labels. Owners, admins and members can change them in test. In live, only owners and admins can. |
| Recent checks | The checks of the last 3 days that named it. |
Every subject on the page links to its own page, so you can walk from a user to its team and on to the team’s account.
Limitry learns which subjects your checks name together from the checks, so there’s nothing to set up. When a check names a user and shares a team’s budget, the user’s page lists the team, and the team’s page lists the user. Each budget’s period is its own, such as the team’s month. A minute or hour budget counts by the day in UTC.
A workspace sending a new ID with almost every check could add links without end. Past 20,000 new links in a day, Limitry counts the rest as **Others**.
## From your code or the CLI
[Section titled “From your code or the CLI”](#from-your-code-or-the-cli)
| What | API | CLI |
| ------------------------------------- | ----------------------------------------------------- | -------------------------------------------- |
| List and search subjects | `GET /v1/subjects` | `limitry subjects list --q design` |
| One subject: names, budgets and links | `GET /v1/subjects/{subjectKind}/{subjectId}` | `limitry subjects get team team_42` |
| Name a subject | `PATCH /v1/subjects/{subjectKind}/{subjectId}` | `limitry subjects update team team_42 …` |
| Name many subjects | `POST /v1/subjects/import` | `limitry subjects import --data '…'` |
| Erase a subject’s name and labels | `DELETE /v1/subjects/{subjectKind}/{subjectId}/names` | `limitry subjects names delete team team_42` |
| Where a subject stands | `GET /v1/subjects/{subjectKind}/{subjectId}/standing` | `limitry subjects standing team team_42` |
| The last 3 days’ checks | `GET /v1/checks` | `limitry checks list` |
`GET /v1/subjects` filters by `kind` and by one `label` as `key:value`, and searches the name or ID with `q`. `GET /v1/checks` takes a `subject` as `kind:id`, and `refused=true` for refused checks only. Both return a page at a time (see [Pagination](/docs/pagination/)). A subject’s `links` say what it spent within each other subject’s budget this period (`within`), and what others spent within its own (`member`).
## Kinds
[Section titled “Kinds”](#kinds)
On **Settings → General**, the **Kinds** card sets how the app names each kind your checks use, such as “Cost center” and “Cost centers” for `cost-center`. Without a name, the app shows the kind as you send it, starting with a capital letter.
The card also puts the kinds in order, from the top level down. With an order, a subject’s page splits the subjects it’s checked with into **Above** and **Below**. Without one, it groups them by kind. The names and the order are labels only: checks and the API keep using the kinds themselves. Owners and admins can change them. To keep them in your repository, list them in `limitry.json` (see [limitry.json](/docs/limitry-json/#kinds)). The card is then locked, except for an override until the next sync.
Names and labels never go in `limitry.json`: a repository’s history would keep a name after you erase it.
# Test and live
> Every workspace has a test environment and a live one. The API key decides which one a request uses, and test traffic never touches live counts.
Every workspace has two environments, **test** and **live**. Each has its own API keys, webhook endpoints, limits, counts, balances, reservations and usage. Build and try your limits in test, then copy them to live when they work. Your production code uses a live key.
| | Test | Live |
| ------------- | ------------------------------------------ | --------------------------------------------------------------------------------- |
| API keys | start with `lim_test_` | start with `lim_live_` |
| Checks | count against a test allowance, not billed | count toward your plan |
| Plan limit | a hard stop at the test allowance | extras up to your cap on Pro and Business, 10% grace on Free, then your fail mode |
| Workspace API | a test key can read, not change | a live key can read and change |
| Webhooks | to test endpoints only | to live endpoints only |
You can’t rename the two environments, remove one or add a third.
## The key decides
[Section titled “The key decides”](#the-key-decides)
A key belongs to one environment, and its prefix says which: `lim_test_…` or `lim_live_…`. A request made with a test key reads and changes only test limits and counts. A request made with a live key uses only live ones. The API paths are the same in both, so moving to production means changing the key and nothing else.
Limit names are unique within an environment, so test and live can each have an “AI budget” limit. The other environment’s key can’t find a limit by its id. The same goes for a reservation, so commit or release it with a key from the environment that made it.
Test traffic can’t move live counts, even by mistake. A check made with a test key never counts toward a live limit, a live balance or your plan’s allowed checks.
## In the app
[Section titled “In the app”](#in-the-app)
Switch between **test** and **live** with the **Test | Live** toggle at the top right of the app. A dot marks the environment you’re in. Limits, usage, credits, API keys and webhooks all show that environment, and each page’s title says which, such as “Test API keys”. While you’re in test, a light orange band across the top of the page says “You’re viewing test data”, with a link to switch to live. The app starts in test, and remembers your choice for each workspace in this browser.
[   ](/docs/_astro/test-and-live.CaU9Ce0g.png "Open the screenshot at full size")
Workspace-wide settings, such as members, billing and the audit log, are the same in both. Switching doesn’t change them. Webhook endpoints aren’t shared. Each endpoint belongs to one environment and receives only its events.
## The test allowance
[Section titled “The test allowance”](#the-test-allowance)
Test checks have their own monthly allowance of 10% of your plan’s allowed checks, and we don’t bill them. They never count toward your allowed checks. The test allowance has no grace. Once a workspace uses it up, test checks return `402 plan_limit_reached` until the month resets or you upgrade. Live checks carry on as normal. See [Plan allowances](/docs/plans/) for the numbers on each plan.
## Copy to live
[Section titled “Copy to live”](#copy-to-live)
Once your limits work in test, copy them to live instead of creating them again. On the **Limits** page, switch to test and click **Copy to live**. Limitry lists exactly what will change in live before anything happens:
* When live has no limit with a test limit’s name, Limitry creates it in live.
* When live has a limit with the same name, Limitry updates it to match, field by field. The dialog shows each change, such as an amount going from 200 to 300.
* When a limit already matches, Limitry leaves it alone.
* A limit can’t change to or from `concurrent` in place. Archive or rename the live one first.
The dialog ticks every limit it would change. Untick any you don’t want to copy, then confirm. Copy to live carries over each limit’s subject, action, amount, unit, window, `every`, `start`, rolling, enabled and fail mode. It never copies balances, credits you added, reservations or usage, because live keeps its own.
[   ](/docs/_astro/copy-to-live.Cjp1JPwX.png "Open the screenshot at full size")
Owners and admins can copy limits. The audit log records each copy as `limits.copied`, with the limits it created and updated. An AI agent can’t copy limits itself. It asks, and an owner or admin approves. See [Approvals](/docs/approvals/).
There’s no API call for Copy to live, because every key belongs to one environment. To do the same from your own code, read the limits with a test key and create or update them with a live key.
## Your tools default to test
[Section titled “Your tools default to test”](#your-tools-default-to-test)
The [CLI](/docs/cli/), the [MCP server](/docs/mcp/) and scripts with a personal access token act as you. They work in test unless you name live, so a mistake changes test limits, never the ones your customers depend on. To act in live, say so in one of these ways.
| Tool | Live |
| ------------------ | ----------------------------------------------------------------------------------- |
| CLI | `--environment live`, `LIMITRY_ENVIRONMENT=live`, or `limitry environment use live` |
| MCP server | choose **Live** when you connect it |
| SDK | `createClient({ token, workspace: "acme", environment: "live" })` |
| HTTP, with a token | the header `X-Environment: live` |
Every response names its environment. The CLI prints `Environment: test` or `Environment: live` after each command, and every MCP tool result ends with the same line. An HTTP response to a personal access token or an agent carries an `X-Environment` header.
An API key always acts in its own environment, so it needs none of this. When a request made with a key names any other environment, it gets `403 forbidden`. A token that names an environment that doesn’t exist gets `400 invalid_request`.
## What a test key can’t change
[Section titled “What a test key can’t change”](#what-a-test-key-cant-change)
A test key can read workspace-wide things, such as members, webhook endpoints, deliveries, the audit log, approvals and plan usage. It can’t change them, because test keys are for trying limits, not for setting up the workspace. A test key that tries gets `403 forbidden` with the message “A test key cannot change workspace-wide settings”. To manage webhook endpoints through the API, use a live key or a personal access token.
## Webhooks
[Section titled “Webhooks”](#webhooks)
Each webhook endpoint belongs to test or live, like an API key, and gets only that environment’s events. Add an endpoint under **Settings → Developers**, and select the environment it’s for. You might add a test endpoint for your staging app and a live one for production. Events about the workspace itself, such as a member joining, go to endpoints in both.
Every Limitry event also says where it happened in its `environment` field, which is `"test"` or `"live"`.
```json
{
"type": "limit.reached",
"data": {
"limitId": "lmt_…",
"limitName": "AI budget",
"action": "ai-call",
"unit": "cents",
"window": "month",
"subject": { "kind": "user", "id": "user_123" },
"environment": "test",
"periodStart": "2026-10-01T00:00:00.000Z",
"resetsAt": "2026-11-01T00:00:00.000Z"
}
}
```
We moved endpoints added before 10 October 2026 to live.
## Older keys
[Section titled “Older keys”](#older-keys)
Keys that start with `sk_limitry_` date from before test and live existed. They no longer work and get `401 unauthorized`. Create a test or live key under **Settings → Developers** instead.
# TypeScript SDK
> Guard costly work with one call, and call every API operation from TypeScript, with types from the API itself.
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](/docs/reference/).
## Install
[Section titled “Install”](#install)
```bash
npm install @limitry/sdk
```
## Your key
[Section titled “Your key”](#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 the `LIMITRY_API_KEY` environment variable. If that isn’t set, it reads `LIMITRY_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](/docs/test-and-live/) explains the difference.
* With a **personal access token**, pass it as `token` and 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”](#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:
```ts
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:
```ts
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-your-code-cant-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](/docs/rolling-and-concurrency/#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 a `RangeError` for 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](/docs/how-it-works/#when-your-code-cant-reach-limitry) has the details.
## Methods
[Section titled “Methods”](#methods)
Every API operation is a method, named after the operation in the [API reference](/docs/reference/). For example, `limits.create` is `limitry.limits.create()`:
```ts
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:
```ts
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
* [`checks.create()`](/docs/reference/checks/#check-whether-a-subject-may-act)
Check whether a subject may act
* [`checks.list()`](/docs/reference/checks/#list-checks)
List checks
### Reservations
* [`reservations.commit()`](/docs/reference/reservations/#commit-a-reservation)
Commit a reservation
* [`reservations.extend()`](/docs/reference/reservations/#extend-a-reservation)
Extend a reservation
* [`reservations.get()`](/docs/reference/reservations/#get-a-reservation)
Get a reservation
* [`reservations.release()`](/docs/reference/reservations/#release-a-reservation)
Release a reservation
### Limits
* [`limits.archive()`](/docs/reference/limits/#archive-a-limit)
Archive a limit
* [`limits.create()`](/docs/reference/limits/#create-a-limit)
Create a limit
* [`limits.credits.create()`](/docs/reference/limits/#add-credits-to-a-balance)
Add credits to a balance
* [`limits.credits.get()`](/docs/reference/limits/#get-a-credit)
Get a credit
* [`limits.credits.list()`](/docs/reference/limits/#list-a-balances-credits)
List a balance's credits
* [`limits.get()`](/docs/reference/limits/#get-a-limit)
Get a limit
* [`limits.list()`](/docs/reference/limits/#list-limits)
List limits
* [`limits.restore()`](/docs/reference/limits/#restore-an-archived-limit)
Restore an archived limit
* [`limits.sync()`](/docs/reference/limits/#sync-limits-from-a-list)
Sync limits from a list
* [`limits.update()`](/docs/reference/limits/#change-a-limit)
Change a limit
### Subjects
* [`subjects.get()`](/docs/reference/subjects/#get-a-subject)
Get a subject
* [`subjects.import()`](/docs/reference/subjects/#name-many-subjects)
Name many subjects
* [`subjects.list()`](/docs/reference/subjects/#list-subjects)
List subjects
* [`subjects.names.delete()`](/docs/reference/subjects/#erase-a-subjects-name-and-labels)
Erase a subject's name and labels
* [`subjects.reset()`](/docs/reference/subjects/#reset-a-subjects-limits)
Reset a subject's limits
* [`subjects.standing()`](/docs/reference/subjects/#get-where-a-subject-stands)
Get where a subject stands
* [`subjects.update()`](/docs/reference/subjects/#update-a-subject)
Update a subject
### Usage
* [`usage.overview()`](/docs/reference/usage/#get-every-limits-usage-at-once)
Get every limit's usage at once
* [`usage.query()`](/docs/reference/usage/#get-a-limits-usage-over-time)
Get a limit's usage over time
* [`usage.subjects()`](/docs/reference/usage/#list-who-is-using-a-limit)
List who is using a limit
### Workspace
* [`workspace.get()`](/docs/reference/workspace/#get-the-current-workspace)
Get the current workspace
* [`workspace.invitations.list()`](/docs/reference/workspace/#list-pending-invitations)
List pending invitations
* [`workspace.members.list()`](/docs/reference/workspace/#list-workspace-members)
List workspace members
* [`workspace.planUsage.get()`](/docs/reference/workspace/#get-your-plans-usage-this-period)
Get your plan's usage this period
* [`workspace.teams.list()`](/docs/reference/workspace/#list-teams)
List teams
### Webhooks
* [`workspace.eventTypes.list()`](/docs/reference/webhooks/#list-event-types)
List event types
* [`workspace.webhookDeliveries.list()`](/docs/reference/webhooks/#list-an-endpoints-deliveries)
List an endpoint's deliveries
* [`workspace.webhookDeliveries.redeliver()`](/docs/reference/webhooks/#redeliver-an-event)
Redeliver an event
* [`workspace.webhookEndpoints.create()`](/docs/reference/webhooks/#add-a-webhook-endpoint)
Add a webhook endpoint
* [`workspace.webhookEndpoints.delete()`](/docs/reference/webhooks/#remove-a-webhook-endpoint)
Remove a webhook endpoint
* [`workspace.webhookEndpoints.enable()`](/docs/reference/webhooks/#re-enable-a-webhook-endpoint)
Re-enable a webhook endpoint
* [`workspace.webhookEndpoints.get()`](/docs/reference/webhooks/#get-a-webhook-endpoint)
Get a webhook endpoint
* [`workspace.webhookEndpoints.list()`](/docs/reference/webhooks/#list-webhook-endpoints)
List webhook endpoints
* [`workspace.webhookEndpoints.test()`](/docs/reference/webhooks/#send-a-test-event)
Send a test event
* [`workspace.webhookEndpoints.update()`](/docs/reference/webhooks/#update-a-webhook-endpoint)
Update a webhook endpoint
### Approvals
* [`workspace.approvalActions.list()`](/docs/reference/approvals/#list-the-actions-you-can-ask-approval-for)
List the actions you can ask approval for
* [`workspace.approvalRequests.create()`](/docs/reference/approvals/#ask-a-person-to-approve-an-action)
Ask a person to approve an action
* [`workspace.approvalRequests.get()`](/docs/reference/approvals/#check-an-approval-request)
Check an approval request
* [`workspace.approvalRequests.redeem()`](/docs/reference/approvals/#redeem-an-approved-request)
Redeem an approved request
### Audit events
* [`workspace.auditEvents.list()`](/docs/reference/audit-events/#list-workspace-audit-events)
List workspace audit events
### Personal access tokens
* [`user.me()`](/docs/reference/personal-access-tokens/#get-the-current-user)
Get the current user
* [`user.revokeToken()`](/docs/reference/personal-access-tokens/#revoke-the-token-making-this-request)
Revoke the token making this request
## Lists
[Section titled “Lists”](#lists)
A list method returns its first page when you `await` it. The page has the response’s `items` and `nextCursor`:
```ts
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:
```ts
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](/docs/pagination/).
## Errors
[Section titled “Errors”](#errors)
When the API refuses a call, the method throws an `APIError`. It has the [error](/docs/errors/)’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 as `Retry-After` and 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`:
```ts
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”](#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](#your-own-timeout-or-fail-mode) shows.
* Every write sends an [idempotency key](/docs/idempotency/). 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 `maxRetries` to `createClient`. `0` turns 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 a `RateLimitError`, instead.
* To make your own retries safe too, pass your key as the last argument:
```ts
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 `timeout` in milliseconds to `createClient`, or to one call:
```ts
limitry.limits.list({}, { timeout: 5000 });
```
* To limit a whole call, retries included, pass a `signal`. With `AbortSignal.timeout()`, the call stops at once when time is up, even while it waits to retry. It then throws the signal’s `TimeoutError`, not an SDK error:
```ts
limitry.limits.list({}, { signal: AbortSignal.timeout(2000) });
```
## Client options
[Section titled “Client options”](#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”](#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:
```ts
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:
```ts
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”](#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`:
```ts
import { createClient, unwrap } from "@limitry/sdk";
const limitry = createClient(); // uses the LIMITRY_API_KEY environment variable
const limits = unwrap(await limitry.GET("/limits"));
console.log(limits.items.length);
```
# Usage and reports
> See how much of each limit your subjects use over time and who is closest to it now, and hear when a limit says no.
Limitry counts every check per limit, per subject, per hour. Reports in the app and the API are at most about a minute behind. Test and live each have their own usage. The app shows the environment you picked, and the API returns usage for the key’s environment.
## In the app
[Section titled “In the app”](#in-the-app)
The **Usage** page shows two things for the limit you pick:
* **Last 30 days:** the units all subjects used each day (UTC). A plan that keeps less history shows fewer days, such as 7 on Free.
* **Right now:** the subjects using the limit, most used first. Each row shows what the subject has used and has left in its current period. For a limit that resets on each subject’s billing date or from first use, that’s the subject’s own period. When a limit has said no to a subject, the row shows how many of its checks got a no. When another subject’s limit said no, such as a team’s budget, the row names that subject. A check that uses several budgets counts in each of them, so the rows don’t add up to a total. The owner and admins can click **Reset** to reset a subject at once, and members can in test. See [When limits reset](/docs/resets/#reset-now).
[   ](/docs/_astro/usage-chart.BDVh9_ol.png "Open the screenshot at full size")
[   ](/docs/_astro/usage-now.CR-jYvVL.png "Open the screenshot at full size")
At the bottom of the page, **Busiest** lists the five subjects that made the most checks per second in the last 7 days, and when that happened. The figure is the checks in the subject’s busiest minute, divided by 60. A check counts for every subject it names, including its shared subjects. A team’s pool takes the checks of all its users, so it can be busier than any one of them. Limitry handles up to about 100 checks a second on one subject. A subject making 60 or more a second gets a note that it’s busy. Limitry is still handling it, and there’s nothing for you to do.
Below it, **Recent checks** lists each check from the last 3 days, newest first: every subject it named, its action and cost, and whether Limitry allowed it. A refused check names the subject whose budget refused it. Limitry keeps the last 3 days, and at most 100,000 checks in each environment. Click any subject to open its page (see [Subjects, names and links](/docs/subjects/)).
## From your code or the CLI
[Section titled “From your code or the CLI”](#from-your-code-or-the-cli)
Your code can read a limit’s use over time, by day (the default) or by hour. It can also see who is using the limit in the current window, or who used it most in a past period. Name the limit by its ID or by its name. A key or token needs the `limits:read` scope.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
const lastMonth = await limitry.usage.query({
limitName: "AI budget",
period: "last_month",
});
const busiest = await limitry.usage.subjects({
limitName: "AI budget",
period: "last_month",
});
const now = await limitry.usage.subjects({ limitName: "AI budget" });
console.log(lastMonth.total, busiest.subjects, now.subjects);
```
* Python
```python
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
last_month = limitry.usage.query(limit_name="AI budget", period="last_month")
busiest = limitry.usage.subjects(limit_name="AI budget", period="last_month")
now = limitry.usage.subjects(limit_name="AI budget")
print(last_month.total, busiest.subjects, now.subjects)
```
* CLI
```bash
limitry usage query --limit-name "AI budget" --period last_month
limitry usage subjects --limit-name "AI budget" --period last_month
limitry usage subjects --limit-name "AI budget"
```
* curl
```bash
curl "https://api.limitry.com/v1/usage?limitName=AI%20budget&period=last_month" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
curl "https://api.limitry.com/v1/usage/subjects?limitName=AI%20budget&period=last_month" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
curl "https://api.limitry.com/v1/usage/subjects?limitName=AI%20budget" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
The history has every bucket in the range, including empty ones. Each bucket has `used`, `allowed` and `refused`. `total` adds them up for the whole range. To see one subject, add `subject` as `kind:id`, such as `user:user_123`. To see a different range, add a `period`, or `from` and `to` as ISO 8601 times. A time can end in `Z` or an offset, such as `+05:00`. The default range is the last 30 days. No range reaches further back than your plan’s history, which is 7 days on Free. See [Plan allowances](/docs/plans/).
| `period` | The range, in UTC |
| ------------ | ------------------------------------------ |
| `today` | From midnight to now |
| `this_week` | From Monday to now |
| `last_week` | The week before this one, Monday to Monday |
| `this_month` | From the 1st to now |
| `last_month` | The whole calendar month before this one |
A name matches an active limit in the same environment. An exact match comes first. Otherwise, the name matches whatever its case. When two limits match that way, the request fails with a 400: send the exact name or the ID.
Both answers name the limit with its `unit`, `amount` and `window`, so you can read the numbers without fetching the limit. The ranking of subjects also says when the current window `resetsAt`.
The ranking of subjects covers the current window by default. With a `period` or a range, it ranks the subjects by their use in that range instead. Each one’s `remaining` is then null, since what’s left belongs to the current window. To list the most refused first, add `sort` as `refused`. The answer’s `subjects` ranks at most 50 subjects, or 25 for a `concurrent` limit. `top` sets fewer.
### Every limit at once
[Section titled “Every limit at once”](#every-limit-at-once)
The overview gives every active limit’s usage in one answer. Each limit comes with its unit, amount and window, its `total`, and its top subjects. It covers each limit’s current window by default, the whole window on every plan. Add a `period`, or `from` and `to`, for a past range. A past range reaches no further back than your plan’s history. With `sort` as `refused`, each limit lists only the subjects it refused. `top` sets how many subjects each limit lists, up to 20. A balance (window `total`) also lists its `credits`: the credits added and taken back in the range, and the latest credits, newest first.
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
const limitry = createClient();
const overview = await limitry.usage.overview({ period: "last_month" });
for (const limit of overview.limits) {
console.log(limit.limitName, limit.total.used, limit.unit);
}
```
* Python
```python
from limitry import Limitry
limitry = Limitry()
overview = limitry.usage.overview(period="last_month")
for limit in overview.limits:
print(limit.limit_name, limit.total.used, limit.unit)
```
* CLI
```bash
limitry usage overview --period last_month
limitry usage overview --period this_week --sort refused
```
* curl
```bash
curl "https://api.limitry.com/v1/usage/overview?period=last_month" \
-H "Authorization: Bearer $LIMITRY_API_KEY"
```
`used` is net. Limitry gives back the unused part of a committed reservation, and all of a released one.
For a balance (window `total`), what’s left includes the credits you’ve added.
Limitry keeps usage history as long as your plan shows it, then deletes it.
| Plan | History kept |
| ---------- | ------------------------ |
| Free | 7 days |
| Pro | 90 days |
| Business | 13 months |
| Enterprise | What your agreement says |
Limitry always keeps each limit’s current period whole, such as this month for a monthly limit. When your plan changes to one that keeps less, Limitry keeps the older history for 30 days, then deletes it. If you upgrade again within those 30 days, Limitry keeps all of it.
To read a whole billing period after it ends, use Pro or Business. On Free, send each finished hour to your billing system as it ends, as [Use Limitry with Stripe](/docs/works-with/stripe/#3-bill-usage-through-stripe-meters) does.
## Webhook: `limit.reached`
[Section titled “Webhook: limit.reached”](#webhook-limitreached)
The first time a limit refuses a subject in a window, your webhook endpoints receive `limit.reached`. Here a user has spent this month’s AI budget:
```json
{
"type": "limit.reached",
"data": {
"limitId": "lmt_…",
"limitName": "AI budget",
"action": "ai-call",
"unit": "cents",
"window": "month",
"subject": { "kind": "user", "id": "user_123" },
"environment": "live",
"periodStart": "2026-10-01T00:00:00.000Z",
"resetsAt": "2026-11-01T00:00:00.000Z"
}
}
```
Limitry sends it once per subject, limit and window, not on every check that gets a no. `environment` says whether it happened in `test` or `live`, and only that environment’s endpoints receive it. For a balance, `periodStart` and `resetsAt` are `null`. Add an endpoint under **Settings → Developers**.
To hear before a limit says no, use `limit.threshold_crossed`. Limitry sends it at 80% and 100% of a limit. See [Warnings before a limit](/docs/webhooks/#warnings-before-a-limit).
## One subject, right now
[Section titled “One subject, right now”](#one-subject-right-now)
`limitry.standing(...)` in the SDKs tells you where one subject stands on every limit that applies to it, exactly as a check would see it. On the CLI, it’s `limitry subjects standing`. Call it to show your users how much they have left. See [Show users where they stand](/docs/guides/show-usage/).
# Versioning
> What can change in the API, what never changes, and how we announce deprecations.
The API’s version is in its path, `/v1`. Within a version, we only make changes that don’t break a correctly written integration. The same promise covers the CLI and the tools agents use, because they’re named after the API’s operations.
## Changes we may make at any time
[Section titled “Changes we may make at any time”](#changes-we-may-make-at-any-time)
* New endpoints.
* New optional request parameters and fields.
* New fields in responses.
* New error codes, webhook event types and scopes.
* New commands, and new tools for agents.
Write your integration so these don’t break it:
* Ignore response fields you don’t recognise.
* Treat an error `code` you don’t recognise as `internal_error`.
* Branch on `code`, never on `message`.
* Treat cursors and ids as opaque strings.
## Changes we never make within `/v1`
[Section titled “Changes we never make within /v1”](#changes-we-never-make-within-v1)
* Removing or renaming an endpoint, a field or an operation. That includes the command or agent tool named after it.
* Changing the type or meaning of an existing field.
* Making an optional parameter required.
* Changing how requests authenticate, or which error a given failure returns.
Changes like these only ship in a new version, `/v2`, which runs alongside `/v1` while integrations move over.
## Deprecations
[Section titled “Deprecations”](#deprecations)
Before we retire anything in `/v1`, we announce it in the changelog, mark it **deprecated** in the [API reference](/docs/reference/), and say what to use instead. Deprecated endpoints keep working for as long as `/v1` exists.
# Webhooks
> Receive workspace events at your endpoint, verify signatures, and handle retries.
Webhooks send workspace events to an HTTPS endpoint you host as soon as they happen. Workspace owners and admins manage endpoints in the app under **Settings → Developers**, and members manage the test ones. Add a URL and copy the signing secret, which we show only once. Events then start arriving. You can edit an endpoint’s URL or events later, and it keeps the same signing secret.
## Managing endpoints through the API
[Section titled “Managing endpoints through the API”](#managing-endpoints-through-the-api)
Software can manage endpoints too, with a credential that has these scopes:
| To | Scope |
| ---------------- | -------------------------- |
| Manage endpoints | `workspace.webhooks:write` |
| Read endpoints | `workspace.webhooks:read` |
**Manage limits** includes both.
With a personal access token, every member of the workspace can read endpoints. Owners and admins can add and change them, and members can add and change test endpoints. A test key can read endpoints but can’t add or change them. To manage them, use a live key (`lim_live_…`) or a personal access token. Each endpoint still belongs to either test or live, as described below.
```bash
curl -X POST \
-H "Authorization: Bearer YOUR_LIVE_API_KEY" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{ "url": "https://example.com/hooks" }' \
https://api.limitry.com/v1/workspace/webhook-endpoints
```
The response is a `201` with the new endpoint. Its `Location` header holds the endpoint’s path. The endpoint’s signing secret is in `secret`, and the API returns it only this once:
```json
{
"id": "we_3f0c1a2e-4b5d-4c6e-8f70-1a2b3c4d5e6f",
"url": "https://example.com/hooks",
"description": null,
"enabled": true,
"eventTypes": null,
"environment": "live",
"consecutiveFailures": 0,
"lastHttpStatus": null,
"lastAttemptAt": null,
"createdAt": "2026-08-20T12:00:00.000Z",
"secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
}
```
The API can also:
* list endpoints
* change an endpoint’s URL or events with `PATCH`, which keeps its secret
* re-enable an endpoint we switched off after repeated failures
* send a test event
* list deliveries and redeliver them
The [API reference](/docs/reference/) has every operation.
Sending a test event and redelivering answer `200` when we tried the delivery right away. Then `ok` and `httpStatus` say how your endpoint answered. They answer `202` when the delivery went to the queue, with `queued: true`. Redelivering to a disabled endpoint fails with `409` and the code `conflict`. Re-enable the endpoint first.
AI agents connected to the workspace can read endpoints and delivery history, send test events and redeliver. They can’t add, change, remove or re-enable endpoints, because that changes where your workspace’s data goes. Only a person can do that.
## A delivery
[Section titled “A delivery”](#a-delivery)
Each delivery is an HTTP `POST` with a JSON body:
```json
{
"id": "evt_5f0c…",
"type": "workspace.member.joined",
"createdAt": "2026-08-20T12:00:00.000Z",
"data": { "userId": "…", "email": "casey@example.com" }
}
```
Each delivery also carries three signature headers:
```http
webhook-id: del_9a1b…
webhook-timestamp: 1755691200
webhook-signature: v1,MEQCIB…
```
`webhook-id` identifies the delivery and stays the same when we retry it, so use it to ignore duplicates. The `id` in the body identifies the event.
If you have several endpoints, each gets its own delivery of the same event, so deduplicate by the event’s `id` to process it once. That also covers the rare case where an event reaches you more than once as separate deliveries, for example when we resend it after an outage.
## Verifying signatures
[Section titled “Verifying signatures”](#verifying-signatures)
Before you trust a delivery, check that we sent it, that nobody changed it, and that it’s recent. The SDKs do all three checks with your endpoint’s secret (`whsec_…`) and give you the event:
* TypeScript
```ts
import { verifyWebhook, WebhookVerificationError } from "@limitry/sdk";
// A fetch-style handler (Hono, Workers, Next.js route handlers…).
export async function POST(request: Request) {
try {
// The RAW body: verify before parsing it.
const event = await verifyWebhook(
await request.text(),
request.headers,
process.env.WEBHOOK_SECRET!,
);
// handle event…
return new Response("ok");
} catch (error) {
if (error instanceof WebhookVerificationError) {
return new Response("bad signature", { status: 400 });
}
throw error;
}
}
```
* Python
```python
import os
from flask import Flask, request
from limitry import WebhookVerificationError, verify_webhook
app = Flask(__name__)
@app.post("/webhooks")
def webhooks():
try:
# The RAW body: verify before parsing it.
event = verify_webhook(
request.get_data(), request.headers, os.environ["WEBHOOK_SECRET"]
)
except WebhookVerificationError:
return "bad signature", 400
# handle event…
return "ok"
```
If you’ve already created a client, the same check is `limitry.webhooks.verify(…)`. The SDKs refuse a delivery older than 5 minutes, so no one can replay an old one. To change that limit, set `toleranceSeconds` in TypeScript or `tolerance_seconds` in Python.
We sign deliveries the same way [Svix](https://docs.svix.com/receiving/verifying-payloads/how) does, so any standard Svix library can verify them. In other languages, verify the signature yourself:
1. Take the secret without its `whsec_` prefix and Base64-decode it. That’s the HMAC key.
2. Compute the HMAC-SHA256 of `` `${webhookId}.${timestamp}.${body}` `` with that key, and Base64-encode it.
3. The signature is `v1,` followed by that value.
Always verify the **raw** body, because re-serialising the JSON changes it and breaks the signature. Reject timestamps more than a few minutes old.
## Respond quickly, process later
[Section titled “Respond quickly, process later”](#respond-quickly-process-later)
Respond with a `2xx` within 10 seconds, or the delivery counts as failed. If processing takes longer, acknowledge the delivery first and do the work afterwards.
## Retries and failures
[Section titled “Retries and failures”](#retries-and-failures)
If a delivery fails, we retry it with backoff, up to 6 attempts in total. Each retry keeps the same `webhook-id`. A delivery fails when your endpoint:
* times out
* doesn’t respond
* returns a `5xx`, `408` or `429`
Any other response, such as a `400` or a `404`, means your endpoint got the request and refused it. Retrying wouldn’t help, so that delivery fails straight away. We don’t follow redirects, so a `3xx` fails it too.
If 20 attempts in a row fail, across all of the endpoint’s deliveries, we switch the endpoint off. Once it’s working again, choose **Re-enable** under **Settings → Developers**, or call `POST /v1/workspace/webhook-endpoints/{endpointId}/enable`. It keeps its signing secret, and the count of failed attempts starts again from zero.
Under **Settings → Developers**, an endpoint’s **Deliveries** shows each delivery’s status and attempts. Through the API, a delivery’s `status` is its state: `pending`, `delivered` or `failed`. `lastHttpStatus` is the HTTP status code your endpoint last answered with. You can also send a test event (`type: "ping"`) and redeliver any recorded delivery. A redelivery gets a new `webhook-id` but keeps the event’s `id`, so deduplicating by event still works.
## Events
[Section titled “Events”](#events)
| Type | Sent when | `data` |
| ------------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `limit.threshold_crossed` | A subject first reaches 80% or 100% of a limit. | `limitId`, `limitName`, `action`, `unit`, `window`, `subject`, `environment`, `threshold`, `used`, `amount`, `periodStart`, `resetsAt` |
| `limit.reached` | A limit first refuses a subject in a window. | `limitId`, `limitName`, `action`, `unit`, `window`, `subject`, `environment`, `periodStart`, `resetsAt` |
| `workspace.member.joined` | Someone accepts an invitation. | `userId`, `email` |
| `ping` | You send a test from Settings. | a test message |
`limitName`, `action`, `unit` and `window` say what the limit is, so a handler can word its message (“80% of this month’s AI budget”) without looking the limit up.
An endpoint belongs to [test or live](/docs/test-and-live/#webhooks) and receives only that environment’s limit events. Both limit events also say which in `environment`, `"test"` or `"live"`. See [Usage and reports](/docs/usage/#webhook-limitreached) for an example.
### In the dashboard too
[Section titled “In the dashboard too”](#in-the-dashboard-too)
You don’t need a webhook to hear about your live limits. The dashboard tells the workspace’s owners and admins when a live limit refuses one of your users, and when one of your users passes 80% or 100% of a live limit. Each limit sends each notification at most once a day. Each person chooses whether it reaches them in the app, by email or on their phone. See [Notifications](/docs/notifications/).
## Warnings before a limit
[Section titled “Warnings before a limit”](#warnings-before-a-limit)
`limit.threshold_crossed` tells you a subject is close to a limit while there’s still room to act: email the user, show a banner, offer more credits. Limitry sends it the first time a subject’s use reaches 80% of a limit in a window, and again at 100%, which is the last use the limit allows. Limitry refuses the first check after that and sends `limit.reached` as before.
```json
{
"id": "evt_3c9a…",
"type": "limit.threshold_crossed",
"createdAt": "2026-10-08T09:14:02.000Z",
"data": {
"limitId": "lmt_…",
"limitName": "AI budget",
"action": "ai-call",
"unit": "cents",
"window": "month",
"subject": { "kind": "user", "id": "user_123" },
"environment": "live",
"threshold": 80,
"used": 160,
"amount": 200,
"periodStart": "2026-10-01T00:00:00.000Z",
"resetsAt": "2026-11-01T00:00:00.000Z"
}
}
```
How often each kind of limit warns:
| Limit | When it warns |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Per minute, hour, day, week, month or year | Once at 80% and once at 100% in each window. |
| Rolling (“in any 24 hours”) | At 80% and 100%, at most once an hour for each. |
| Balance (window `total`) | At 20% left (`threshold: 80`) and when it runs out (`threshold: 100`). After you add credits, it can warn again (as a new event, with a new id) as the balance runs down. `periodStart` and `resetsAt` are `null`. |
| Concurrent (“at most N at once”) | Never. A concurrent limit fills and empties all the time, so a warning would mean nothing. |
A warning reaches your endpoint within about a minute of the check that crossed the line. A [reservation](/docs/reservations/) counts from the moment you make it. If its commit costs more than it reserved, the extra use can warn too. If you release a reservation that warned, or commit it for less, the warning stands. The next time use reaches the line, it warns again. A rolling limit still warns at most once an hour.
A warning from [test](/docs/test-and-live/) carries `"environment": "test"`, so a handler can skip it. If we send the same warning twice, after an outage for example, both deliveries carry the same event `id`, so deduplicating by `id` drops the second one.
Limitry only tells you. Whether and how to tell your user is up to your product: see [Warn your users before they hit a limit](/docs/guides/warn-users/).
Event payloads only ever gain fields, so write parsers that ignore fields they don’t know. `GET /v1/workspace/event-types` lists every event type and what it means.
## Choosing events
[Section titled “Choosing events”](#choosing-events)
An endpoint receives every event unless you choose otherwise. In **Settings → Developers**, pick “Only these” when you add the endpoint. Through the API, pass `eventTypes` when you create it:
```bash
curl -X POST https://api.limitry.com/v1/workspace/webhook-endpoints \
-H "Authorization: Bearer YOUR_LIVE_API_KEY" -H "content-type: application/json" \
-d '{"url":"https://example.com/hooks","eventTypes":["limit.reached"]}'
```
A test event (`ping`) always reaches the endpoint you’re testing.
# Works with
> Limitry works beside the billing tool, the AI gateway and the AI SDKs you already use. Each page shows one pairing, with the code for it.
Limitry answers yes or no before each costly request your product makes. It works beside the tools you already use, and each one keeps doing its own job. Your code checks with Limitry, then calls those tools directly.
| Tool | How the two fit |
| --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| [Stripe](/docs/works-with/stripe/) | Stripe takes the payments, and Limitry counts what each customer uses. |
| [OpenRouter](/docs/works-with/openrouter/) | OpenRouter reports what each request cost, and Limitry charges that cost to the user’s budget. |
| [Vercel AI SDK](/docs/works-with/vercel-ai-sdk/) | One middleware gives each of your users a budget across every model they use. |
| [LiteLLM](/docs/works-with/litellm/) | One hook on the proxy gives each of your users a budget, charged at the cost LiteLLM reports. |
| [OpenAI and Anthropic SDKs](/docs/works-with/openai-anthropic/) | Each call reserves its likely cost first, then charges the tokens it used. |
| [Agent frameworks](/docs/works-with/agent-frameworks/) | Each agent gets a budget, and stops cleanly between steps when it runs out. |
Every page follows the same three steps. Reserve what the request will probably cost, run it, then commit what it really cost. [Reservations](/docs/reservations/) explains each step.
The pages use the budget from [Limit AI spend per user](/docs/guides/limit-ai-spend/#1-create-the-budget): 200 cents a month for each user, with the action `ai-call`. The agent pages use the budget from [Give AI agents a budget](/docs/guides/agent-budgets/).
# Use Limitry with agent frameworks
> Give each agent a budget in the Claude Agent SDK, the OpenAI Agents SDK, LangChain and LangGraph, or Mastra, and stop it cleanly between steps.
Agent frameworks run the loop: the model thinks, calls a tool, and thinks again. Limitry gives each agent a budget across that whole loop. Each framework has a place to check it, and the agent stops cleanly between steps when the budget runs out.
## 1. Create the budget
[Section titled “1. Create the budget”](#1-create-the-budget)
Create the $5-a-day budget for every agent from [Give AI agents a budget](/docs/guides/agent-budgets/#1-create-the-budget). Its action is `*`, so every check for an agent draws from it.
## Claude Agent SDK
[Section titled “Claude Agent SDK”](#claude-agent-sdk)
The Claude Agent SDK caps a run’s spend with `maxBudgetUsd`, and reports what the run cost. Reserve the run’s cap from the agent’s budget, give the agent the same cap, then commit what the run cost:
* TypeScript
```ts
import { query } from "@anthropic-ai/claude-agent-sdk";
import { createClient, LimitReachedError } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
export async function runTask(agentId: string, task: string) {
try {
// Set aside the run's whole cap, $2, and give the agent the same cap.
return await limitry.reserve(
{
subject: { kind: "agent", id: agentId },
action: "tool",
cost: 200,
ttlSeconds: 3600,
},
async (reservation) => {
const options = { maxBudgetUsd: 2 };
for await (const message of query({ prompt: task, options })) {
if (message.type === "result") {
reservation.cost(Math.ceil(message.total_cost_usd * 100));
return message.subtype === "success" ? message.result : null;
}
}
return null;
},
);
} catch (err) {
if (err instanceof LimitReachedError) {
return "This agent reached its budget for today.";
}
throw err;
}
}
```
* Python
```python
import math
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
from limitry import AsyncLimitry, LimitReachedError
# Uses the LIMITRY_API_KEY environment variable.
limitry = AsyncLimitry()
async def run_task(agent_id: str, task: str) -> str | None:
try:
# Set aside the run's whole cap, $2, and give the agent the same cap.
async with limitry.reserve(
subject={"kind": "agent", "id": agent_id},
action="tool",
cost=200,
ttl_seconds=3600,
) as reservation:
options = ClaudeAgentOptions(max_budget_usd=2)
async for message in query(prompt=task, options=options):
if isinstance(message, ResultMessage):
reservation.cost = math.ceil((message.total_cost_usd or 0) * 100)
return message.result
return None
except LimitReachedError:
return "This agent reached its budget for today."
```
What the run didn’t spend goes straight back to the agent’s budget. For a run longer than an hour, call `reservation.extend()` as it goes.
## OpenAI Agents SDK
[Section titled “OpenAI Agents SDK”](#openai-agents-sdk)
The OpenAI Agents SDK calls the model once per step. Check the budget at each call, and commit the tokens it used. In TypeScript, wrap the model. In Python, add run hooks:
* TypeScript
```ts
import {
Agent,
run,
type Model,
type ModelRequest,
type ModelResponse,
} from "@openai/agents";
import { OpenAIProvider } from "@openai/agents-openai";
import { createClient, LimitReachedError } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
// Your prices, in cents per million tokens.
const priceCents = (response: ModelResponse) =>
Math.ceil(
(response.usage.inputTokens * 300 + response.usage.outputTokens * 1500) /
1_000_000,
);
// Reserves before each model call in the run, and commits what it cost.
class BudgetedModel implements Model {
constructor(
private readonly model: Model,
private readonly agentId: string,
) {}
getResponse(request: ModelRequest) {
return limitry.reserve(
{
subject: { kind: "agent", id: this.agentId },
action: "tool",
cost: 10,
},
async (reservation) => {
const response = await this.model.getResponse(request);
reservation.cost(priceCents(response));
return response;
},
);
}
getStreamedResponse(request: ModelRequest) {
return this.model.getStreamedResponse(request);
}
}
export async function runTask(agentId: string, task: string) {
const model = await new OpenAIProvider().getModel("gpt-6.2-sol");
const agent = new Agent({
name: "Researcher",
instructions: "Answer with sources.",
model: new BudgetedModel(model, agentId),
});
try {
const result = await run(agent, task);
return result.finalOutput;
} catch (err) {
if (err instanceof LimitReachedError) {
return "This agent reached its budget for today.";
}
throw err;
}
}
```
* Python
```python
import math
from agents import Agent, RunContextWrapper, RunHooks, Runner, TResponseInputItem
from agents.items import ModelResponse
from limitry import AsyncLimitry, LimitReachedError
# Uses the LIMITRY_API_KEY environment variable.
limitry = AsyncLimitry()
# Your prices, in cents per million tokens.
def price_cents(response: ModelResponse) -> int:
usage = response.usage
return math.ceil((usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000)
class AgentBudget(RunHooks):
"""Reserves before each model call in the run, and commits what it cost."""
def __init__(self, agent_id: str) -> None:
self.agent_id = agent_id
self.reservation_id: str | None = None
async def on_llm_start(
self,
context: RunContextWrapper,
agent: Agent,
system_prompt: str | None,
input_items: list[TResponseInputItem],
) -> None:
decision = await limitry.checks.create(
subject={"kind": "agent", "id": self.agent_id},
action="tool",
cost=10,
mode="reserve",
)
if not decision.allowed or decision.reservation is None:
raise LimitReachedError(decision)
self.reservation_id = decision.reservation.id
async def on_llm_end(
self, context: RunContextWrapper, agent: Agent, response: ModelResponse
) -> None:
if self.reservation_id:
await limitry.reservations.commit(self.reservation_id, cost=price_cents(response))
self.reservation_id = None
async def run_task(agent_id: str, task: str) -> str:
agent = Agent(name="Researcher", instructions="Answer with sources.")
try:
result = await Runner.run(agent, task, hooks=AgentBudget(agent_id))
return str(result.final_output)
except LimitReachedError:
return "This agent reached its budget for today."
```
## LangChain and LangGraph
[Section titled “LangChain and LangGraph”](#langchain-and-langgraph)
A LangChain agent runs on LangGraph, and its middleware wraps every model call the agent makes. Add one middleware for the budget:
* TypeScript
```ts
import { createClient, LimitReachedError } from "@limitry/sdk";
import { createAgent, createMiddleware, type AIMessage } from "langchain";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
// Your prices, in cents per million tokens.
const priceCents = (message: AIMessage) =>
Math.ceil(
((message.usage_metadata?.input_tokens ?? 0) * 300 +
(message.usage_metadata?.output_tokens ?? 0) * 1500) /
1_000_000,
);
// Reserves before each model call the agent makes, and commits its cost.
const agentBudget = (agentId: string) =>
createMiddleware({
name: "LimitryBudget",
wrapModelCall: (request, handler) =>
limitry.reserve(
{ subject: { kind: "agent", id: agentId }, action: "tool", cost: 10 },
async (reservation) => {
const message = await handler(request);
reservation.cost(priceCents(message));
return message;
},
),
});
export async function runTask(agentId: string, task: string) {
const agent = createAgent({
model: "openai:gpt-6.2-sol",
tools: [],
middleware: [agentBudget(agentId)],
});
try {
const result = await agent.invoke({
messages: [{ role: "user", content: task }],
});
return result.messages.at(-1)?.content;
} catch (err) {
// LangChain passes a middleware's error on as its `cause`.
if (err instanceof Error && err.cause instanceof LimitReachedError) {
return "This agent reached its budget for today.";
}
throw err;
}
}
```
* Python
```python
import math
from collections.abc import Callable
from langchain.agents import create_agent
from langchain.agents.middleware import ModelRequest, ModelResponse, wrap_model_call
from langchain.messages import AIMessage
from limitry import LimitReachedError, Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
# Your prices, in cents per million tokens.
def price_cents(response: ModelResponse) -> int:
tokens_in = tokens_out = 0
for message in response.result:
if isinstance(message, AIMessage) and message.usage_metadata:
tokens_in += message.usage_metadata["input_tokens"]
tokens_out += message.usage_metadata["output_tokens"]
return math.ceil((tokens_in * 300 + tokens_out * 1500) / 1_000_000)
def agent_budget(agent_id: str):
"""Reserves before each model call the agent makes, and commits its cost."""
@wrap_model_call
def budget(
request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]
) -> ModelResponse:
with limitry.reserve(
subject={"kind": "agent", "id": agent_id}, action="tool", cost=10
) as reservation:
response = handler(request)
reservation.cost = price_cents(response)
return response
return budget
def run_task(agent_id: str, task: str):
agent = create_agent(
model="openai:gpt-6.2-sol", tools=[], middleware=[agent_budget(agent_id)]
)
try:
result = agent.invoke({"messages": [{"role": "user", "content": task}]})
return result["messages"][-1].content
except LimitReachedError:
return "This agent reached its budget for today."
```
## Mastra
[Section titled “Mastra”](#mastra)
A Mastra agent takes an AI SDK model, so it takes the Limitry middleware from [Use Limitry with the Vercel AI SDK](/docs/works-with/vercel-ai-sdk/#2-add-the-middleware) as it is. Wrap the agent’s model with the agent as the subject:
```ts
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { wrapLanguageModel } from "ai";
import { aiBudget } from "./ai-budget";
export const researcher = (agentId: string) =>
new Agent({
id: "researcher",
name: "Researcher",
instructions: "Answer with sources.",
model: wrapLanguageModel({
model: openai("gpt-6.2-sol"),
middleware: aiBudget({ kind: "agent", id: agentId }),
}),
});
```
`researcher(agentId).generate(task)` throws the `LimitReachedError` once the agent’s budget runs out.
## What you see
[Section titled “What you see”](#what-you-see)
* A step that uses 10,000 input tokens and 2,000 output tokens commits 6 cents at these prices, against the agent’s $5 for the day.
* On the [Usage](/docs/usage/) page, each agent’s spend today.
* An agent over budget stops before its next model call, never in the middle of one, and your code gets the `LimitReachedError`.
To let a person approve more for an agent, see [Give AI agents a budget](/docs/guides/agent-budgets/#3-let-a-person-approve-more).
Related: [Reservations](/docs/reservations/).
# Use Limitry with LiteLLM
> Give each of your users an AI budget on the LiteLLM proxy or in the LiteLLM SDK, charged at the cost LiteLLM works out for each call.
LiteLLM gives your product one API for every model, and works out what each call cost. Limitry charges that cost to each of your users’ budgets. LiteLLM’s own budgets for keys and teams keep working beside it, and your users each get an allowance of their own.
## 1. Create the budget
[Section titled “1. Create the budget”](#1-create-the-budget)
Create the 200-cent monthly budget from [Limit AI spend per user](/docs/guides/limit-ai-spend/#1-create-the-budget). It counts in cents, with the action `ai-call`.
## 2a. On the LiteLLM proxy
[Section titled “2a. On the LiteLLM proxy”](#2a-on-the-litellm-proxy)
One hook file gives every request through the proxy a budget check. Before the call, it reserves a few cents for the user the request names. After the call, it commits the cost LiteLLM reports. Save it next to your `config.yaml` as `limitry_budget.py`:
```python
import math
import litellm
from fastapi import HTTPException
from limitry import AsyncLimitry
from litellm.integrations.custom_logger import CustomLogger
# Uses the LIMITRY_API_KEY environment variable.
limitry = AsyncLimitry()
def cents(dollars: float | None) -> int:
return math.ceil((dollars or 0) * 100)
class LimitryBudget(CustomLogger):
async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
if not data.get("user"):
raise HTTPException(status_code=400, detail="Name the user in `user`.")
decision = await limitry.checks.create(
subject={"kind": "user", "id": data["user"]},
action="ai-call",
cost=5,
mode="reserve",
)
if not decision.allowed or decision.reservation is None:
raise HTTPException(status_code=429, detail="This user's AI budget has run out.")
data.setdefault("metadata", {})["limitry_reservation"] = decision.reservation.id
return data
async def async_post_call_success_hook(self, data, user_api_key_dict, response):
reservation_id = data["metadata"]["limitry_reservation"]
cost = cents(response._hidden_params.get("response_cost"))
await limitry.reservations.commit(reservation_id, cost=cost)
return response
async def async_post_call_streaming_iterator_hook(
self, user_api_key_dict, response, request_data
):
chunks = []
async for chunk in response:
chunks.append(chunk)
yield chunk
reply = litellm.stream_chunk_builder(chunks, messages=request_data["messages"])
reservation_id = request_data["metadata"]["limitry_reservation"]
cost = cents(litellm.completion_cost(reply))
await limitry.reservations.commit(reservation_id, cost=cost)
proxy_handler_instance = LimitryBudget()
```
Then point the proxy at it in `config.yaml`:
```yaml
litellm_settings:
callbacks: limitry_budget.proxy_handler_instance
```
Your app names the user in the `user` field of each request, as the OpenAI API does. Every language and SDK that talks to the proxy works unchanged.
## 2b. In the LiteLLM SDK
[Section titled “2b. In the LiteLLM SDK”](#2b-in-the-litellm-sdk)
Calling LiteLLM from your own Python code? Reserve around the call, and commit LiteLLM’s price for it:
```python
import math
import litellm
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
def answer(user_id: str, prompt: str) -> str:
with limitry.reserve(
subject={"kind": "user", "id": user_id}, action="ai-call", cost=5
) as reservation:
response = litellm.completion(
model="openai/gpt-6.2-sol",
messages=[{"role": "user", "content": prompt}],
)
# LiteLLM prices each call, in US dollars.
reservation.cost = math.ceil(litellm.completion_cost(response) * 100)
return response.choices[0].message.content or ""
```
When the user is over budget, `reserve` raises `LimitReachedError` before the call, so you can show your own message.
## What you see
[Section titled “What you see”](#what-you-see)
* Each request commits the cents LiteLLM charged for it, streamed or not.
* On the [Usage](/docs/usage/) page, each user’s AI spend this month, across every model behind LiteLLM.
* A user over budget gets a `429` from the proxy, with “This user’s AI budget has run out.” The model call never starts, so it costs you nothing.
Related: [Reservations](/docs/reservations/), [Budgets at several levels](/docs/guides/several-levels/).
# Use Limitry with the OpenAI and Anthropic SDKs
> Give each of your users an AI budget around every OpenAI or Anthropic call, charged at the tokens each reply used, streamed or not.
The OpenAI and Anthropic SDKs report the tokens each reply used. Limitry turns those tokens into cents at your prices, and charges them to the user’s budget. Your code calls the model exactly as before, inside one `reserve` block.
## 1. Create the budget
[Section titled “1. Create the budget”](#1-create-the-budget)
Create the 200-cent monthly budget from [Limit AI spend per user](/docs/guides/limit-ai-spend/#1-create-the-budget). It counts in cents, with the action `ai-call`.
## 2. OpenAI
[Section titled “2. OpenAI”](#2-openai)
Reserve a few cents, call the model, then commit what the tokens cost:
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
import OpenAI from "openai";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
// Uses the OPENAI_API_KEY environment variable.
const openai = new OpenAI();
// Your prices, in cents per million tokens.
const priceCents = (usage: OpenAI.CompletionUsage) =>
Math.ceil(
(usage.prompt_tokens * 300 + usage.completion_tokens * 1500) / 1_000_000,
);
export async function answer(userId: string, prompt: string) {
return limitry.reserve(
{ subject: { kind: "user", id: userId }, action: "ai-call", cost: 5 },
async (reservation) => {
const completion = await openai.chat.completions.create({
model: "gpt-6.2-sol",
messages: [{ role: "user", content: prompt }],
});
if (completion.usage) reservation.cost(priceCents(completion.usage));
return completion.choices[0]?.message.content ?? "";
},
);
}
```
* Python
```python
import math
from limitry import Limitry
from openai import OpenAI
from openai.types import CompletionUsage
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
# Uses the OPENAI_API_KEY environment variable.
openai = OpenAI()
# Your prices, in cents per million tokens.
def price_cents(usage: CompletionUsage) -> int:
return math.ceil((usage.prompt_tokens * 300 + usage.completion_tokens * 1500) / 1_000_000)
def answer(user_id: str, prompt: str) -> str:
with limitry.reserve(
subject={"kind": "user", "id": user_id}, action="ai-call", cost=5
) as reservation:
completion = openai.chat.completions.create(
model="gpt-6.2-sol",
messages=[{"role": "user", "content": prompt}],
)
if completion.usage:
reservation.cost = price_cents(completion.usage)
return completion.choices[0].message.content or ""
```
### Streaming
[Section titled “Streaming”](#streaming)
Ask for the usage with `stream_options`. OpenAI then sends it in the stream’s last chunk:
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
import OpenAI from "openai";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
// Uses the OPENAI_API_KEY environment variable.
const openai = new OpenAI();
// Your prices, in cents per million tokens.
const priceCents = (usage: OpenAI.CompletionUsage) =>
Math.ceil(
(usage.prompt_tokens * 300 + usage.completion_tokens * 1500) / 1_000_000,
);
export async function streamAnswer(userId: string, prompt: string) {
return limitry.reserve(
{ subject: { kind: "user", id: userId }, action: "ai-call", cost: 5 },
async (reservation) => {
const stream = await openai.chat.completions.create({
model: "gpt-6.2-sol",
messages: [{ role: "user", content: prompt }],
stream: true,
stream_options: { include_usage: true },
});
let text = "";
for await (const chunk of stream) {
text += chunk.choices[0]?.delta.content ?? "";
if (chunk.usage) reservation.cost(priceCents(chunk.usage));
}
return text;
},
);
}
```
* Python
```python
import math
from limitry import Limitry
from openai import OpenAI
from openai.types import CompletionUsage
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
# Uses the OPENAI_API_KEY environment variable.
openai = OpenAI()
# Your prices, in cents per million tokens.
def price_cents(usage: CompletionUsage) -> int:
return math.ceil((usage.prompt_tokens * 300 + usage.completion_tokens * 1500) / 1_000_000)
def stream_answer(user_id: str, prompt: str) -> str:
with limitry.reserve(
subject={"kind": "user", "id": user_id}, action="ai-call", cost=5
) as reservation:
stream = openai.chat.completions.create(
model="gpt-6.2-sol",
messages=[{"role": "user", "content": prompt}],
stream=True,
stream_options={"include_usage": True},
)
text = ""
for chunk in stream:
if chunk.choices:
text += chunk.choices[0].delta.content or ""
if chunk.usage:
reservation.cost = price_cents(chunk.usage)
return text
```
## 3. Anthropic
[Section titled “3. Anthropic”](#3-anthropic)
The same block works with Claude. The reply’s `usage` has the token counts:
* TypeScript
```ts
import Anthropic from "@anthropic-ai/sdk";
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
// Uses the ANTHROPIC_API_KEY environment variable.
const anthropic = new Anthropic();
// Your prices, in cents per million tokens.
const priceCents = (usage: Anthropic.Usage) =>
Math.ceil(
(usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000,
);
export async function answer(userId: string, prompt: string) {
return limitry.reserve(
{ subject: { kind: "user", id: userId }, action: "ai-call", cost: 5 },
async (reservation) => {
const message = await anthropic.messages.create({
model: "claude-sonnet-5-5",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }],
});
reservation.cost(priceCents(message.usage));
return message.content
.map((block) => (block.type === "text" ? block.text : ""))
.join("");
},
);
}
```
* Python
```python
import math
from anthropic import Anthropic
from anthropic.types import Usage
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
# Uses the ANTHROPIC_API_KEY environment variable.
anthropic = Anthropic()
# Your prices, in cents per million tokens.
def price_cents(usage: Usage) -> int:
return math.ceil((usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000)
def answer(user_id: str, prompt: str) -> str:
with limitry.reserve(
subject={"kind": "user", "id": user_id}, action="ai-call", cost=5
) as reservation:
message = anthropic.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
)
reservation.cost = price_cents(message.usage)
return "".join(block.text for block in message.content if block.type == "text")
```
### Streaming
[Section titled “Streaming”](#streaming-1)
A stream’s final message carries the usage for the whole reply:
* TypeScript
```ts
import Anthropic from "@anthropic-ai/sdk";
import { createClient } from "@limitry/sdk";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
// Uses the ANTHROPIC_API_KEY environment variable.
const anthropic = new Anthropic();
// Your prices, in cents per million tokens.
const priceCents = (usage: Anthropic.Usage) =>
Math.ceil(
(usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000,
);
export async function streamAnswer(userId: string, prompt: string) {
return limitry.reserve(
{ subject: { kind: "user", id: userId }, action: "ai-call", cost: 5 },
async (reservation) => {
const stream = anthropic.messages.stream({
model: "claude-sonnet-5-5",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }],
});
stream.on("text", (text) => process.stdout.write(text));
const message = await stream.finalMessage();
reservation.cost(priceCents(message.usage));
return message;
},
);
}
```
* Python
```python
import math
from anthropic import Anthropic
from anthropic.types import Usage
from limitry import Limitry
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
# Uses the ANTHROPIC_API_KEY environment variable.
anthropic = Anthropic()
# Your prices, in cents per million tokens.
def price_cents(usage: Usage) -> int:
return math.ceil((usage.input_tokens * 300 + usage.output_tokens * 1500) / 1_000_000)
def stream_answer(user_id: str, prompt: str) -> str:
with limitry.reserve(
subject={"kind": "user", "id": user_id}, action="ai-call", cost=5
) as reservation:
with anthropic.messages.stream(
model="claude-sonnet-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
) as stream:
text = "".join(stream.text_stream)
reservation.cost = price_cents(stream.get_final_message().usage)
return text
```
## What you see
[Section titled “What you see”](#what-you-see)
* A reply that uses 10,000 input tokens and 2,000 output tokens commits 6 cents at these prices.
* On the [Usage](/docs/usage/) page, each user’s AI spend this month, across both providers.
* A user over budget gets a `LimitReachedError` from `reserve` before the call, so the model is never called and it costs you nothing. [Limit AI spend per user](/docs/guides/limit-ai-spend/#2-reserve-call-commit) shows the message to send them.
To cap each model on its own as well, name the model in the action: [One budget, or a budget per model](/docs/guides/limit-ai-spend/#3-one-budget-or-a-budget-per-model).
Related: [Reservations](/docs/reservations/).
# Use Limitry with OpenRouter
> Give each of your users an AI budget across every model on OpenRouter, charged at the exact cost OpenRouter reports for each request.
OpenRouter gives your product one API for many models, and tells you what each request cost. Limitry charges that exact cost to the user’s budget, so each of your users stays within their allowance on every model. There’s no price table to keep.
## 1. Create the budget
[Section titled “1. Create the budget”](#1-create-the-budget)
Create the 200-cent monthly budget from [Limit AI spend per user](/docs/guides/limit-ai-spend/#1-create-the-budget). It counts in cents, with the action `ai-call`.
## 2. Reserve, call, commit
[Section titled “2. Reserve, call, commit”](#2-reserve-call-commit)
OpenRouter answers the OpenAI API, so the OpenAI SDK talks to it. Reserve a few cents before the request. Then commit the cost OpenRouter returns, in whole cents:
* TypeScript
```ts
import { createClient, LimitReachedError } from "@limitry/sdk";
import OpenAI from "openai";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
// OpenRouter answers the OpenAI API, so the OpenAI SDK talks to it.
const openrouter = new OpenAI({
baseURL: "https://openrouter.ai/api/v1",
apiKey: process.env.OPENROUTER_API_KEY,
});
// OpenRouter adds what the request cost to its usage, in US dollars.
type OpenRouterUsage = OpenAI.CompletionUsage & { cost?: number };
export async function answer(userId: string, prompt: string) {
try {
return await limitry.reserve(
{ subject: { kind: "user", id: userId }, action: "ai-call", cost: 5 },
async (reservation) => {
const completion = await openrouter.chat.completions.create({
model: "anthropic/claude-sonnet-5.5",
messages: [{ role: "user", content: prompt }],
user: userId,
});
const usage = completion.usage as OpenRouterUsage | undefined;
if (usage?.cost !== undefined) {
reservation.cost(Math.ceil(usage.cost * 100));
}
return completion.choices[0]?.message.content ?? "";
},
);
} catch (err) {
if (err instanceof LimitReachedError) {
return "You've used this month's AI allowance. It resets on the 1st.";
}
throw err;
}
}
```
* Python
```python
import math
import os
from limitry import LimitReachedError, Limitry
from openai import OpenAI
# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()
# OpenRouter answers the OpenAI API, so the OpenAI SDK talks to it.
openrouter = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
)
def answer(user_id: str, prompt: str) -> str:
try:
with limitry.reserve(
subject={"kind": "user", "id": user_id}, action="ai-call", cost=5
) as reservation:
completion = openrouter.chat.completions.create(
model="anthropic/claude-sonnet-5.5",
messages=[{"role": "user", "content": prompt}],
user=user_id,
)
# OpenRouter adds what the request cost to its usage, in US dollars.
cost = getattr(completion.usage, "cost", None)
if cost is not None:
reservation.cost = math.ceil(cost * 100)
return completion.choices[0].message.content or ""
except LimitReachedError:
return "You've used this month's AI allowance. It resets on the 1st."
```
The `user` field sends your user’s id to OpenRouter too, so both tools name the same person.
To count small requests more finely, count the budget in hundredths of a cent. A $2 budget is then 20,000, and the commit is `Math.ceil(usage.cost * 10_000)`.
## What you see
[Section titled “What you see”](#what-you-see)
* A request that costs $0.0123 commits 2 cents, and the user’s budget shows 198 cents left.
* On the [Usage](/docs/usage/) page, each user’s spend this month, in the cents OpenRouter charged.
* A user over budget gets your message straight away. The request never reaches OpenRouter, so it costs you nothing.
Related: [Reservations](/docs/reservations/), [Warn your users before they hit a limit](/docs/guides/warn-users/).
# Use Limitry with Stripe
> Let a customer's Stripe plan set their limits, sell credits with Stripe Checkout, and bill usage through Stripe meters.
Stripe takes the payments and Limitry does the counting. This guide covers the three ways the two meet:
1. A customer’s plan decides their limits.
2. Customers buy credits with Stripe Checkout, and a refund takes them back.
3. You bill for usage, and Stripe’s meters get each unit exactly once.
The examples use Node with the `stripe` package and the [Limitry SDK](/docs/typescript/), and a team as the subject. Your webhook handler checks Stripe’s signature first, as Stripe’s docs describe.
## Before you start: the webhook endpoint
[Section titled “Before you start: the webhook endpoint”](#before-you-start-the-webhook-endpoint)
In Stripe, open **Workbench → Webhooks** and click **Create an event destination**. Choose the **Snapshot** payload, because these handlers read the event’s `data.object`. Then add your endpoint’s URL, and copy its signing secret for the handler.
## Before you start: two things every handler does
[Section titled “Before you start: two things every handler does”](#before-you-start-two-things-every-handler-does)
**Pick the environment from the event.** Stripe’s test mode and live mode match Limitry’s test and live. Keep a Limitry key for each, and choose by the event’s `livemode`:
* TypeScript
```ts
import { createClient } from "@limitry/sdk";
const limitry = {
live: createClient({ apiKey: process.env.LIMITRY_LIVE_KEY! }),
test: createClient({ apiKey: process.env.LIMITRY_TEST_KEY! }),
};
const apiFor = (event: Stripe.Event) =>
event.livemode ? limitry.live : limitry.test;
```
* Python
```python
import os
import stripe
from limitry import Limitry
limitry = {
"live": Limitry(api_key=os.environ["LIMITRY_LIVE_KEY"]),
"test": Limitry(api_key=os.environ["LIMITRY_TEST_KEY"]),
}
def api_for(event) -> Limitry:
return limitry["live"] if event.livemode else limitry["test"]
```
**Expect the same event twice, and events out of order.** Stripe redelivers events for up to three days and doesn’t promise their order. Each section below says how its handler stays correct either way.
## 1. The plan decides the limits
[Section titled “1. The plan decides the limits”](#1-the-plan-decides-the-limits)
To give a bigger plan more, give each plan its own subject kind, such as `team-free` and `team-pro`, with its own limits. To give one team more than its plan allows, add a limit for that team alone. It replaces the plan’s limit that has the same action and window.
Then store each team’s plan, and send that kind in every check.
* TypeScript
```ts
await limitry.live.guard(
{
subject: { kind: `team-${team.plan}`, id: team.id },
action: "report",
},
() => buildReport(params),
);
```
* Python
```python
with limitry["live"].guard(
subject={"kind": f"team-{team.plan}", "id": team.id}, action="report"
):
report = build_report(params)
```
Keep the plan up to date from the subscription events. Don’t trust the order they arrive in: fetch the subscription again and store what it says now. A late or repeated event then does no harm.
* TypeScript
```ts
const PLAN_BY_PRICE: Record = {
pro_monthly: "pro",
pro_annual: "pro",
};
async function onSubscriptionEvent(event: Stripe.Event) {
const { id } = event.data.object as Stripe.Subscription;
const subscription = await stripe.subscriptions.retrieve(id);
const team = await teams.byStripeCustomer(subscription.customer as string);
const paying = ["active", "trialing", "past_due"].includes(
subscription.status,
);
const lookupKey = subscription.items.data[0]?.price.lookup_key ?? "";
await teams.setPlan(
team.id,
paying ? (PLAN_BY_PRICE[lookupKey] ?? "free") : "free",
);
}
// customer.subscription.created, .updated and .deleted
```
* Python
```python
PLAN_BY_PRICE = {"pro_monthly": "pro", "pro_annual": "pro"}
def on_subscription_event(event) -> None:
subscription = stripe.Subscription.retrieve(event.data.object.id)
team = teams.by_stripe_customer(subscription.customer)
paying = subscription.status in ("active", "trialing", "past_due")
lookup_key = subscription["items"].data[0].price.lookup_key or ""
teams.set_plan(team.id, PLAN_BY_PRICE.get(lookup_key, "free") if paying else "free")
# customer.subscription.created, .updated and .deleted
```
What this does in each case:
* **Upgrade or downgrade:** the next check uses the new plan’s limits.
* **Trial:** a `trialing` subscription counts as the plan.
* **Failed payment:** Stripe retries while the subscription is `past_due`, and the team keeps its plan. To cut them off sooner, leave `past_due` out of the list.
* **Cancellation:** a `canceled` or `unpaid` subscription drops the team to `free`.
Each plan’s kind keeps its own count. A team that upgrades mid-month starts the Pro window at zero. A team that moves back to Free finds its Free count where it left it.
### Reset on the billing date
[Section titled “Reset on the billing date”](#reset-on-the-billing-date)
Stripe bills from the day a subscription starts, not on the 1st. To reset a team’s allowance on its billing day, give the plan’s limits `start: "billing_date"` (see [When limits reset](/docs/resets/)), and set the team’s billing date from the subscription in the same handler:
* TypeScript
```ts
async function setBillingDate(
event: Stripe.Event,
subscription: Stripe.Subscription,
team: { id: string; plan: string },
) {
// Stripe's billing_cycle_anchor is in seconds.
await apiFor(event).subjects.update(`team-${team.plan}`, team.id, {
billingAnchorAt: new Date(
subscription.billing_cycle_anchor * 1000,
).toISOString(),
});
}
```
* Python
```python
from datetime import datetime, timezone
def set_billing_date(event, subscription, team) -> None:
# Stripe's billing_cycle_anchor is in seconds.
anchor = datetime.fromtimestamp(subscription.billing_cycle_anchor, tz=timezone.utc)
api_for(event).subjects.update(
f"team-{team.plan}", team.id, billing_anchor_at=anchor.isoformat()
)
```
An annual plan’s monthly allowance then resets on the same day every month, and a new subscription starts a new period. Without a billing date, a team’s first check sets it.
To match a Stripe customer to a team, store the customer id on the team when you create the customer. Put the team’s id in the customer’s `metadata` too, so you can find it from either side.
Stripe’s own Entitlements say which features a plan includes. Limitry says how much of them a team can use. You can use both: decide the subject kind from the team’s entitlements instead of the price.
## 2. Credits from Stripe Checkout
[Section titled “2. Credits from Stripe Checkout”](#2-credits-from-stripe-checkout)
Make a balance, a limit with the window `total`, as in [Sell prepaid credits](/docs/guides/prepaid-credits/). When you create the Checkout Session, record what it sells:
* TypeScript
```ts
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: [{ price: "price_credits_5000", quantity: 1 }],
client_reference_id: team.id,
metadata: { credits: "5000" },
success_url: "https://example.com/billing?paid=1",
});
```
* Python
```python
session = stripe.checkout.Session.create(
mode="payment",
line_items=[{"price": "price_credits_5000", "quantity": 1}],
client_reference_id=team.id,
metadata={"credits": "5000"},
success_url="https://example.com/billing?paid=1",
)
```
When the payment succeeds, add the credits. The session’s id is the idempotency key, so a repeated event adds nothing:
* TypeScript
```ts
async function onCheckoutPaid(event: Stripe.Event) {
const session = event.data.object as Stripe.Checkout.Session;
if (session.payment_status !== "paid") return; // a delayed method: wait
const credits = Number(session.metadata?.credits);
await purchases.record({
paymentIntent: session.payment_intent as string,
teamId: session.client_reference_id!,
credits,
amountPaid: session.amount_total!,
});
await apiFor(event).limits.credits.create(
BALANCE_ID,
{
subject: { kind: "team", id: session.client_reference_id! },
amount: credits,
note: `Checkout ${session.id}`,
},
{ idempotencyKey: session.id },
);
}
// checkout.session.completed, and checkout.session.async_payment_succeeded
// for payment methods that settle later
```
* Python
```python
def on_checkout_paid(event) -> None:
session = event.data.object
if session.payment_status != "paid":
return # a delayed method: wait
credits = int(session.metadata["credits"])
purchases.record(
payment_intent=session.payment_intent,
team_id=session.client_reference_id,
credits=credits,
amount_paid=session.amount_total,
)
api_for(event).limits.credits.create(
BALANCE_ID,
subject={"kind": "team", "id": session.client_reference_id},
amount=credits,
note=f"Checkout {session.id}",
idempotency_key=session.id,
)
# checkout.session.completed, and checkout.session.async_payment_succeeded
# for payment methods that settle later
```
### A refund takes credits back
[Section titled “A refund takes credits back”](#a-refund-takes-credits-back)
A negative amount takes credits back. For a partial refund, take back the same share of the credits:
* TypeScript
```ts
async function onRefund(event: Stripe.Event) {
const refund = event.data.object as Stripe.Refund;
const purchase = await purchases.byPaymentIntent(
refund.payment_intent as string,
);
const credits = Math.round(
(purchase.credits * refund.amount) / purchase.amountPaid,
);
await apiFor(event).limits.credits.create(
BALANCE_ID,
{
subject: { kind: "team", id: purchase.teamId },
amount: -credits,
note: `Refund ${refund.id}`,
},
{ idempotencyKey: refund.id },
);
}
// refund.created
```
* Python
```python
def on_refund(event) -> None:
refund = event.data.object
purchase = purchases.by_payment_intent(refund.payment_intent)
credits = round(purchase.credits * refund.amount / purchase.amount_paid)
api_for(event).limits.credits.create(
BALANCE_ID,
subject={"kind": "team", "id": purchase.team_id},
amount=-credits,
note=f"Refund {refund.id}",
idempotency_key=refund.id,
)
# refund.created
```
A chargeback works the same way: on `charge.dispute.created`, take back the credits for `dispute.amount`, with the dispute’s id as the key. If you win the dispute (`charge.dispute.closed` with the status `won`), add them again with a new key.
If the team already spent the credits, the balance goes below zero. Their checks are then refused until they buy more.
### Repeats after a day
[Section titled “Repeats after a day”](#repeats-after-a-day)
Limitry never forgets a credit’s idempotency key. A checkout or refund event that Stripe redelivers days later adds or takes back nothing. Other writes keep their key for 24 hours, but Stripe can redeliver an event for up to three days. Record the session, refund or dispute ids you’ve handled in your database, and skip an event whose id you’ve seen.
## 3. Bill usage through Stripe meters
[Section titled “3. Bill usage through Stripe meters”](#3-bill-usage-through-stripe-meters)
When you charge per unit, Limitry has already counted every unit at the check. Send that count to a Stripe meter instead of counting a second time in your own code.
Once an hour, for each team, read the hours that have finished, and send each one as a meter event:
* TypeScript
```ts
const HOUR = 3_600_000;
async function sendUsage(team: Team) {
// Hours are final about a minute after they end; wait five.
const until = Math.floor((Date.now() - 5 * 60_000) / HOUR) * HOUR;
const from = team.usageSentUntil; // where the last run stopped
if (from >= until) return;
const series = await limitry.live.usage.query({
limitId: METERED_LIMIT_ID,
subject: `team:${team.id}`,
granularity: "hour",
from: new Date(from).toISOString(),
to: new Date(until - 1).toISOString(),
});
let carry = team.usageCarry; // units given back in an earlier hour
for (const point of series.points) {
const value = point.used + carry;
carry = Math.min(0, value);
if (value <= 0) continue;
await stripe.billing.meterEvents.create({
event_name: "reports",
payload: {
stripe_customer_id: team.stripeCustomerId,
value: String(value),
},
identifier: `${team.id}:${point.start}`,
timestamp: Math.floor(Date.parse(point.start) / 1000),
});
}
await teams.saveUsageCursor(team.id, { sentUntil: until, carry });
}
```
* Python
```python
import time
from datetime import datetime, timezone
HOUR = 3600
def iso(seconds: float) -> str:
return datetime.fromtimestamp(seconds, tz=timezone.utc).isoformat()
def send_usage(team) -> None:
# Hours are final about a minute after they end; wait five.
until = int((time.time() - 5 * 60) // HOUR * HOUR)
start = team.usage_sent_until # where the last run stopped
if start >= until:
return
series = limitry["live"].usage.query(
limit_id=METERED_LIMIT_ID,
subject=f"team:{team.id}",
granularity="hour",
from_=iso(start),
to=iso(until - 1),
)
carry = team.usage_carry # units given back in an earlier hour
for point in series.points:
value = point.used + carry
carry = min(0, value)
if value <= 0:
continue
stripe.billing.MeterEvent.create(
event_name="reports",
payload={"stripe_customer_id": team.stripe_customer_id, "value": str(value)},
identifier=f"{team.id}:{point.start}",
timestamp=int(datetime.fromisoformat(point.start.replace("Z", "+00:00")).timestamp()),
)
teams.save_usage_cursor(team.id, sent_until=until, carry=carry)
```
Why this counts each unit once:
* **Each hour goes once.** The job stores where it stopped and starts there next time. If it fails part way, the next run sends those hours again, and Stripe drops a repeated `identifier`.
* **A finished hour doesn’t change.** Limitry records a reservation’s final cost in the hour it settles, never in an earlier hour.
* **Given-back units aren’t lost.** `used` is net: an hour in which reservations released more than they took can come out below zero. The job carries that into the next hour it sends, because a meter event can’t be negative.
Send from the live key only, so test checks never reach a live invoice. To try the job in Stripe’s test mode, run it once with your test key against a test customer.
Related: [Sell prepaid credits](/docs/guides/prepaid-credits/), [Test and live](/docs/test-and-live/), [Idempotency](/docs/idempotency/), [Usage and reports](/docs/usage/).
# Use Limitry with the Vercel AI SDK
> Add one language model middleware, and each of your users gets an AI budget across every model the AI SDK calls, streamed or not.
The AI SDK gives your product one interface for every model provider, and its middleware runs your code around each model call. One Limitry middleware gives each of your users a budget across every model they use. You add it once, and every `generateText` and `streamText` call stays within budget.
## 1. Create the budget
[Section titled “1. Create the budget”](#1-create-the-budget)
Create the 200-cent monthly budget from [Limit AI spend per user](/docs/guides/limit-ai-spend/#1-create-the-budget). It counts in cents, with the action `ai-call`.
## 2. Add the middleware
[Section titled “2. Add the middleware”](#2-add-the-middleware)
The middleware reserves a few cents before each model call, then commits what the call cost. A stream keeps its reservation open until its last part, which carries the usage.
```ts
import { createClient, type ReserveRequest } from "@limitry/sdk";
import type { LanguageModelMiddleware } from "ai";
// Uses the LIMITRY_API_KEY environment variable.
const limitry = createClient();
type Usage = {
inputTokens: { total: number | undefined };
outputTokens: { total: number | undefined };
};
// Your prices, in cents per million tokens.
const priceCents = (usage: Usage) =>
Math.ceil(
((usage.inputTokens.total ?? 0) * 300 +
(usage.outputTokens.total ?? 0) * 1500) /
1_000_000,
);
// Reserves before each model call and commits what the call cost.
export function aiBudget(
subject: ReserveRequest["subject"],
): LanguageModelMiddleware {
const request = { subject, action: "ai-call", cost: 5 };
return {
specificationVersion: "v4",
wrapGenerate: ({ doGenerate }) =>
limitry.reserve(request, async (reservation) => {
const result = await doGenerate();
reservation.cost(priceCents(result.usage));
return result;
}),
wrapStream: ({ doStream }) =>
new Promise((resolve, reject) => {
limitry
.reserve(request, async (reservation) => {
const { stream, ...rest } = await doStream();
await new Promise((finished) => {
const counted = stream.pipeThrough(
new TransformStream({
transform(part, controller) {
if (part.type === "finish") {
reservation.cost(priceCents(part.usage));
}
controller.enqueue(part);
},
flush: () => finished(),
}),
);
resolve({ ...rest, stream: counted });
});
})
.catch(reject);
}),
};
}
```
## 3. Wrap your model
[Section titled “3. Wrap your model”](#3-wrap-your-model)
Wrap the model with the user’s middleware, and call it as you always do:
```ts
import { openai } from "@ai-sdk/openai";
import { LimitReachedError } from "@limitry/sdk";
import { generateText, streamText, wrapLanguageModel } from "ai";
import { aiBudget } from "./ai-budget";
export async function answer(userId: string, prompt: string) {
const model = wrapLanguageModel({
model: openai("gpt-6.2-sol"),
middleware: aiBudget({ kind: "user", id: userId }),
});
try {
const { text } = await generateText({ model, prompt });
return text;
} catch (err) {
if (err instanceof LimitReachedError) {
return "You've used this month's AI allowance. It resets on the 1st.";
}
throw err;
}
}
export function streamAnswer(userId: string, prompt: string) {
const model = wrapLanguageModel({
model: openai("gpt-6.2-sol"),
middleware: aiBudget({ kind: "user", id: userId }),
});
return streamText({
model,
prompt,
onError: ({ error }) => {
if (error instanceof LimitReachedError) {
console.log(`${userId} has used this month's AI allowance.`);
}
},
});
}
```
`generateText` throws the `LimitReachedError`. `streamText` hands it to `onError` instead, before any text streams.
The middleware works with every provider the AI SDK supports. Swap `openai("gpt-6.2-sol")` for any other model, and the same budget covers it.
## What you see
[Section titled “What you see”](#what-you-see)
* A call that uses 10,000 input tokens and 2,000 output tokens commits 6 cents at these prices, streamed or not.
* On the [Usage](/docs/usage/) page, each user’s AI spend this month.
* A user over budget gets your message straight away. The model call never starts, so it costs you nothing.
Agents built on the AI SDK, such as Mastra’s, take the same wrapped model: see [Agent frameworks](/docs/works-with/agent-frameworks/#mastra).
Related: [Reservations](/docs/reservations/), [Show users where they stand](/docs/guides/show-usage/).