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

# How Orb works

> The building blocks of usage-based billing

Orb transforms customer activity into accurate invoices through a pipeline of five interconnected concepts. Understanding this flow is the foundation for building any billing model.

```
Events → Metrics → Prices → Subscriptions → Invoices
```

## Events: Recording customer activity

Everything starts with **events**—timestamped records of customer activity sent to Orb's ingestion API.

```json theme={null}
{
  "event_name": "api_call",
  "timestamp": "2024-03-15T14:30:00Z",
  "external_customer_id": "cust_123",
  "properties": {
    "endpoint": "/v1/generate",
    "tokens": 1500,
    "model": "gpt-4",
    "region": "us-east-1"
  }
}
```

Events are stored immutably in a columnar data store. They're never aggregated or mutated at ingestion time—this raw data becomes the source of truth for all billing calculations.

<Info>
  **Why immutability matters**: Traditional billing systems increment counters as events arrive. Once incremented, the original context is lost. Orb stores raw events, so you can always re-query with different logic, backfill late data, or audit any charge down to the specific events that generated it.
</Info>

## Metrics: Defining what to measure

A **metric** (also called a billable metric) is a query that transforms raw events into a billable quantity. Metrics define *what* you're measuring, separate from *how* you're pricing it.

| Metric type         | Use case                      | Example                                   |
| ------------------- | ----------------------------- | ----------------------------------------- |
| **COUNT**           | Count events matching filters | API calls, transactions                   |
| **SUM**             | Sum a numeric property        | Tokens consumed, bytes transferred        |
| **MAX**             | Peak value during the period  | Concurrent users, storage high-water mark |
| **COUNT(DISTINCT)** | Unique values                 | Monthly active users, unique sessions     |

A single event stream can power multiple metrics. The same API call event might contribute to:

* Total API calls (COUNT)
* Total tokens (SUM of `tokens` property)
* Calls by model (COUNT, grouped by `model` property)

Metrics are queries, not pre-computed aggregates. Define a new metric today and calculate it against historical events—no re-ingestion required.

## Prices: Configuring rates

A **price** defines how a metric quantity translates to a charge. Orb supports multiple pricing models:

| Model       | How it works                         | Example                                             |
| ----------- | ------------------------------------ | --------------------------------------------------- |
| **Unit**    | Fixed amount per unit                | \$0.01 per API call                                 |
| **Tiered**  | Rate changes at volume thresholds    | First 1,000 calls free, then \$0.005 each           |
| **Package** | Charge per bundle of units           | \$10 per 1,000 tokens (4 units used = 1,000 billed) |
| **Bulk**    | Volume determines rate for all units | Under 10K: \$0.02/unit; 10K+: \$0.01/unit for all   |

Prices also specify:

* **Cadence**: Monthly, quarterly, annual, or one-time
* **Timing**: In-advance (charge at period start) or in-arrears (charge at period end)
* **Currency**: The billing currency or a custom pricing unit

<Info>
  **Metric + Price separation**: The same metric can have different prices for different customers. A "tokens consumed" metric might be \$0.01/token for self-serve customers and \$0.005/token for enterprise contracts—same underlying measurement, different commercial terms.
</Info>

## Plans: Packaging prices together

A **plan** bundles prices into a product offering. Plans are templates that define the standard pricing for a customer segment.

A plan might include:

* A monthly platform fee (unit price, in-advance)
* API call charges (tiered price, in-arrears)
* Storage fees (unit price based on GB-hours, in-arrears)
* An annual commitment minimum

Plans are versioned. When you update pricing, existing subscriptions can stay on their current version or migrate to the new one—you control the timing and scope.

## Subscriptions: Connecting customers to plans

A **subscription** represents a customer's ongoing relationship with a plan. It specifies:

* Which customer
* Which plan (or plan version)
* Start date and optional end date
* Any customer-specific overrides (custom rates, additional discounts, negotiated minimums)

Subscriptions generate invoices according to the plan's billing cadence. A customer on a monthly plan receives an invoice each month; a customer on an annual plan with monthly charges receives monthly invoices within an annual term.

<Info>
  **Overrides without complexity**: When an enterprise customer negotiates a 20% discount, you don't create a custom plan. Apply the discount as an override on their subscription. They're still on the standard plan—with customer-specific terms layered on top.
</Info>

## Invoices: The output

An **invoice** is the billing document generated for a subscription's billing period. Orb calculates invoices by querying:

1. **Events** matching the customer and billing period
2. **Metrics** defined on the subscription's prices
3. **Prices** with their rates, tiers, and adjustments
4. **Subscription terms** including overrides and discounts

The result is a line-item breakdown showing exactly what the customer owes and why.

```
Invoice #INV-2024-0342
Customer: Acme Corp
Period: March 1-31, 2024

Platform fee (monthly)           $500.00
API calls (47,250 @ tiered)      $236.25
  - First 10,000 @ $0.00           $0.00
  - Next 37,250 @ $0.00635       $236.25
Storage (892 GB-hours @ $0.10)    $89.20
────────────────────────────────────────
Subtotal                         $825.45
Discount (Enterprise 15%)       -$123.82
────────────────────────────────────────
Total                            $701.63
```

Because invoices are calculated from raw events, they're fully auditable. Every line item traces to specific events and pricing rules.

## What makes this different

Traditional billing systems aggregate at ingestion time. Events increment counters; counters determine charges. This is efficient but inflexible—once aggregated, the raw data is gone.

Orb's query-based approach preserves raw events and calculates at billing time:

| Scenario             | Traditional system              | Orb                                               |
| -------------------- | ------------------------------- | ------------------------------------------------- |
| Late-arriving events | Lost or requires re-ingestion   | Automatically included in next calculation        |
| Pricing change       | Requires migration scripts      | Apply new prices, recalculate                     |
| Metric redefinition  | Impossible without re-ingestion | Query historical events with new logic            |
| Audit a charge       | Limited counter history         | Trace to specific events                          |
| Backdate a contract  | Manual adjustments              | Atomic recalculation with correct effective dates |

This architectural difference is why Orb can safely backdate changes, simulate pricing scenarios, and maintain complete audit trails—capabilities that are difficult or impossible in counter-based systems.

## Next steps

<CardGroup cols={2}>
  <Card title="Core concepts" icon="book" href="/core-concepts">
    Detailed reference for Events, Metrics, Plans, Subscriptions, and Invoices
  </Card>

  <Card title="Quickstart guide" icon="rocket" href="/quickstart-guide">
    Build your first usage-based billing workflow in 30 minutes
  </Card>

  <Card title="Query-based billing" icon="database" href="/architecture/query-based-billing">
    Deep dive into immutable events and deterministic queries
  </Card>

  <Card title="Diff-based engine" icon="code-compare" href="/architecture/billing-architecture">
    How safe backdating and migrations work
  </Card>
</CardGroup>
