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

# Create metrics

<div className="m-badge-page-wrapper">
  <Badge stroke color="orange" size="sm">Limited Release</Badge>
</div>

A metric defines how to aggregate event data and calculate billable usage. An event is an action your customer performs while using your system, such as placing an API call.

Metrics connect the following:

* <a href="/limited-release/usage-based-billing/set-up-billing-process/create-pricing-plans" target="_blank" rel="noopener noreferrer">Pricing plans</a> that apply pricing models to metric usage for calculating charges.
* <a href="/limited-release/usage-based-billing/meter-bill/record-metric-usage" target="_blank" rel="noopener noreferrer">Usage events</a> that the metric aggregates to determine billable consumption.

## 1. Decide the event to track

Before you create metrics, choose which event you want to track and the event details (event properties) you require.

For most aggregation methods, you need to include the event property name in the API call to create metrics.

## 2. Decide the metric type

Based on your business use case, decide on one of the following metric types:

* **Metered metric**: Customers are charged based on exactly how much of a feature they use within a specific billing period. The usage resets to zero each cycle and customers pay only for what they use in that period. For example, a metric that calculates usage based on the number of API calls placed in a month.
* **Recurring metric**: Customers are charged for usage that persists across billing periods. The usage accumulates or remains steady until modified. For example, a metric that calculates usage as the total storage space utilized.

You need to pass the metric type in the API call to create metrics.

## 3. Decide the aggregation type and aggregation field

Aggregation type determines how the metric aggregates event data and calculates usage. Based on your business use case, choose an aggregation type from the following.

| Aggregation type | Description                                | Use case                                                                            |
| ---------------- | ------------------------------------------ | ----------------------------------------------------------------------------------- |
| `COUNT`          | Counts total items                         | When you need a simple total, like API calls or transactions.                       |
| `COUNT_DISTINCT` | Counts unique values in an events data set | When you want to track distinct users, devices, or IDs.                             |
| `SUM`            | Adds up values in a data set               | When you want a total amount, such as data usage or time spent.                     |
| `MAX`            | Finds the highest value in a data set      | When you need to know the peak value, like maximum storage or highest transaction.  |
| `LATEST`         | Uses the most recent value in a data set   | When only the current or last value matters, like current balance or latest status. |

<Note>
  Recurring metrics support only `SUM` and `COUNT_DISTINCT` aggregation types.
</Note>

You can track multiple properties of an event. Aggregation field specifies the specific property on which the selected aggregation type is applied. For example, an event for using data storage can contain properties such as `storage_gb` and `region`. You can set up a metric that aggregates `storage_gb` to determine billable usage. In this case, `storage_gb` is the aggregation field.

You need to pass the aggregation type in the API call to create metrics.

## 4. Create metrics

Use a <a href="/developer/how-to/api/get-started#2-get-an-access-token" target="_blank" rel="noopener noreferrer">valid access token</a> and make a POST call to the `/v1/commerce/billing/metrics` endpoint. Include the following parameters:

| <span style={{textAlign: 'left', display: 'block'}}>Parameter</span>                                                                                                                                                                                           | <span style={{textAlign: 'left', display: 'block'}}>Action</span>                                                                                                                                                                                                             |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`<br /><span style={{color: 'red', fontSize: 'smaller'}}>Required</span>, <span style={{color: '#95a5a6', fontSize: 'smaller'}}>string</span>                                                                                                             | Provide a descriptive name that identifies the metric's purpose.                                                                                                                                                                                                              |
| `code`<br /><span style={{color: 'red', fontSize: 'smaller'}}>Required</span>, <span style={{color: '#95a5a6', fontSize: 'smaller'}}>string</span>                                                                                                             | Set a unique code to identify this metric.                                                                                                                                                                                                                                    |
| `type`<br /><span style={{color: 'red', fontSize: 'smaller'}}>Required</span>, <span style={{color: '#95a5a6', fontSize: 'smaller'}}>string</span>                                                                                                             | Set to `METERED` to reset usage each billing period or `RECURRING` to accumulate usage.                                                                                                                                                                                       |
| `aggregation_type`<br /><span style={{color: 'red', fontSize: 'smaller'}}>Required</span>, <span style={{color: '#95a5a6', fontSize: 'smaller'}}>string</span>                                                                                                 | Choose the aggregation type based on your billing use case. See [Aggregation types](#3-decide-the-aggregation-type-and-aggregation-field) for more information.<br /><br /><b>Possible values:</b> `COUNT`, `COUNT_DISTINCT`, `SUM`, `MAX`, {/* `weighted_sum`, */} `LATEST`. |
| `aggregation_field`<br /><span style={{color: 'red', fontSize: 'smaller'}}>Required when `aggregation_type` is `SUM`, `COUNT_DISTINCT`, `MAX`, {/* `weighted_sum`, */} or `LATEST`</span>, <span style={{color: '#95a5a6', fontSize: 'smaller'}}>string</span> | Set to the event property name that contains the value to aggregate.                                                                                                                                                                                                          |
| `description`<br /><span style={{color: '#95a5a6', fontSize: 'smaller'}}>string</span>                                                                                                                                                                         | Provide additional details about what the metric measures.                                                                                                                                                                                                                    |
| `field_filters[]`<br /><span style={{color: '#95a5a6', fontSize: 'smaller'}}>array</span>                                                                                                                                                                      | Add filter objects to include only specific events. See [Field filters](#5-filter-aggregation-field-values) for more information.                                                                                                                                             |
| `field_filters[].key`<br /><span style={{color: 'red', fontSize: 'smaller'}}>Required when field\_filters\[] provided</span>, <span style={{color: '#95a5a6', fontSize: 'smaller'}}>string</span>                                                              | Set to the event property name to filter by.                                                                                                                                                                                                                                  |
| `field_filters[].values`<br /><span style={{color: 'red', fontSize: 'smaller'}}>Required when field\_filters\[] provided</span>, <span style={{color: '#95a5a6', fontSize: 'smaller'}}>array</span>                                                            | Provide an array of values to include in the metric calculation.                                                                                                                                                                                                              |

For information on all parameters, see <a href="/reference/api/rest/metrics/create-a-new-metric" target="_blank" rel="noopener noreferrer">API reference</a>.

<CodeGroup>
  ```shell lines title="Sample request" theme={null}
  curl -X POST -L 'https://api-m.sandbox.paypal.com/v1/commerce/billing/metrics' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Bearer <ACCESS-TOKEN>' \
  --data '{
      "name": "API Requests",
      "code": "api_requests",
      "type": "METERED",
      "description": "Measures the total number of API requests made",
      "aggregation_type": "COUNT",
      "field_filters": [
          {
              "key": "region",
              "values": [
                  "us-east-1",
                  "us-west-1",
                  "eu-west-1"
              ]
          }
      ]
  }'
  ```

  ```json lines title="Sample response" theme={null}
  {
      "id": "bm_01H2XT1G7N8E2JHJKBVPDS0TQD",
      "name": "API Requests",
      "code": "api_requests",
      "type": "METERED",
      "description": "Measures the total number of API requests made",
      "aggregation_type": "COUNT",
      "field_filters": [
          {
              "key": "region",
              "values": [
                  "us-east-1",
                  "us-west-1",
                  "eu-west-1"
              ]
          }
      ],
      "created_at": "2023-05-10T14:32:18Z"
  }
  ```
</CodeGroup>

A successful call returns a `201 Created` response. The response includes the following parameters:

| <span style={{textAlign: 'left', display: 'block'}}>Parameter</span>            | <span style={{textAlign: 'left', display: 'block'}}>Description</span> | <span style={{textAlign: 'left', display: 'block'}}>Further action</span>                                                                                                           |
| ------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`<br /><span style={{color: '#95a5a6', fontSize: 'smaller'}}>string</span>   | Unique identifier for the metric.                                      | Use this `id` when <a href="/limited-release/usage-based-billing/set-up-billing-process/create-pricing-plans" target="_blank" rel="noopener noreferrer">creating pricing plans</a>. |
| `code`<br /><span style={{color: '#95a5a6', fontSize: 'smaller'}}>string</span> | Unique code for the metric.                                            | Use this `code` when <a href="/limited-release/usage-based-billing/manage-entities/manage-metrics" target="_blank" rel="noopener noreferrer">managing the metric</a>.               |

For information on all parameters, see <a href="/reference/api/rest/metrics/create-a-new-metric" target="_blank" rel="noopener noreferrer">API reference</a>.

## 5. Filter aggregation field values

**Field filters** let you include only specific events or data in your metric calculation. The system only includes events that match all your filter rules.

For each filter, choose a property name (key) and the values you want to match.

Common ways to use filters and samples:

* **By region**: Track usage across different geographic locations.
* **By performance tier**: Separate different service levels.
* **By token type**: Distinguish between different AI processing types.
* **By feature**: Track premium vs standard features.
* **By status**: Count only successful operations.

<CodeGroup>
  ```shell lines title="By region: Database usage" theme={null}
  curl -X POST -L 'https://api-m.sandbox.paypal.com/v1/commerce/billing/metrics' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer <ACCESS-TOKEN>' \
  -d '{
    "name": "Database Usage - Europe",
    "code": "DB_USAGE_EU",
    "type": "METERED",
    "description": "Database storage usage in European regions",
    "aggregation_type": "SUM",
    "aggregation_field": "storage_gb",
    "field_filters": [
      {
        "key": "region",
        "values": ["europe", "africa"]
      }
    ]
  }'
  ```

  ```shell lines title="By GPU type: GPU time" theme={null}
  curl -X POST -L 'https://api-m.sandbox.paypal.com/v1/commerce/billing/metrics' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer <ACCESS-TOKEN>' \
  -d '{
    "name": "Premium GPU Time",
    "code": "GPU_TIME_PREMIUM",
    "type": "METERED",
    "description": "GPU compute time for premium GPU instances",
    "aggregation_type": "SUM",
    "aggregation_field": "compute_minutes",
    "field_filters": [
      {
        "key": "gpu_type",
        "values": ["standard_gpu", "premium_gpu"]
      }
    ]
  }'
  ```

  ```shell lines title="By token type: AI processing" theme={null}
  curl -X POST -L 'https://api-m.sandbox.paypal.com/v1/commerce/billing/metrics' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer <ACCESS-TOKEN>' \
  -d '{
    "name": "AI Input Tokens",
    "code": "AI_INPUT_TOKENS",
    "type": "METERED",
    "description": "AI tokens consumed for input and cached input processing",
    "aggregation_type": "SUM",
    "aggregation_field": "token_count",
    "field_filters": [
      {
        "key": "token_type",
        "values": ["input", "cached_input"]
      }
    ]
  }'
  ```

  ```shell lines title="By feature: Unique users" theme={null}
  curl -X POST -L 'https://api-m.sandbox.paypal.com/v1/commerce/billing/metrics' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer <ACCESS-TOKEN>' \
  -d '{
    "name": "Unique Premium Feature Users",
    "code": "UNIQUE_PREMIUM_USERS",
    "type": "METERED",
    "description": "Counts unique users accessing premium features",
    "aggregation_type": "COUNT_DISTINCT",
    "aggregation_field": "user_id",
    "field_filters": [
      {
        "key": "feature_tier",
        "values": ["premium", "enterprise"]
      }
    ]
  }'
  ```
</CodeGroup>

## 6. Manage metrics

You can update metric configurations when adjusting aggregation methods, modifying field filters, or changing metric descriptions. To review a metric's current configuration, call the <a href="/reference/api/rest/metrics/get-a-metric-by-code" target="_blank" rel="noopener noreferrer">Get metric details</a> endpoint.

| Metric attribute       | Updatable | Possible management options                                                                                                                                                                                          | Impact on existing plans                                   |
| ---------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| **Metric name**        | Yes       | <a href="/limited-release/usage-based-billing/manage-entities/manage-metrics#update-metric-details" target="_blank" rel="noopener noreferrer">Update metric details</a> - modify display name                        | No impact - display only                                   |
| **Metric description** | Yes       | <a href="/limited-release/usage-based-billing/manage-entities/manage-metrics#update-metric-details" target="_blank" rel="noopener noreferrer">Update metric details</a> - modify metric description                  | No impact - display only                                   |
| **Aggregation type**   | Yes       | <a href="/limited-release/usage-based-billing/manage-entities/manage-metrics#update-metric-details" target="_blank" rel="noopener noreferrer">Update metric details</a> - modify calculation method                  | Affects usage calculations for all plans using this metric |
| **Aggregation field**  | Yes       | <a href="/limited-release/usage-based-billing/manage-entities/manage-metrics#update-metric-details" target="_blank" rel="noopener noreferrer">Update metric details</a> - modify event property used for aggregation | Affects usage calculations for all plans using this metric |
| **Field filters**      | Yes       | <a href="/limited-release/usage-based-billing/manage-entities/manage-metrics#update-metric-details" target="_blank" rel="noopener noreferrer">Update metric details</a> - modify event filtering rules               | Affects which events count toward usage                    |
| **Metric code**        | No        | Metric cannot be modified - unique identifier remains permanent                                                                                                                                                      | N/A - cannot be modified                                   |
| **Metric type**        | No        | Metric cannot be modified - type (METERED or RECURRING) is permanent                                                                                                                                                 | N/A - cannot be modified                                   |
