Metering Engine

Every Billable Moment.
Captured. Validated. Ready to Invoice.

Revenue leakage starts where metering stops. Missed events, duplicate charges, and unvalidated timestamps cost enterprise billing teams millions annually in write-offs and customer disputes.

Aforo captures every billable event from every source, gateways, SDKs, webhooks, REST, batch uploads, validates it against financial-grade rules, and delivers it to billing with full audit provenance. 100% accurate usage-based billing at enterprise scale.

LIVE EVENT AUDIT
INGESTING
TIMESTAMPSOURCEEVENTSTATUS
14:23:07.412Kong GatewayPOST /v2/searchVALIDATED
14:23:07.415Python SDKagent.run()ENRICHED
14:23:07.418REST APIPUT /data/syncDEDUPLICATED
14:23:07.421Plugsstripe.chargeREJECTED
14:23:07.424Node SDKtools/callVALIDATED
14:23:07.427AWS LambdaPOST /ingestENRICHED
EVENTS TODAY
847,293
DUPLICATES CAUGHT
142
LEAKAGE PREVENTED
$4,208

Metering is the revenue foundation.
Get it wrong, and every invoice downstream is suspect.

Most metering systems count events. Aforo validates, enriches, and certifies them, giving your finance team the confidence to close the books without manual reconciliation.

Revenue Assurance

Every event passes through idempotency checks, timestamp validation, and schema enforcement before it reaches billing. Duplicate detection via configurable idempotency keys. Late arrivals flagged for reconciliation, never silently dropped, never double-counted. Your finance team can certify that every invoice traces back to a validated source event.

Financial Auditability

Full provenance chain from ingest to invoice. Every event carries its source, ingestion timestamp, validation result, enrichment context, and routing decision. Replay any billing period from raw events. SOC 2 and SOX-ready audit trails without building custom logging infrastructure.

Real-Time Cost vs. Revenue Mapping

Events are enriched with customer, subscription, and pricing context at ingest time, not at billing time. The RevenueEstimator computes per-event revenue using cumulative-aware running totals. Margin by cohort visible before the billing cycle closes. No more month-end surprises.

Built for AI Economics

MCP server tool calls, agent session lifecycles, and per-token AI compute auto-detected and metered. The aforo-mcp-proxy sidecar handles stdio, SSE, and streamable-HTTP MCP transports without source-code changes. Per-tool, per-agent, per-session billing primitives that map directly to AI commerce patterns no incumbent supports.

The Atomic Unit

Source Event + Billing Context. One Revenue-Ready Event.

Every billable signal in Aforo resolves to two inseparable halves. A Source Event captures the raw fact, the API call, the SDK invoke, the webhook, the tool_call. Billing Context attaches the customer, the contract, and the price at ingest time. Together they become a Revenue-Ready Event with full provenance, ready for billing the moment it arrives.

Raw Signal
Source Event

The fact. An API call landing at a Kong route, an SDK decorator firing, an MCP tools/call JSON-RPC, a Stripe webhook. Captured with full provenance and validated against four financial-grade gates before anything else happens.

6 ingestion tiers
Gateway plugin · Middleware filter · SDK decorator · REST API · Upload (CSV/JSON) · MCP sidecar
4 validation gates
Timestamp (±5 min skew, <90d) · Idempotency dedup · Schema enforcement · Latency flag
Provenance chain
Source · ingestion timestamp · validation hash · enrichment context · routing decision
Late-arrival reconciliation
Events >24h late flagged, billing watermarks gate re-runs — never silently dropped, never double-counted
Raw payload preserved
Stored alongside enriched event for replay, dispute defense, and SOC 2 audit
+
= Revenue-Ready Event
Enriched at Ingest
Billing Context

The meaning. Customer identity, contracted rate plan, applicable pricing model, cost-to-serve, and real-time margin attach to every event at ingest, not at month-end. Revenue is known the moment usage happens.

Customer + tenant resolution
BillingHierarchyEnricher resolves tenant → customer → subscription via Redis-cached entitlements (10-min TTL)
Rate plan binding
Subscription pinned to a rate plan version — one of 8 pricing models, immutable for the contract
Real-time revenue estimate
Per-event marginal revenue computed via PricingCalculator subtraction (cumulative-aware running totals)
Cost-to-serve attribution
COGS events for AI inference, payment gateway fees, and provider costs attached per event
Margin computation
Revenue − COGS visible per customer per product BEFORE the billing cycle closes

Other systems count events and enrich them at billing time, which is how month-end surprises happen. Aforo enriches at ingest time, which is how Finance closes the books on Tuesday.

The Surface

Six Ingestion Tiers. One Integration Guide.

Engineering picks the tier that matches the architecture. The in-product Integration Guide ships ready-to-paste code for each tier, a live event tester, and a verification panel that confirms events are landing within seconds. Same backend pipeline, six front doors.

aforo.app / developer / integration-guide
CONNECTED
MCP Proxy / npmCopy · Run
# 1 sidecar process. No MCP server source changes.
$ npm i -g @aforo/mcp-proxy

$ aforo-mcp-proxy \
    --transport stdio \
    --command "npx" \
    --args "-y,@modelcontextprotocol/server-fs,/tmp" \
    --tenant ${TENANT_ID} \
    --product mcp-fs-server \
    --api-key ${AFORO_API_KEY}

# Every tools/call auto-metered per tool, per agent, per session.
Live Event Stream
INGESTING
14:23:07.412VALIDATED
MCP Server
tools/call · read_file · 18ms
14:23:07.415ENRICHED
MCP Server
tools/call · search · 42ms
14:23:07.418VALIDATED
MCP Server
session.start · agent_acme_42
14:23:07.421DEDUPLICATED
MCP Server
tools/call · embed · 24ms
Live tail · scoped to your tenant · <5ms ingest latency

The same Integration Guide ships with every Aforo tenant. Pick a tier, copy the snippet, send a test event, see it land in the live stream within seconds. No deploy required to verify your wiring.

How It Works

From source event to certified invoice in four stages

Every event carries full provenance. Every stage is auditable. No black boxes between your API traffic and your revenue.

Capture Usage Automatically

Six ingestion tiers, zero-code to full control

Gateway plugins intercept every API call at the network layer. SDK decorators instrument application code. REST endpoints accept custom payloads. Webhook receivers normalize third-party events from Stripe, Twilio, SendGrid, GitHub, and Slack. Batch uploads reconcile historical data. The aforo-mcp-proxy sidecar wraps MCP servers (stdio, SSE, streamable-HTTP) for per-tool-call metering. Pick the tier that fits your architecture, the pipeline treats every source identically.

Validate for Financial Integrity

Every event passes 4 validation gates

Timestamp validation rejects future events beyond 5-minute clock skew and events older than 90 days. Idempotency keys detect and reject duplicates. Schema validation ensures required fields exist. Late arrivals (>24 hours) are flagged for manual reconciliation, never silently dropped, never silently accepted.

Enrich and Map to Contracts

Billing context resolved at ingest time

Every validated event is enriched with the customer, subscription, rate plan, and pricing model it belongs to. Redis-cached entitlements (10-minute TTL) ensure sub-millisecond resolution. Events arrive at billing fully contextualized, no lookups required at invoice generation time.

Settle and Invoice

Deterministic 10-stage handoff to billing

At period end, the billing engine consumes metered events already tagged with pricing context. The 10 stages run in order: QuotaCheck → Rollover → Aggregate → Allowance → Rate → Commit → Discount → Tax → Route → Settle. Each is independently testable; failures are isolated, not cascading. Your team never touches the data between metering and invoice.

The Outcome

Real-Time Revenue. Computed Per Event.

Validated, enriched metering is table stakes. The differentiator is what comes out the other end. The RevenueEstimator computes exact marginal revenue per event using cumulative running totals, then surfaces it on operator dashboards and customer portals continuously, not at month-end.

Live Revenue
LIVE · 60s refresh
Today's Revenue
$24,820.45
+18.4% vs yesterday
00:00 UTC14:23 UTC (now)
This Period (live)
Day 16 of 31
$487,206
+12.1% vs last period
$0Projected end-of-period: $943K
Upper-bound estimate for tier/allowance plans. Final invoice may be lower.
How the math works
Cumulative-aware running totals

Per-(subscription, metric, period) running totals updated under SELECT FOR UPDATE per event. Exact marginal revenue, not upper-bound approximation.

PricingCalculator subtraction

For each event: subtract(running_total_after) − subtract(running_total_before). Identical math to the canonical bill-run pipeline.

Live tiles + customer portal

P14′ surface mounts on operator Home + customer storefront. 60s refresh interval, 30s stale window, sparkline trend over last 24h.

Margin per customer, pre-bill

Revenue ledger joins COGS events (AI inference, gateway fees, provider costs) so margin is visible BEFORE bill-run finalize.

Other systems tell you what you billed last month. Aforo tells you what you're billing right now. Margin compression shows up on Wednesday, not on the 30th.

Active Monitoring

Capture Is Step One. Monitoring Closes the Loop.

Three production-grade monitors run continuously on top of the metering pipeline. They normalize inbound third-party events, catch usage anomalies before they become churn signals, and project quota exhaustion before customers hit it. Operators intervene days earlier.

Webhook-to-Ingest Receiver

Stripe · Twilio · SendGrid · GitHub · Slack

Inbound webhooks from external providers normalize into billable events automatically. JSONPath extraction maps any provider payload shape to your event schema. HMAC SHA-256 verification with 5-minute replay window rejects forged events at the perimeter.

JSONPath extractionHMAC SHA-256 verify5+ provider templatesPer-source rate limit
Mapped event sample
stripe.event.idevt_3OqXk2...
$.data.amount→ quantity
$.created→ occurredAt
tenantX-Tenant-Id header

Anomaly Detection

2σ hourly + 50% weekly drop

Two detectors watch every customer’s usage curve. The hourly BillableUnitAnomalyDetector fires on 2σ deviations from a per-customer rolling baseline. The weekly drop detector catches 50%+ week-over-week declines, the leading indicator of customer disengagement.

2σ hourly detection50% weekly dropPer-customer baselinesIdempotent alerts
Live signal
baseline+2.4σ spike−58% drop

Quota Pacing Alerts

80% · 100% · 120% thresholds

Projection on the quota axis. The QuotaPacingProjectionService watches accruing usage, projects end-of-period consumption based on current pace, and fires alerts at 80%, 100%, and 120% projected thresholds, once per period per threshold.

Projected end-of-period5% min-progress gateCustomer + operator alertsPer-period idempotency
Projection bar
52% used (day 16)120% projected

Capture without monitoring is just logs. Aforo ships the receivers, detectors, and projections that turn the metering pipeline into a revenue-protection system.

The metering infrastructure, in detail

Six ingestion tiers. Four validation gates. One certified, auditable pipeline.

Six Ingestion Tiers

From zero-code gateway plugins to MCP sidecar to full REST API control. Choose based on your architecture, not our constraints.

Gateway
0 lines
Network-level
Middleware
1 line
App-level filter
SDK
5 lines
Decorator pattern
REST
~10 lines
Full control
Upload
CSV/JSON
Historical data
MCP
1 sidecar
tools/call proxy

Financial Validation

Every event passes timestamp, idempotency, schema, and latency checks before reaching billing.

Timestamp within 5-min skewPASS
Idempotency key uniquePASS
Schema valid (7 required fields)PASS
Arrival >24h lateFLAGGED

Full Audit Provenance

Trace any invoice line item back to the raw source event. Every stage logged with timestamps.

Ingest<5msKong gateway → event captured
Validate+2msTimestamp OK, dedup OK, schema OK
Enrich+4msCustomer: Acme, Plan: Enterprise
Route+5ms→ billing.usage.events (Kafka)

Cost vs. Revenue in Real Time

See margin by customer and product before the billing cycle closes. Spot negative-margin accounts immediately.

CUSTOMEREVENTSREVCOSTMARGIN
Acme Corp124K$4,820$1,24074%
GlobalBank89K$12,600$2,14083%
DataSync312K$2,100$3,800-44%

Five Gateway Plugins

Kong, AWS, Apigee, Azure APIM, MuleSoft. Same validated pipeline regardless of gateway.

Kong
AWS API GW
Apigee
Azure APIM
MuleSoft
The Buying Committee

One Pipeline. Four Stakeholders. Zero Friction.

Engineering, Product, Finance, and Customer Success each get the controls they need over revenue accuracy without stepping on each other. Zero-code gateway plugins, real-time pricing-fitness dashboards, audit-grade trace exports, and 1-command MCP onboarding, all on one validated pipeline.

Engineering

VP Engineering · Platform Lead

Ship a new product without writing metering code.

The Workflow
  1. 1Platform team adds a Translation API product to the Kong gateway route.
  2. 2Install the aforo-metering Lua plugin once on the route. Zero source-code changes.
  3. 3Validation, enrichment, and rate-plan binding fire automatically per event.
  4. 4First invoice generates against real usage. Engineering ticket count for billing: zero.
0 metering tickets per product launch

Product

VP Product · Pricing Strategist

Validate pricing-model fitness in real time.

The Workflow
  1. 1PM ships a new "AI Agent Sessions" billable unit via the catalog UI.
  2. 2Within an hour, BillableUnitHealthPage shows distribution against assumed tier thresholds.
  3. 3Histogram surfaces that 73% of usage falls in tier 1, not tier 2 as planned.
  4. 4PM adjusts GRADUATED tier thresholds before the new pricing rolls to all customers.
Pricing fitness proven before contracts lock

Finance

CFO · FP&A · Revenue Operations

Close audit disputes in hours, not weeks.

The Workflow
  1. 1Acme disputes a $4.8K usage line item on invoice INV-2026-0427.
  2. 2CFO opens the Usage Attribution tab on the invoice detail drawer.
  3. 3bill_run_event_index trace shows 124K source events with HMAC validation hashes.
  4. 4Export the audit trail to Acme. Dispute closed in 4 hours, not 14 days.
<1 day median dispute resolution

Customer Success / RevOps

Head of RevOps · CS Lead

Monetize an MCP server in minutes.

The Workflow
  1. 1Customer ships an MCP server exposing 12 tools to AI agents.
  2. 2Wrap the server with aforo-mcp-proxy sidecar — 1 CLI command, no source-code change.
  3. 3Every tools/call JSON-RPC auto-metered per tool, per agent, per session.
  4. 4Per-tool pricing live on the next deploy. Customer onboarded same day.
1-command onboarding for MCP server customers
0
Ingestion Tiers
Gateway · Middleware · SDK · REST · Upload · MCP Proxy
0
Gateway Plugins
Kong · Apigee · AWS · Azure APIM · MuleSoft
0
Customer SDKs
Node.js · Python · Java · Go
0
Validation Gates
Timestamp · Idempotency · Schema · Latency

Your revenue deserves
financial-grade metering.

Stop writing off disputed charges. Stop building custom metering for every new product. Start with a pipeline that validates every billable event and traces it to the invoice.