# 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

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

| 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

`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

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

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

```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

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 <limit-id>`. Before you merge, run `limitry sync --dry-run` to list the limits a sync would archive.

## 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

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.
