Class: MetronomeSDK::Resources::V1::Usage
- Inherits:
-
Object
- Object
- MetronomeSDK::Resources::V1::Usage
- Defined in:
- lib/metronome_sdk/resources/v1/usage.rb,
sig/metronome_sdk/resources/v1/usage.rbs
Overview
Usage events are the basis for billable metrics. Use these endpoints to send usage events to Metronome and retrieve aggregated event data.
Instance Method Summary collapse
-
#ingest(usage: nil, request_options: {}) ⇒ nil
The ingest endpoint is the primary method for sending usage events to Metronome, serving as the foundation for all billing calculations in your usage-based pricing model.
-
#initialize(client:) ⇒ Usage
constructor
private
A new instance of Usage.
-
#list(ending_before:, starting_on:, window_size:, next_page: nil, billable_metrics: nil, customer_ids: nil, request_options: {}) ⇒ MetronomeSDK::Internal::CursorPageWithoutLimit<MetronomeSDK::Models::V1::UsageListResponse>
Some parameter documentations has been truncated, see Models::V1::UsageListParams for more details.
-
#list_with_groups(billable_metric_id:, customer_id:, window_size:, limit: nil, next_page: nil, current_period: nil, ending_before: nil, group_by: nil, group_filters: nil, group_key: nil, starting_on: nil, request_options: {}) ⇒ MetronomeSDK::Internal::CursorPage<MetronomeSDK::Models::V1::UsageListWithGroupsResponse>
Some parameter documentations has been truncated, see Models::V1::UsageListWithGroupsParams for more details.
-
#search(transaction_ids:, request_options: {}) ⇒ Array<MetronomeSDK::Models::V1::UsageSearchResponseItem>
This endpoint retrieves events by transaction ID for events that occurred within the last 34 days.
Constructor Details
#initialize(client:) ⇒ Usage
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns a new instance of Usage.
352 353 354 |
# File 'lib/metronome_sdk/resources/v1/usage.rb', line 352 def initialize(client:) @client = client end |
Instance Method Details
#ingest(usage: nil, request_options: {}) ⇒ nil
The ingest endpoint is the primary method for sending usage events to Metronome, serving as the foundation for all billing calculations in your usage-based pricing model. This high-throughput endpoint is designed for real-time streaming ingestion, supports backdating 34 days, and is built to handle mission-critical usage data with enterprise-grade reliability. Metronome supports 100,000 events per second without requiring pre-aggregation or rollups and can scale up from there. See the Send usage events guide to learn more about usage events.
Use this endpoint to:
Create a customer usage pipeline into Metronome that drives billable metrics, credit drawdown, and invoicing. Track customer behavior, resource consumption, and feature usage
What happens when you send events:
- Events are validated and processed in real-time
- Events are matched to customers using customer IDs or customer ingest aliases
- Events are matched to billable metrics and are immediately available for usage and spend calculations
Usage guidelines:
- Historical events can be backdated up to 34 days and will immediately impact live customer spend
- Duplicate events are automatically detected and ignored (34-day deduplication window)
Event structure:
Usage events are simple JSON objects designed for flexibility and ease of integration:
{
"transaction_id": "2021-01-01T00:00:00Z_cluster42",
"customer_id": "team@example.com",
"event_type": "api_request",
"timestamp": "2021-01-01T00:00:00Z",
"properties": {
"endpoint": "/v1/users",
"method": "POST",
"response_time_ms": 45,
"region": "us-west-2"
}
}
Learn more about usage event structure definitions.
Transaction ID
The transaction_id serves as your idempotency key, ensuring events are processed exactly once. Metronome maintains a 34-day deduplication window - significantly longer than typical 12-hour windows - enabling robust backfill scenarios without duplicate billing.
- Best Practices:
- Use UUIDs for one-time events: uuid4()
- For heartbeat events, use deterministic IDs
- Include enough context to avoid collisions across different event sources
Customer ID
Identifies which customer should be billed for this usage. Supports two identification methods:
- Metronome Customer ID: The UUID returned when creating a customer
- Ingest Alias: Your system's identifier (email, account number, etc.)
Ingest aliases enable seamless integration without requiring ID mapping, and customers can have multiple aliases for flexibility.
Event Type:
Categorizes the event type for billable metric matching. Choose descriptive names that aligns with the product surface area.
Properties:
Flexible metadata also used to match billable metrics or to be used to serve as group keys to create multiple pricing dimensions or breakdown costs by novel properties for end customers or internal finance teams measuring underlying COGs.
176 177 178 179 180 181 182 183 184 185 |
# File 'lib/metronome_sdk/resources/v1/usage.rb', line 176 def ingest(params = {}) parsed, = MetronomeSDK::V1::UsageIngestParams.dump_request(params) @client.request( method: :post, path: "v1/ingest", body: parsed[:usage], model: NilClass, options: ) end |
#list(ending_before:, starting_on:, window_size:, next_page: nil, billable_metrics: nil, customer_ids: nil, request_options: {}) ⇒ MetronomeSDK::Internal::CursorPageWithoutLimit<MetronomeSDK::Models::V1::UsageListResponse>
Some parameter documentations has been truncated, see Models::V1::UsageListParams for more details.
Retrieve aggregated usage data across multiple customers and billable metrics in a single query. This batch endpoint enables you to fetch usage patterns at scale, broken down by time windows, making it ideal for building analytics dashboards, generating reports, and monitoring platform-wide usage trends.
Use this endpoint to:
- Generate platform-wide usage reports for internal teams
- Monitor aggregate usage trends across your entire customer base
- Create comparative usage analyses between customers or time periods
- Support capacity planning with historical usage patterns
Key response fields:
An array of UsageBatchAggregate objects containing:
customer_id: The customer this usage belongs tobillable_metric_idandbillable_metric_name: What was measuredstart_timestampandend_timestamp: Time window for this data pointvalue: Aggregated usage amount for the periodgroups(optional): Usage broken down by group keys with valuesnext_page: Pagination cursor for large result sets
Usage guidelines:
- Time windows: Set
window_sizetohour,day, ornone(entire period) - Required parameters: Must specify
starting_on,ending_before, andwindow_size - Filtering options:
customer_ids: Limit to specific customers (omit for all customers)billable_metrics: Limit to specific metrics (omit for all metrics)
- Pagination: Use
next_pagecursor to retrieve large datasets - Null values: Group values may be null when no usage matches that group
66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/metronome_sdk/resources/v1/usage.rb', line 66 def list(params) query_params = [:next_page] parsed, = MetronomeSDK::V1::UsageListParams.dump_request(params) query = MetronomeSDK::Internal::Util.encode_query_params(parsed.slice(*query_params)) @client.request( method: :post, path: "v1/usage", query: query, body: parsed.except(*query_params), page: MetronomeSDK::Internal::CursorPageWithoutLimit, model: MetronomeSDK::Models::V1::UsageListResponse, options: ) end |
#list_with_groups(billable_metric_id:, customer_id:, window_size:, limit: nil, next_page: nil, current_period: nil, ending_before: nil, group_by: nil, group_filters: nil, group_key: nil, starting_on: nil, request_options: {}) ⇒ MetronomeSDK::Internal::CursorPage<MetronomeSDK::Models::V1::UsageListWithGroupsResponse>
Some parameter documentations has been truncated, see Models::V1::UsageListWithGroupsParams for more details.
Retrieve granular usage data for a specific customer and billable metric, with the ability to break down usage by custom grouping dimensions. This endpoint enables deep usage analytics by segmenting data across attributes like region, user, model type, or any custom dimension defined in your billable metrics.
Use this endpoint to:
- Analyze usage patterns broken down by specific attributes (region, user, department, etc.)
- Build detailed usage dashboards with dimensional filtering
- Identify high-usage segments for optimization opportunities
Request parameters
Use group_key and group_filters to
group by one or more dimensions. This is required for compound group keys and
recommended for all new integrations:
{
"group_key": ["region", "team"],
"group_filters": {
"region": ["US-East", "US-West"]
}
}
Important: For compound group keys, you must pass the complete set of keys that
make up the compound key. Partial key combinations are not supported. For
example, if your billable metric has a compound group key [region, team,
environment], you must pass all three keys in group_key—you cannot pass just
[region] or [region, team].
Key response fields:
An array of PagedUsageAggregate objects containing:
starting_onandending_before: Time window boundaries-
group: Object mapping group keys to their values- For simple groups, this will be a map with a single key-value pair (e.g.,
{"region": "US-East"}) - For compound groups, this will be a map with multiple key-value pairs (e.g.,
{"region": "US-East", "team": "engineering"})
- For simple groups, this will be a map with a single key-value pair (e.g.,
value: Aggregated usage for this group and time windownext_page: Pagination cursor for large datasets
Usage guidelines:
- Required parameters: Must specify
customer_id,billable_metric_id, andwindow_size - Time windows: Set
window_sizeto hour, day, or none for different granularities - Group filtering: Use
group_keyandgroup_filtersto specify groups and group filters - Limits: When using compound group keys (2+ keys in
group_key), the default and max limit is 100 - Pagination: Use limit and
next_pagefor large result sets - Null handling: Group values may be null for events missing the group key property
279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
# File 'lib/metronome_sdk/resources/v1/usage.rb', line 279 def list_with_groups(params) query_params = [:limit, :next_page] parsed, = MetronomeSDK::V1::UsageListWithGroupsParams.dump_request(params) query = MetronomeSDK::Internal::Util.encode_query_params(parsed.slice(*query_params)) @client.request( method: :post, path: "v1/usage/groups", query: query, body: parsed.except(*query_params), page: MetronomeSDK::Internal::CursorPage, model: MetronomeSDK::Models::V1::UsageListWithGroupsResponse, options: ) end |
#search(transaction_ids:, request_options: {}) ⇒ Array<MetronomeSDK::Models::V1::UsageSearchResponseItem>
This endpoint retrieves events by transaction ID for events that occurred within the last 34 days. It is specifically designed for sampling-based testing workflows to detect revenue leakage. The Event Search API provides a critical observability tool that validates the integrity of your usage pipeline by allowing you to sample raw events and verify their matching against active billable metrics.
Why event observability matters for revenue leakage: Silent revenue loss occurs when events are dropped, delayed, or fail to match billable metrics due to:
- Upstream system failures
- Event format changes
- Misconfigured billable metrics
Use this endpoint to:
- Sample raw events and validate they match the expected billable metrics
- Build custom leakage detection alerts to prevent silent revenue loss
- Verify event processing accuracy during system changes or metric updates
- Debug event matching issues in real-time
Key response fields:
- Complete event details including transaction ID, customer ID, and properties
- Matched Metronome customer (if any)
- Matched billable metric information (if any)
- Processing status and duplicate detection flags
Usage guidelines:
⚠️ Important: This endpoint is heavily rate limited and designed for sampling workflows only. Do not use this endpoint to check every event in your system. Instead, implement a sampling strategy to randomly validate a subset of events for observability purposes.
338 339 340 341 342 343 344 345 346 347 |
# File 'lib/metronome_sdk/resources/v1/usage.rb', line 338 def search(params) parsed, = MetronomeSDK::V1::UsageSearchParams.dump_request(params) @client.request( method: :post, path: "v1/events/search", body: parsed, model: MetronomeSDK::Internal::Type::ArrayOf[MetronomeSDK::Models::V1::UsageSearchResponseItem], options: ) end |