Designing the backend behind usage-based pricing: idempotent event ingestion, hourly rollups that handle late events, reporting usage to Stripe meters exactly once, and what customers see on their usage page.

A usage metering backend records what each customer consumes and turns it into billable quantities: API calls per month, gigabytes processed, minutes of compute. Under usage-based pricing, it is the system of record for revenue, so the two failure modes are billing a customer twice for the same usage and not billing usage at all.
The edges are producers that retry and send the same event twice, events that arrive an hour late, a billing provider with rate limits and its own deduplication rules, and a customer who opens a support ticket asking why this month's invoice is higher than last month's.
This guide builds a metering service in Go with Encore that ingests events idempotently, rolls them up hourly, and reports closed hours to Stripe Billing meters. It then compares that with sending each event straight to Stripe.
Encore is a backend framework with built-in infrastructure, and a metering service uses a database for raw events and hourly totals, cron jobs for the rollup and the reporting, and a secret for the Stripe key. Cron jobs are managed by the Encore platform and do not run locally or in preview environments, so you call the rollup and reporting endpoints directly when testing. The Stripe key is set with encore secret set and the production value is not in the repository, so an AI coding agent working in the repo cannot read that value. A local override in .secrets.local.cue is readable if it is present. The database runs locally under encore run and on RDS or Cloud SQL in your own AWS or GCP account.

Run in your terminal to get started locally.
Raw events are kept as they arrived, keyed by customer and the producer's event ID. Hourly totals are what dashboards read and what gets billed, with a reported_at that freezes an hour once Stripe has it:
-- Raw events. The primary key makes ingestion idempotent per customer.
CREATE TABLE usage_events (
customer_id TEXT NOT NULL,
event_id TEXT NOT NULL,
metric TEXT NOT NULL,
quantity BIGINT NOT NULL CHECK (quantity >= 0),
occurred_at TIMESTAMPTZ NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (customer_id, event_id)
);
CREATE INDEX usage_events_time_idx ON usage_events (occurred_at);
-- Hourly totals: what dashboards read and what gets billed.
CREATE TABLE usage_hourly (
customer_id TEXT NOT NULL,
metric TEXT NOT NULL,
hour TIMESTAMPTZ NOT NULL,
quantity BIGINT NOT NULL,
reported_at TIMESTAMPTZ,
PRIMARY KEY (customer_id, metric, hour)
);
Producers, such as your API gateway or job runners, send batches. A retried batch inserts nothing new, and the response says how many events were duplicates:
// Service usage records metered usage and reports it for billing.
package usage
import (
"context"
"time"
"encore.dev/beta/errs"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("usage", sqldb.DatabaseConfig{Migrations: "./migrations"})
type Event struct {
CustomerID string `json:"customer_id"`
EventID string `json:"event_id"` // generated by the producer, reused on retry
Metric string `json:"metric"` // for example "api_calls" or "gb_processed"
Quantity int64 `json:"quantity"`
OccurredAt time.Time `json:"occurred_at"`
}
type IngestRequest struct {
Events []Event `json:"events"`
}
type IngestResponse struct {
Accepted int `json:"accepted"`
Duplicates int `json:"duplicates"`
}
// Ingest accepts a batch. Retried batches are safe: known event IDs are skipped.
//
//encore:api private method=POST path=/usage/events
func Ingest(ctx context.Context, req *IngestRequest) (*IngestResponse, error) {
if len(req.Events) > 1000 {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "at most 1000 events per batch"}
}
var customers, ids, metrics []string
var quantities []int64
var times []time.Time
for _, e := range req.Events {
if e.Quantity < 0 || e.EventID == "" {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "event_id and a non-negative quantity are required"}
}
customers = append(customers, e.CustomerID)
ids = append(ids, e.EventID)
metrics = append(metrics, e.Metric)
quantities = append(quantities, e.Quantity)
times = append(times, e.OccurredAt)
}
res, err := db.Exec(ctx, `
INSERT INTO usage_events (customer_id, event_id, metric, quantity, occurred_at)
SELECT * FROM unnest($1::text[], $2::text[], $3::text[], $4::bigint[], $5::timestamptz[])
ON CONFLICT (customer_id, event_id) DO NOTHING`,
customers, ids, metrics, quantities, times)
if err != nil {
return nil, err
}
n := int(res.RowsAffected())
return &IngestResponse{Accepted: n, Duplicates: len(req.Events) - n}, nil
}
The rollup recomputes the last three hours from raw events instead of adding increments, which makes it safe to run twice and puts late events in the hour they happened:
package usage
import (
"context"
"encore.dev/cron"
)
var _ = cron.NewJob("rollup-usage", cron.JobConfig{
Title: "Roll raw usage up into hourly totals",
Every: 10 * cron.Minute,
Endpoint: Rollup,
})
// Rollup recomputes the last three hours from raw events, so events that arrive
// late still land in the right hour. Recomputing makes it safe to run twice.
// Hours that were already reported to the billing provider are left alone.
//
//encore:api private
func Rollup(ctx context.Context) error {
_, err := db.Exec(ctx, `
INSERT INTO usage_hourly (customer_id, metric, hour, quantity)
SELECT customer_id, metric, date_trunc('hour', occurred_at), SUM(quantity)
FROM usage_events
WHERE occurred_at >= date_trunc('hour', now()) - interval '3 hours'
GROUP BY 1, 2, 3
ON CONFLICT (customer_id, metric, hour) DO UPDATE
SET quantity = EXCLUDED.quantity
WHERE usage_hourly.reported_at IS NULL`)
return err
}
Once an hour is past the late-arrival window, it is sent to Stripe as one meter event with a deterministic identifier and the hour as its timestamp:
package usage
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"encore.dev/cron"
)
var secrets struct {
StripeSecretKey string
}
var _ = cron.NewJob("report-usage", cron.JobConfig{
Title: "Report closed hours to Stripe meters",
Every: 1 * cron.Hour,
Endpoint: ReportClosedHours,
})
// ReportClosedHours sends one meter event per customer, metric and hour once the
// hour is past the late-arrival window. Stripe enforces uniqueness of the identifier,
// so a resend after a crash between sending and marking the row is not counted twice.
//
//encore:api private
func ReportClosedHours(ctx context.Context) error {
rows, err := db.Query(ctx, `
SELECT customer_id, metric, hour, quantity FROM usage_hourly
WHERE reported_at IS NULL AND hour < date_trunc('hour', now()) - interval '3 hours'
ORDER BY hour LIMIT 500`)
if err != nil {
return err
}
type row struct {
customer, metric string
hour time.Time
qty int64
}
var pending []row
for rows.Next() {
var r row
if err := rows.Scan(&r.customer, &r.metric, &r.hour, &r.qty); err != nil {
rows.Close()
return err
}
pending = append(pending, r)
}
rows.Close()
// One failing customer must not hold back everyone else's billing.
var failed []error
for _, r := range pending {
id := fmt.Sprintf("%s:%s:%d", r.customer, r.metric, r.hour.Unix())
if err := sendMeterEvent(ctx, r.metric, r.customer, r.qty, r.hour, id); err != nil {
failed = append(failed, err) // stays unreported; the next run retries it
continue
}
if _, err := db.Exec(ctx, `
UPDATE usage_hourly SET reported_at = now()
WHERE customer_id = $1 AND metric = $2 AND hour = $3`,
r.customer, r.metric, r.hour); err != nil {
failed = append(failed, err)
}
}
return errors.Join(failed...)
}
// customer here is the Stripe customer ID; map from your own ID if they differ.
func sendMeterEvent(ctx context.Context, eventName, customer string, qty int64, at time.Time, identifier string) error {
form := url.Values{
"event_name": {eventName},
"payload[stripe_customer_id]": {customer},
"payload[value]": {strconv.FormatInt(qty, 10)},
"timestamp": {strconv.FormatInt(at.Unix(), 10)},
"identifier": {identifier},
}
req, err := http.NewRequestWithContext(ctx, "POST",
"https://api.stripe.com/v1/billing/meter_events", strings.NewReader(form.Encode()))
if err != nil {
return err
}
req.SetBasicAuth(secrets.StripeSecretKey, "")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("stripe meter event %s: %s", identifier, resp.Status)
}
return nil
}
encore check compiled this app. Our build machine has no Docker, which the local database needs, so we ran the SQL on Postgres 17: a batch of two events followed by a retry carrying one duplicate stored three events, not four; a late event for the previous hour moved its total from 15 to 115 after the rollup, and running the rollup again left it there; and once that hour was marked reported, a further late event no longer changed it.
An event that arrives after its hour is reported stays in usage_events but is not billed. Either reject events older than the window at ingestion, so producers see the error, or bill them as a correction in the current hour. Stripe accepts meter events up to 35 days old, but usage that arrives after an invoice finalizes does not change that invoice.
The customer-facing usage page reads usage_hourly, which is also what an engineer or a coding agent would query to explain an invoice, since every billed number traces back to rows in usage_events.
Best fit: SaaS products that bill on usage at meaningful volume, need a customer usage page, and want the ledger in their own database in their own AWS or GCP account.
The simplest design skips the ledger and creates a meter event for each billable action, with your own action ID as the identifier so a retried call is not counted twice:
// meter/record.ts
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
// Called once per billable action, for example after each API request is served.
export async function recordUsage(
stripeCustomerId: string,
eventId: string, // your own ID for the action, reused if this call is retried
quantity: number,
): Promise<void> {
await stripe.billing.meterEvents.create({
event_name: "api_calls",
payload: { stripe_customer_id: stripeCustomerId, value: String(quantity) },
identifier: eventId,
});
}
It holds up at low volume. Stripe limits the live-mode meter event endpoint to 1,000 calls per second per account and one concurrent call per customer per meter, so a busy customer making parallel requests will see 429 responses that need retries with backoff, and Stripe's own guidance is to pre-aggregate before you hit those limits. Stripe also processes meter events asynchronously, so a usage page built on its summaries lags, and errors such as an unknown customer arrive later as v1.billing.meter.error_report_triggered events you have to subscribe to.
Best fit: Early usage-based pricing with modest volume, where Stripe's meter summaries are enough for the customer and for finance.
Send events straight to Stripe while volume is low and one metric is billed, and plan the move to a ledger before you reach the per-customer concurrency limit. Keep your own ledger once you need a usage page, several metrics, invoice audits or a second billing provider, and report closed periods with deterministic identifiers. Invoice, tax and revenue-recognition rules stay with your finance and compliance team. Pick Encore when you want the ledger, the rollup and reporting jobs and the Stripe secret declared in one Go service and deployed to your own AWS or GCP account.
Usage metering is recording what each customer consumes, such as API calls, gigabytes processed, seats or compute minutes, so it can be billed under usage-based pricing and shown to the customer. A metering backend ingests usage events, deduplicates them, aggregates them into billable periods and reports the totals to the billing system.
No. Stripe's meter event endpoint is limited to 1,000 calls per second per account in live mode and one concurrent call per customer per meter, and Stripe recommends pre-aggregating usage when you would exceed those limits. For low volumes, sending every event is a simple design. Keeping your own usage table also gives customers a usage page and lets you audit an invoice.
Give every usage event a unique ID at the source and make ingestion ignore IDs it has seen, for example with a primary key and ON CONFLICT DO NOTHING. When reporting to the billing provider, send a deterministic identifier per customer, metric and period, since Stripe enforces uniqueness of meter event identifiers within a rolling period of at least 24 hours.
Pick a late-arrival window, recompute aggregates for periods still inside it, and only report a period to billing once the window has passed. Stripe accepts meter events with timestamps up to 35 days in the past, but usage reported after an invoice finalizes does not change that invoice.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.