PicoDevs Logo
PicoDevs
Architecting Event-Sourced Billing Engines: Usage-Based Pricing at Scale in B2B SaaS
Back to Articles
Engineering8 min readJuly 31, 2026

Architecting Event-Sourced Billing Engines: Usage-Based Pricing at Scale in B2B SaaS

PicoDevs Studio

The shift from flat-rate subscriptions to usage-based pricing (UBP) has exposed a critical weakness in most B2B SaaS architecture: billing is treated as a downstream concern rather than a core data primitive. When pricing models depend on real-time API consumption, compute milliseconds, or token throughput, traditional polling-based metering introduces reconciliation drift, delayed invoicing, and revenue leakage. At Picodevs, we architect event-sourced billing engines as first-class infrastructure, treating every billable action as an immutable, append-only event in a CQRS-aligned data model.

The Architectural Failure of Polling-Based Metering

Legacy SaaS billing typically relies on cron jobs that poll operational databases to aggregate usage metrics. This approach introduces three compounding failure modes in high-volume B2B environments:

  • Event Loss: Polling intervals create windows where transient usage spikes are missed if the system crashes between polling cycles.
  • Reconciliation Drift: Aggregating usage via batch updates makes it nearly impossible to audit why a specific invoice amount was calculated, breaking SOC 2 and GDPR compliance requirements.
  • Latency Ceiling: Customers operating on prepaid credits or hard limits require sub-second enforcement. Polling architectures simply cannot trigger threshold alerts or service cutoffs in real time.

The solution is not better polling; it is a fundamental shift to event-driven metering where the billing engine is a consumer of a high-throughput event stream, not a periodic scraper.

Event Sourcing as the Billing Foundation

Event sourcing mandates that we store every state-changing action as an immutable event. For a billing engine, this means every API call, compute invocation, or data transfer is persisted as an event before the business logic executes. This creates a definitive, replayable audit trail.

The Core Event Schema

An effective billable event must encapsulate the dimensions required for both real-time enforcement and asynchronous aggregation:

  • event_id: UUID for idempotency.
  • tenant_id: The organizational boundary for data isolation.
  • metric_type: The specific usage dimension (e.g., llm_tokens, compute_ms, gb_transferred).
  • quantity: The numeric volume consumed.
  • timestamp: High-resolution UNIX timestamp for temporal querying.
  • resource_meta: JSON payload containing node locality, model ID, or API endpoint for granular cost attribution.

By persisting this schema to an append-only log (such as Apache Kafka or Redpanda), we decouple usage capture from usage processing. The operational system fires the event and continues; the billing engine consumes the stream at its own pace.

Technical Deep Dive: The Metering Pipeline

Architecting a resilient metering pipeline requires distinct components for ingestion, processing, and materialization. When we build these systems for clients at Picodevs via our custom web development services, we segment the architecture into three isolated layers.

1. High-Throughput Ingestion

The ingestion layer must handle burst traffic without applying backpressure to the core application. We deploy edge-native API gateways that asynchronously push events to a managed streaming buffer. This ensures that even if the downstream billing processor experiences latency, the user-facing application remains unaffected. If you are evaluating infrastructure providers, consider leveraging high-throughput messaging platforms via Confluent Cloud for managed Kafka to reduce operational overhead.

2. Stream Processing and Aggregation

Raw events are expensive to query. The processing layer consumes the event stream and continuously materializes aggregates into a low-latency key-value store or OLAP database (e.g., ClickHouse or Apache Druid). We define tumbling windows (e.g., 1-minute or 1-hour buckets) per tenant_id and metric_type to maintain running totals.

This continuous materialization allows the system to query current usage in O(1) time, enabling real-time enforcement of spending limits without scanning massive historical logs.

3. The Materialized View Store

The materialized view serves two critical functions: dashboard rendering for end-users and threshold evaluation for the quota enforcement service. By separating the write-optimized event log from the read-optimized materialized view, we adhere to CQRS principles, ensuring that heavy analytical queries do not degrade system performance.

Handling Architectural Edge Cases

Idempotency and Exactly-Once Processing

Distributed systems guarantee at-least-once delivery, meaning duplicate events are inevitable. The billing engine must enforce idempotency by checking the event_id against a deduplication cache (typically Redis) before committing the event to the aggregation logic. Failing to implement this results in phantom overages and customer distrust.

Retroactive Pricing and Proration

B2B contracts frequently involve negotiated rates that change mid-cycle. Because the event log is immutable, we never alter historical events. Instead, we apply pricing as a projection over the event stream. When a rate changes, the system recalculates the materialized invoice by applying the new pricing matrix to the relevant temporal slice of the event log. This separates the concepts of what happened (events) from what it costs (pricing projection).

How Picodevs Architects Billing for AI-Powered SaaS

Modern AI-driven SaaS applications face extreme billing complexity due to variable compute costs (e.g., GPU minutes) and dynamic token consumption. Generic billing platforms like Stripe Billing excel at flat-rate and tiered models but struggle with high-cardinality, real-time usage metrics.

At Picodevs, we build bespoke event-sourced billing engines designed for the edge. By deploying metering logic close to the compute source, we minimize ingestion latency. To see how we have implemented these complex data pipelines for high-growth clients, explore our portfolio of engineered SaaS products.

Conclusion: Billing as a First-Class Architectural Concern

Usage-based pricing is not a pricing strategy; it is an architectural paradigm. Treating billing as an afterthought guarantees data drift and lost revenue. By adopting event sourcing, CQRS, and stream processing, B2B SaaS platforms can achieve auditable, real-time, and infinitely flexible metering. For deeper insights into scaling complex web architectures, follow the technical breakdowns on our studio blog.

#B2B SaaS#Architecture#Event Sourcing#Billing#CQRS#Backend
Share:
Strategic Deployment Matrix

Ready to Build
Something Extraordinary?

Partner with PicoDevs to architect, build, and deploy agentic AI platforms, cloud architectures, and high-performance web systems.

Capacity Available•Fast Turnaround•Production Guaranteed