# Quickstart: usage-based billing in a few minutes

> Install @formata/limitr, write a policy with two plans, and gate your first calls: feature flags, daily and monthly limits, and AI tokens billed past an allowance.

# Quickstart

## Install

<Tabs groupId="lang" queryString>
<TabItem value="typescript" label="TypeScript">

```bash
npm i @formata/limitr
```

</TabItem>
<TabItem value="python" label="Python">

```bash
pip install limitr
```

</TabItem>
</Tabs>

Limitr runs in Node, Bun, Deno, and the browser (TypeScript), and in Python 3.9 and later. The package includes the
engine, so there's nothing else to run.

## Your first policy and calls

Save this as `quickstart.mts` and run it with `npx tsx quickstart.mts` (or Bun or Deno), or the Python version as
`quickstart.py` and run it with `python quickstart.py`:

<Tabs groupId="lang" queryString>
<TabItem value="typescript" label="TypeScript">

```ts
// 1. The policy: what each plan includes, what it costs you, and what you charge.
const limitr = await Limitr.new(`
policy: {
    credits: {
        request: { label: 'API request' }
        ai_token: { label: 'AI token', price: { amount: 0.00002 }, overhead_cost: 0.000008 }
    }
    plans: {
        free: {
            default: true
            entitlements: {
                api: {
                    limit: {
                        credit: 'request', value: 1000
                        resets: true, reset_inc: 1day
                    }
                }
                chat: {
                    limit: {
                        credit: 'ai_token', value: 50_000
                        resets: true, reset_sch: 'monthly:1'
                    }
                }
            }
        }
        pro: {
            entitlements: {
                api: {
                    limit: {
                        credit: 'request', value: 100_000
                        resets: true, reset_sch: 'monthly:1'
                    }
                }
                chat: {
                    limit: {
                        credit: 'ai_token', mode: 'soft', value: 2_000_000
                        resets: true, reset_sch: 'monthly:1'
                    }
                }
                export_pdf: {}
            }
        }
    }
}`);

// 2. Events: bill overage as it happens.
limitr.addHandler('billing', (name, value) => {
    if (name === 'meter-overage') {
        const event = JSON.parse(value as string);
        console.log(`bill ${event.customer.id}: $${event.overage_price}`);
    }
});

// 3. Customers: created on first sight, on the default plan unless you say otherwise.
await limitr.ensureCustomer('ada');
await limitr.ensureCustomer('acme', 'pro');

// 4. Ask before doing anything that costs money.
console.log('ada, 1 API request:', await limitr.allow('ada', 'api', 1));
console.log('ada, PDF export:', await limitr.allow('ada', 'export_pdf'));
console.log('ada, 60k tokens:', await limitr.allow('ada', 'chat', 60_000));
console.log('acme, PDF export:', await limitr.allow('acme', 'export_pdf'));
console.log('acme, 2.1M tokens:', await limitr.allow('acme', 'chat', 2_100_000));
console.log('acme tokens left:', await limitr.remaining('acme', 'chat'));
```

It prints:

```text
ada, 1 API request: true
ada, PDF export: false
ada, 60k tokens: false
acme, PDF export: true
bill acme: $2
acme, 2.1M tokens: true
acme tokens left: -100000
```

</TabItem>
<TabItem value="python" label="Python">

```python
from limitr import Limitr

# 1. The policy: what each plan includes, what it costs you, and what you charge.
limitr = Limitr("""
policy: {
    credits: {
        request: { label: 'API request' }
        ai_token: { label: 'AI token', price: { amount: 0.00002 }, overhead_cost: 0.000008 }
    }
    plans: {
        free: {
            default: true
            entitlements: {
                api: {
                    limit: {
                        credit: 'request', value: 1000
                        resets: true, reset_inc: 1day
                    }
                }
                chat: {
                    limit: {
                        credit: 'ai_token', value: 50_000
                        resets: true, reset_sch: 'monthly:1'
                    }
                }
            }
        }
        pro: {
            entitlements: {
                api: {
                    limit: {
                        credit: 'request', value: 100_000
                        resets: true, reset_sch: 'monthly:1'
                    }
                }
                chat: {
                    limit: {
                        credit: 'ai_token', mode: 'soft', value: 2_000_000
                        resets: true, reset_sch: 'monthly:1'
                    }
                }
                export_pdf: {}
            }
        }
    }
}""")

# 2. Events: bill overage as it happens.
def billing(name, event):
    if name == 'meter-overage':
        print(f"bill {event['customer']['id']}: ${event['overage_price']:g}")
limitr.add_handler('billing', billing)

# 3. Customers: created on first sight, on the default plan unless you say otherwise.
limitr.ensure_customer('ada')
limitr.ensure_customer('acme', 'pro')

# 4. Ask before doing anything that costs money.
print('ada, 1 API request:', limitr.allow('ada', 'api', 1))
print('ada, PDF export:', limitr.allow('ada', 'export_pdf'))
print('ada, 60k tokens:', limitr.allow('ada', 'chat', 60_000))
print('acme, PDF export:', limitr.allow('acme', 'export_pdf'))
print('acme, 2.1M tokens:', limitr.allow('acme', 'chat', 2_100_000))
print('acme tokens left:', f"{limitr.remaining('acme', 'chat'):g}")
```

It prints:

```text
ada, 1 API request: True
ada, PDF export: False
ada, 60k tokens: False
acme, PDF export: True
bill acme: $2
acme, 2.1M tokens: True
acme tokens left: -100000
```

</TabItem>
</Tabs>

## What happened

- **The policy** has two credits (the things you count) and two plans. Each plan lists **entitlements**: what its
  customers can do. `export_pdf` has no limit, so it's a feature flag: Pro has it, Free doesn't. `api` and `chat`
  have limits that reset daily or monthly.
- **Ada** was created without a plan, so she's on the default plan (Free). Her PDF export was denied (not on her
  plan), and so was 60k tokens: Free's chat limit is hard, at 50,000 a month.
- **Acme** is on Pro, where chat is `soft`: the call went 100,000 tokens past the 2 million included, was allowed,
  and the overage was billed through the `meter-overage` event, at the credit's price ($20 per million).
- **`allow`** decides and, when the answer is yes, counts the usage. A denied call changes nothing. Unknown customers
  and entitlements are denied; nothing throws.

## In your app

Create the engine once when your server starts, and ask in one place, like a middleware:

<Tabs groupId="lang" queryString>
<TabItem value="typescript" label="TypeScript">

```ts title="limitr.ts" norun
export const limitr = await Limitr.new(readFileSync('./policy.stof', 'utf8'));

export async function gate(userId: string, entitlement: string, amount = 1): Promise<boolean> {
    await limitr.ensureCustomer(userId);
    return limitr.allow(userId, entitlement, amount);
}
```

</TabItem>
<TabItem value="python" label="Python">

```python title="limitr.py" norun
from pathlib import Path
from limitr import Limitr

limitr = Limitr(Path('policy.stof').read_text())

def gate(user_id: str, entitlement: str, amount: float = 1) -> bool:
    limitr.ensure_customer(user_id)
    return limitr.allow(user_id, entitlement, amount)
```

</TabItem>
</Tabs>

- **Keep one engine per process.** It holds customer state in memory, which is why calls are fast.
- **Save customer state** if you self-host: see [Save customer state](./how-to/save-customer-state). Or use
  [Limitr Cloud](./tutorial/going-to-cloud.md), where `Limitr.cloud({ token })` replaces `Limitr.new` and state is
  managed for you.
- **Await every call.** `if (limitr.allow(...))` without `await` is always true.

## Next

- [How Limitr works](./how-it-works): credits, plans, entitlements, customers, and how a call is decided.
- [AI calls: reserve and settle](./how-to/reserve-llm-calls): for calls whose size you only know afterwards.
- [Map your pricing](./how-to/map-your-pricing): turn your pricing page into a policy.
- [The tutorial](./tutorial/index.md): everything, one runnable chapter at a time.
