Skip to main content

Usage Metering Template

Best SaaS Metering System
for Usage-Based Billing with Webhooks

Track API calls, storage, and any metric per customer. Automated billing via webhook integration to Stripe, Paddle, or any billing system. Full source code — easily customizable with a coding agent.

npm install -g codehooks
coho create mymetering --template saas-metering-webhook
cd mymetering && coho deploy
# Your usage metering system is live

No credit card required. Free tier for development. Set up your coding agent →

Usage-Based Billing with Webhook Integration - No Infrastructure Headache

Your customers want to pay for what they use. But building a metering system from scratch means weeks of work:

  • Event capture and storage at scale
  • Multi-tenant data isolation
  • Time-based aggregation logic
  • Cron-based batch processing
  • Webhook delivery to billing systems
  • Duplicate prevention and idempotency

Deploy all of this in 5 minutes with our open-source template.

Perfect For

API ProvidersTrack requests per customer
Storage ServicesMeter bytes and operations
Platform ToolsCount feature usage
AI/ML ServicesTrack tokens and compute

Everything You Need for Usage Metering

Capture events, aggregate over billing periods, deliver to your billing system

Multi-Tenant Event Capture

Track usage per customer with flexible event types. Capture API calls, storage, transactions, or any metric you need.

Flexible Aggregation Operations

Sum, average, min, max, count, first, or last. Choose the right operation for each metric type.

Calendar-Based Periods

Hourly, daily, weekly, monthly, or yearly aggregations. Billing-friendly calculations that align with your pricing model.

Automated Batch Processing

Cron-based processing runs every 15 minutes. Aggregates completed periods automatically without manual intervention.

HMAC-Signed Webhook Delivery

Secure webhook notifications for completed periods. HMAC-SHA256 signatures ensure authenticity.

Production-Ready Architecture

Idempotent processing, duplicate prevention, and state tracking. Built for reliability at scale.

How Usage Metering Works

From event capture to billing webhook in four steps

Your App

Sends events

Event Storage

Per customer

Aggregation

Sum, avg, count...

Billing Webhook

HMAC signed

Automated flow: Events captured instantly → Stored per customer → Aggregated every 15 min → Webhook sent when period completes

Simple API for Usage Tracking

Track any metric with a single POST request. The system handles storage, aggregation, and webhook delivery automatically.

  • One endpoint per event type
  • Customer ID for multi-tenant isolation
  • Optional metadata for filtering
  • Batch endpoint for high-volume capture

Track API usage per customer:

// Track an API call
await fetch(METERING_URL + '/usage/api.calls', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-apikey': process.env.CODEHOOKS_API_KEY
},
body: JSON.stringify({
customerId: 'cust_123',
value: 1,
metadata: { endpoint: '/api/users' }
})
});
// At end of billing period, your webhook receives:
// { customerId: 'cust_123', eventType: 'api.calls',
// period: 'monthly', value: 15420, ... }

Aggregation Operations

Choose the right operation for each metric type

OperationUse CaseExample
sumTotals (API calls, bytes transferred)[5, 10, 3] → 18
avgAverages (response times, ratings)[10, 20, 30] → 20
countEvent frequency (requests, logins)3 events → 3
maxPeak usage (concurrent users)[100, 200, 150] → 200
minMinimum values (lowest latency)[100, 50, 75] → 50
lastFinal state (closing balance)[100, 200, 300] → 300

Built for Usage-Based SaaS Pricing

Real-world metering for any consumption metric

API Metering

Track API calls, requests per endpoint, and rate limit usage for consumption-based pricing.

api.calls • requests.count • rate.exceeded

Storage & Compute

Meter storage bytes, compute minutes, and resource consumption for infrastructure billing.

storage.bytes • compute.minutes • bandwidth.gb

AI & ML Services

Track tokens, model invocations, and training compute for AI/ML platform billing.

tokens.used • model.calls • training.hours

A Simpler Alternative to Stripe's Usage API

Tired of fighting with complex metering APIs? Own your usage data, aggregate it your way, and stay payment-provider agnostic.

Why build your own metering? Payment processor metering tools often have limited aggregation options, confusing terminology, and lock you into their ecosystem. With this template, you capture events in your own database, aggregate with full flexibility (sum, avg, min, max, count), and create invoices on your terms.

Read: Stop Fighting Stripe's Usage API →

Ready for Usage-Based Billing?

Deploy a production-ready metering system in 5 minutes. Free to start, scales with your business.

SaaS Metering & Usage-Based Billing FAQ

Common questions about usage metering, billing automation, and webhook integration

What are the best systems for usage-based billing with webhook integrations?
The best systems for usage-based billing with webhook integrations need: (1) flexible event capture for any metric, (2) multi-tenant customer isolation, (3) aggregation operations (sum, avg, count), (4) calendar-based billing periods, and (5) secure HMAC-signed webhook delivery. Codehooks SaaS Metering provides all of this as an open-source template you can deploy in 5 minutes.
What is SaaS usage metering?
SaaS usage metering tracks how much of your service each customer uses. It captures events like API calls, storage consumption, or feature usage, then aggregates them over billing periods. This data powers usage-based pricing, billing reports, and analytics dashboards.
How does usage-based billing work with this system?
Your application sends usage events via POST /usage/:eventType with a customer ID and value. The system aggregates these events over your billing period (daily, weekly, monthly). When a period completes, a webhook delivers the totals to your billing system for invoicing.
What aggregation operations are supported?
Seven operations: sum (totals like API calls), avg (metrics like response times), count (event frequency), min/max (extremes like peak usage), first/last (state snapshots like opening/closing values). Each event type can use a different operation.
How do I track API usage per customer?
Send an event for each API call: POST /usage/api.calls with {customerId, value: 1}. Configure the event type with sum operation. At the end of each billing period, you'll receive a webhook with the total API calls per customer.
Can I aggregate usage over different time periods?
Yes. Configure multiple periods: hourly (real-time dashboards), daily (operational reports), weekly/monthly (billing cycles), yearly (annual reviews). Each period aggregates independently, so you can have both real-time and billing views.
How does the webhook delivery work?
When a period completes (e.g., end of month), the system sends a webhook with the aggregated data. Webhooks include HMAC-SHA256 signatures for verification. Your billing system receives: event type, customer ID, period, timestamp, and aggregated value.
Is this suitable for high-volume event tracking?
Yes. The batch processing architecture handles high event volumes efficiently. Events are stored immediately (low latency capture) and aggregated in batches every 15 minutes. The system is idempotent and prevents duplicate aggregations.
How do I test without sending real webhooks?
Set DRY_RUN=true in your environment. The system logs webhook payloads and signatures without making HTTP requests. This lets you validate your configuration and event flow before going to production.
Can I query real-time usage before the period ends?
Yes. Use GET /events to query raw events with filters (customerId, eventType, time range). For real-time dashboards, use POST /aggregations/trigger to manually aggregate the current period without waiting for completion.
What's the difference between sum and count?
Sum adds up the values: events with values [5, 10, 3] sum to 18. Count counts occurrences: 3 events = 3, regardless of values. Use sum for quantities (bytes, dollars), count for frequencies (requests, logins).
How does SaaS billing automation work with API webhook integration?
SaaS billing automation via API webhook integration works by: (1) Your app sends usage events to the metering API, (2) Events are stored per customer, (3) Aggregation runs automatically on schedule, (4) When billing periods complete, webhooks deliver totals to your billing system (Stripe, Paddle, etc.) for automatic invoice generation.