> ## Documentation Index
> Fetch the complete documentation index at: https://polar.sh/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Track usage

> Send usage events from your application and aggregate them with a meter.

> [!NOTE]
>
> **Why start here?** Events are the raw record of what customers do. Send them early and you'll have real usage data, whether you charge for it or not. See [Usage](https://polar.sh/docs/concepts/usage.md).

In this step you'll send events for an AI feature and create a meter that sums the tokens each customer uses.

The examples use the sandbox client from the [quickstart overview](https://polar.sh/docs/quickstart/overview.md#prerequisites), on API version `2026-10`.

## Send your first event

Send an event whenever a customer does something you want to measure, whether you'll bill for it, limit it or just track it. Identify the customer with your own user ID as `external_customer_id` (see [External IDs](https://polar.sh/docs/integrate/external-ids.md)):

```typescript TypeScript theme={null}
import { polar } from "./polar";

await polar.track({
  name: "ai_usage",
  external_customer_id: "user_123",
  metadata: {
    model: "gpt-4.1-nano",
    total_tokens: 77,
  },
});

await polar.flush();
```

```python Python theme={null}
import asyncio
import os

from polar.v2026_10 import PolarAsync


async def main() -> None:
    async with PolarAsync(os.environ["POLAR_ACCESS_TOKEN"], environment="sandbox") as polar:
        await polar.track(
            name="ai_usage",
            external_customer_id="user_123",
            metadata={
                "model": "gpt-4.1-nano",
                "total_tokens": 77,
            },
        )


asyncio.run(main())
```

```bash cURL theme={null}
curl -X POST https://sandbox-api.polar.sh/v1/events/ingest \
  -H "Authorization: Bearer $POLAR_ACCESS_TOKEN" \
  -H "Polar-Version: 2026-10" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [
      {
        "name": "ai_usage",
        "external_customer_id": "user_123",
        "metadata": { "model": "gpt-4.1-nano", "total_tokens": 77 }
      }
    ]
  }'
```

`track()` adds the event to the SDK's queue and returns. The SDK sends queued events in batches in the background. `flush()` waits until they're delivered, and in Python leaving the `async with` block does the same. In Python, `track()` is only on the async client, `PolarAsync`. See [Send events](https://polar.sh/docs/features/usage-based-billing/event-ingestion.md) for running the queue in a server or serverless function.

You don't need to create the customer first. Polar accepts the event now, and links it to the customer once one exists with `external_id` set to `user_123`. You'll do that in [step 3](https://polar.sh/docs/quickstart/checkout.md).

> [!TIP]
>
> Send raw facts, like the tokens used by one request, not running totals. Polar does the aggregation, so the same events can feed several meters later.

For LLM calls, streams and S3 uploads, an [ingestion strategy](https://polar.sh/docs/features/usage-based-billing/ingestion-strategies/ingestion-strategy.md) can send these events for you.

## Create a meter

A meter selects events with a filter and aggregates them into usage. Create one that sums `total_tokens` across `ai_usage` events:

> [tab] Dashboard
>
> * Open **Catalog → Meters**
> * Click **Create Meter**
> * Set **Name** to "AI tokens"
> * Under **Filters**, add a condition: **Name** equals `ai_usage`
> * Set **Aggregation** to **Sum** over the property `total_tokens`
> * Click **Create Meter**

> [tab] CLI
>
> ```bash theme={null}
> export POLAR_METER_ID=$(polar meters create --name "AI tokens" \
>   --filter '{"conjunction":"and","clauses":[{"property":"name","operator":"eq","value":"ai_usage"}]}' \
>   --aggregation '{"func":"sum","property":"total_tokens"}' | jq -r .id)
> ```
>
> See [`polar meters`](https://polar.sh/docs/integrate/cli/reference/meters).

> [tab] Prompt
>
> ```text Prompt theme={null}
> Create a meter called AI tokens in my Polar sandbox that sums total_tokens across ai_usage events.
> ```
>
> Uses the `meters_create` operation of the [Polar MCP server](https://polar.sh/docs/integrate/mcp.md).

> [tab] Pricing as Code Beta
>
> Turn on [Pricing as Code](https://polar.sh/docs/features/pricing-as-code/overview.md) for your sandbox organization. Read [Before you adopt](https://polar.sh/docs/features/pricing-as-code/overview.md#before-you-adopt) first: from now on, the config is the only way to change your catalog.
>
> ```bash theme={null}
> polar auth login --sandbox
> polar config init
> ```
>
> `init` writes `polar.config.ts` in a JavaScript or TypeScript project, and `polar.config.json` otherwise. Describe the `ai_usage` event, then add the meter under its external ID, `ai_tokens`:
>
> ```ts polar.config.ts theme={null}
> import { defineConfig } from '@polar-sh/config'
> import { z } from 'zod'
>
> export default defineConfig({
>   events: ({ event }) => ({
>     ai_usage: event(z.object({ model: z.string(), total_tokens: z.number() })),
>   }),
>   meters: ({ meter, events }) => ({
>     ai_tokens: meter('AI tokens').on(events.ai_usage).sum('total_tokens'),
>   }),
> })
> ```
>
> The event's key is its name, so the meter counts only `ai_usage` events. Summing a property the event doesn't have is a type error. The example uses Zod (`npm install zod`), but any [Standard Schema](https://standardschema.dev) validator works.
>
> Then save it as a draft and publish it:
>
> ```bash theme={null}
> polar config draft
> polar config publish
> ```
>
> See [Billing config](https://polar.sh/docs/integrate/cli/config.md) for the JSON format.

Metadata keys are used directly as properties, without a `metadata.` prefix.

Polar backfills a new meter from events you've already sent, so your first event counts.

Save the meter's ID as `POLAR_METER_ID` in your application's environment. You'll use it in [step 2](https://polar.sh/docs/quickstart/catalog.md) and to check balances in [step 4](https://polar.sh/docs/quickstart/webhooks.md). In the dashboard, open the **AI tokens** meter and click **Copy meter ID**. The CLI example exports it already.

> [!TIP]
>
> Using [Pricing as Code](https://polar.sh/docs/features/pricing-as-code/overview.md)? Skip this and refer to the meter by its external ID, `ai_tokens`. A Polar ID changes when a new [catalog version](https://polar.sh/docs/features/pricing-as-code/versioning.md) changes the meter, but the external ID stays the same across versions.

## Verify it works

Read the meter's usage for `user_123`. It includes the 77 tokens from your event.

> [tab] Dashboard
>
> * Open **Catalog → Meters**
> * Select **AI tokens**
> * Open the **Customers** tab to see usage per customer, or **Events** to see the event you sent

> [tab] CLI
>
> ```bash theme={null}
> polar meters quantities $POLAR_METER_ID --external-customer-id user_123 \
>   --start-timestamp 2026-11-01T00:00:00Z --end-timestamp 2026-12-01T00:00:00Z --interval month
> ```

> [tab] Prompt
>
> ```text Prompt theme={null}
> Show this month's usage of the AI tokens meter for customer user_123 in my Polar sandbox.
> ```
>
> Uses the `meters_quantities` operation of the [Polar MCP server](https://polar.sh/docs/integrate/mcp.md).

## Learn more

| Resource | Description |
| - | - |
| [Send events](https://polar.sh/docs/features/usage-based-billing/event-ingestion.md) | The event queue, duplicates, limits and backdated events |
| [Meters](https://polar.sh/docs/features/usage-based-billing/meters.md) | Filters, aggregations and units |
| [Cost insights](https://polar.sh/docs/features/cost-insights/introduction.md) | Track what each customer costs you on the same events |

> [card] [Next: Set up your catalog](https://polar.sh/docs/quickstart/catalog.md)
>
> Turn this meter into a price, and include credits in a plan.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.