# Usage-based billing, limits, and feature flags in your app

> Limitr is an open-source engine for usage-based billing, limits, and feature flags. One policy decides access, cost, and price on every call, in-process.

# Limitr

**Usage-based billing, limits, and feature flags that run inside your app, and belong to you like the rest of your code.**

Limitr is an open-source engine for usage-based pricing. It meters usage (API calls, AI tokens, seats, storage,
anything you count), enforces plans and limits, prices every call, and tells your code what to bill. One **policy**
holds all of it, and the **engine** that runs it lives in your process (Python, Node, Bun, Deno, or the browser), with
no service to run and no network call in the middle of a request.

This is the real engine, running in your browser:

export const example = {
    title: 'first-look.stof',
    temp: true,
    policyFormat: 'stof',
    policy: `
policy: {
    credits: {
        ai_token: {
            label: 'AI token'
            price: { amount: 0.00002 }      // you charge $20 per million tokens
            overhead_cost: 0.000008         // the model costs you $8 per million
        }
    }
    plans: {
        pro: {
            default: true
            entitlements: {
                export_pdf: {}                                  // a feature flag
                chat: { limit: { credit: 'ai_token', mode: 'soft', value: 100_000, resets: true, reset_sch: 'monthly:1' } }
            }
        }
    }
}`,
    stof: `
#[main]
fn main() {
    const limitr = self.policy;
    limitr.create_customer('ada');

    pln('export a PDF:', limitr.allow('ada', 'export_pdf'));
    pln('use SSO:', limitr.allow('ada', 'sso'));

    pln('80k tokens:', limitr.allow('ada', 'chat', 80_000));
    pln('40k more:', limitr.allow('ada', 'chat', 40_000));
    pln('used this month:', limitr.value('ada', 'chat'));
}

// Runs for every overage: what to bill, and what the call cost you.
#[meter-overage]
fn bill(event: obj) {
    pln(\`  bill ada \$\${event.overage_price} for \${event.overage} tokens (the call cost you \$\${event.meter.overhead_diff})\`);
}
`,
    typescript: `

const limitr = await Limitr.new(policy);
await limitr.ensureCustomer('ada');

limitr.addHandler('billing', (name, value) => {
    if (name !== 'meter-overage') return;
    const event = JSON.parse(value as string);
    console.log(\`  bill ada $\${event.overage_price} for \${event.overage} tokens (the call cost you $\${event.meter.overhead_diff})\`);
});

console.log('export a PDF:', await limitr.allow('ada', 'export_pdf'));
console.log('use SSO:', await limitr.allow('ada', 'sso'));

console.log('80k tokens:', await limitr.allow('ada', 'chat', 80_000));
console.log('40k more:', await limitr.allow('ada', 'chat', 40_000));
console.log('used this month:', await limitr.value('ada', 'chat'));
`,
    python: `
from limitr import Limitr

limitr = Limitr(policy)
limitr.ensure_customer('ada')

def billing(name, event):
    if name == 'meter-overage':
        print(f"  bill ada \${event['overage_price']:g} for {event['overage']:g} tokens (the call cost you \${event['meter']['overhead_diff']:g})")
limitr.add_handler('billing', billing)

print('export a PDF:', limitr.allow('ada', 'export_pdf'))
print('use SSO:', limitr.allow('ada', 'sso'))

print('80k tokens:', limitr.allow('ada', 'chat', 80_000))
print('40k more:', limitr.allow('ada', 'chat', 40_000))
print('used this month:', f"{limitr.value('ada', 'chat'):g}")
`,
};

<LimitrExample {...example} />

That's a plan with a feature flag and a monthly AI token allowance: the first 100,000 tokens are included, and the
rest are billed, with the margin of every call known as it happens. The Stof tab is what runs here; the TypeScript and
Python tabs are the same program with each SDK.

## Why it's different

Pricing is part of your product. Every business has its own units, costs, and deals, and a billing service outside
your app can only bend so far. That's why so many teams end up building it themselves.

Limitr gives you that control without the build. The engine is yours, like your code:

- **Inside your app.** Every check runs in your process, with no network call.
- **Shaped to your business.** Plans, prices, costs, limits, and every customer's deal in one policy document.
- **Extends like code.** Your own pricing functions, feature conditions, rules, and tools run in the policy, written
  in [Stof](https://stof.dev). See [Extend Limitr](./how-to/extend-limitr).
- **Margin on every call.** Every call is checked before the work runs, and priced at what you charge and what it
  costs you.

With Limitr Cloud or without it, it's the same engine, and it's still yours.

## What you can build with it

- **Any pricing model in one policy:** usage-based, seats, credits, flat plans, or a hybrid, per plan and per
  feature. See [Map your pricing](./how-to/map-your-pricing).
- **AI features that stay profitable:** [per-model costs](./how-to/ai-token-costs), per-call margins,
  [usage predicted before the call](./how-to/reserve-llm-calls), and [spend caps](./how-to/budgets).
- **Feature flags and rollouts:** [kill switches, percentage rollouts, and rules per call](./how-to/feature-flags),
  next to the plans, with events to measure them.
- **Custom deals and contracts:** [give one customer a feature](./how-to/custom-deals) their plan doesn't have,
  take one away, or change their limits, with expiry. For a deal many customers sign, write it once as a
  [rule](./how-to/custom-deals#one-deal-for-many-customers).
- **Prepaid credits:** [credit packs](./how-to/prepaid-credits) with expiry, resets, and rollover, spent across
  features at their own rates.
- **Org budgets and seats:** [seats](./how-to/seats) and [budgets](./how-to/budgets) shared by every user in a team
  or org.
- **Rate limits next to paid usage:** [protect your infrastructure](./how-to/rate-limits) without touching what
  customers pay for.
- **Billing events:** overage, limits hit, and thresholds crossed, sent to your code as they happen. See
  [Bill from events](./how-to/bill-from-events).
- **Your own rules and tools:** functions and [capabilities](./reference/capabilities) in the policy that your app,
  your services, and AI agents can run, including ones that load data from your APIs.

## Made for AI coding agents

The easiest way to write a policy and integrate Limitr, including the screens that show customers their usage, is
with your coding agent and the Limitr skills:

- **`limitr`**: the policy reference, every engine function, and every event.
- **`limitr-ts`**: the TypeScript SDK, including connecting to Limitr Cloud.
- **`limitr-py`**: the Python SDK, the same for Python.
- **`stof`**: the language policies are written in.

In Claude Code, add them as a plugin:

```text
/plugin marketplace add dev-formata-io/limitr
/plugin install limitr@limitr
```

For any other agent, they ship in the npm packages: point your agent at `node_modules/@formata/limitr/skill/` (the
Limitr skills) and `node_modules/@formata/stof/skill/` (the Stof language skill, which comes with Stof). In a Python
project, use the zips below. Then ask for what you need (Ex. "gate the chat endpoint with Limitr and settle the real token count", or "add a
usage meter to the account page from the customer's remaining credit"), and your agent writes, reviews, and debugs
policies and integrations the way Limitr works, instead of guessing. They're also packaged as zips in the repo's
[`content/`](https://github.com/dev-formata-io/limitr/tree/main/content) folder for uploading to an agent, and this
whole site is available to agents at [`/llms.txt`](pathname:///llms.txt).

## Open source and Limitr Cloud

These docs cover the **open-source engine** and integrating it. The engine is
[open source](https://github.com/dev-formata-io/limitr) (Apache 2.0) and free to run on your own: keep the policy in
your repo, save customer state in your database, and bill from the events.

[Limitr Cloud](https://limitr.dev) runs the same engine with the parts around it: Limitr Analyst, an agent that
writes and tests your policy, puts a signed contract in place from the order form, and charts your customers, usage,
and margin; versioned policies you publish to every running server without a deploy; customers kept for you; ledgers,
invoices through your own Stripe, and accounts billed as one; contracts with fees and commitments; and analytics
across your customers. Moving to Cloud is one line, `Limitr.cloud({ token })` instead of
`Limitr.new(policy)`, and every check still runs in your process. User guides for the Cloud app are under
[Guides](/guides/cloud/quickstart).

## Where to start

- **[Quickstart](./quickstart)**: install, write a policy, and gate your first call, in a few minutes.
- **[How Limitr works](./how-it-works)**: the pieces of a policy and how a call is decided.
- **[Tutorial](./tutorial/index.md)**: 15 short chapters, each one a program you can run, from a first policy to AI
  calls, org budgets, and feature flags.
- **[How-to guides](./how-to/map-your-pricing)**: recipes for common pricing problems.
- **[Reference](./reference/policy)**: every policy field, engine function, SDK method, and event.
- **[Live demo](./demo)**: watch the engine allow, deny, and price usage as you change the policy.

## Where the engine comes from

*CJ Cummings, co-founder and CEO*

Before Limitr, we were building an AI product that was usage-heavy, and monetizing it became a real limiting factor
in our ability to become profitable and ship features at the pace our market demanded.

Nothing on the market gave us the fine-grained visibility and control that AI and modern usage-based pricing actually
need, and every pricing change came with a growing product and engineering overhead.

The vision I had was a config document to define packaging, prices, credits, token limits, overhead costs, and
everything that's needed for reasonable and dynamic decisions about what every user and agent can do, how much usage
they get at every moment, and what it should cost them (and us). Easy to reason about, and quick to change.

I'd already built Stof (the runtime under Limitr) for a different reason, a smart AI context layer, out of a
background in graphics, parametric file formats, and language runtimes. It enables us to put usage control logic
directly into each config, and sandbox it to the local config that contains it. Customer state and all of the rules
that dictate it are isolated, local, extensible, and yours, forever.

Many iterations and projects later, that pricing-as-config is what became Limitr. And it's the single config that
enables us and all of our users to monetize, control, and analyze usage across every product and customer.

The vision has expanded, but our mission remains the same: to provide flexible, reliable, and secure usage
infrastructure for profitable software products, the teams behind those products, and the users of those products.

If this resonates, [book a call](https://calendly.com/d/ctjd-5gm-qqc/limitr-demo-with-founders). I'd love to hear how
it's going for you.
