Markdown Editor

SaaS Metering and Billing Design Template

Pricing models, billable metrics, CloudEvents usage events, idempotent pipeline, entitlements, tiered rating, quotas, invoicing, reconciliation

आर्किटेक्चरपूर्णCloudEvents 1.0.2; AWS Well-Architected SaaS Lenssaasmeteringbillingdesign
एडिटर में खोलें.md डाउनलोड करें

उपयोग कैसे करें: Use it when a SaaS product bills on usage or mixes platform fees with usage and commitments. Fill the pricing model and the billable metric definitions with finance first, then the event contract and reconciliation checks. The main pitfall is metrics nobody defined precisely and duplicates or late events that silently change invoices.

प्रीव्यू

SaaS Metering and Billing Design: [Product name]

Design document for usage metering and billing in a software-as-a-service product: the pricing model, billable metrics, the usage event contract (CloudEvents 1.0.2), the metering pipeline with idempotent ingestion and late-event handling, entitlements and plans, rating and aggregation, quotas and overage, integration with the invoicing and payment systems, revenue recognition hooks, reconciliation, audit and operations. Tenant cost and tiering considerations follow the themes of the AWS Well-Architected SaaS Lens (publication of 4 April 2023). Replace every [bracketed] value and every row marked Example. Revenue recognition rows are a documentation format, not accounting advice.

Document control

FieldValue
Document ID[MTR-001]
Product and editions[Product], [Editions or plans]
Billing system of record[Commercial billing platform / in-house]
Payment processor[Processor]
ERP or general ledger[System]
Event formatCloudEvents 1.0.2, [JSON] structured mode
Version[0.1]
Status[Draft / In review / Approved / Superseded]
Owner[@billing-architect]
Approvers/reviewers[@product-pricing-lead], [@revenue-accounting-lead], [@finance-systems-lead], [@security-lead], [@sre-lead]
Last updatedYYYY-MM-DD
Classification[Internal / Confidential]

Approvals

RoleNameDecisionDate
Product pricing[@name][Approve / Approve with conditions / Reject]YYYY-MM-DD
Revenue accounting[@name][Decision]YYYY-MM-DD
Finance systems[@name][Decision]YYYY-MM-DD
Engineering[@name][Decision]YYYY-MM-DD
Security[@name][Decision]YYYY-MM-DD

Revision history

VersionDateAuthorChange summary
0.1YYYY-MM-DD[@name]First draft
1.0YYYY-MM-DD[@name]Example: Approved; API call and storage metrics live
1.1YYYY-MM-DD[@name]Example: Added prepaid commitment with drawdown

Contents

1. Scope and context

1.1 Scope

In scopeOut of scope
Example: Usage capture for all billable metrics across regionsProduct analytics events that are not billed
Example: Entitlement checks, quotas and overageSales quoting and contract negotiation
Example: Rating and handover of rated usage to the billing systemTax calculation (delegated to the billing system)
Example: Reconciliation of usage to invoices and to the ledgerCollections and dunning operations
[Item][Item]

1.2 Context

ItemValue
Tenants (paying accounts)Example: 2,000, growing [40 %] per year
Sales channelsExample: Self-serve card (70 % of accounts, 20 % of revenue); sales-led annual contracts (30 % of accounts, 80 % of revenue); cloud marketplace listing planned
Billing periodsExample: Monthly in arrears for usage; annual in advance for platform fees
CurrenciesExample: USD, EUR, GBP
RegionsExample: EU and US deployments; usage stays in region until aggregated

1.3 Requirements

IDRequirementType
MTR-REQ-001 (Example)Every billable action is counted exactly once on the invoice, even when producers retryCorrectness
MTR-REQ-002 (Example)Customers see near-real-time usage (delay under [15 minutes]) in the consoleExperience
MTR-REQ-003 (Example)Quotas stop or throttle usage within [1 minute] of the limit being reached, where the plan says hard limitControl
MTR-REQ-004 (Example)Invoices for a period close within [3 days] after period end, including late eventsFinance
MTR-REQ-005 (Example)Every invoice line traces to stored events and rating rules for [7 years or the retention schedule]Audit
MTR-REQ-006 (Example)Metering outage must not block the product; events buffer and replayAvailability
[MTR-REQ-NNN][Requirement][Type]

2. Pricing model

ModelHow the charge is computedUse when
Flat feeFixed amount per periodSimple entry plans
Per seatUnit price times active or assigned usersValue grows with people using it
Per unit usageUnit price times measured quantityValue grows with consumption
Graduated tiersEach tier's units priced at that tier's rateEncourage growth while keeping small use cheap
Volume tiersAll units priced at the rate of the tier reachedSimple large-volume discounts
PackagePrice per block of units, rounded upUsage in natural bundles
Prepaid commitment with drawdownCustomer prepays credits; usage draws down; overage at a contract rateSales-led contracts that need budget certainty
HybridPlatform fee plus usage componentsMost B2B SaaS

2.1 Plans

Plan IDPlanPlatform feeIncluded usageUsage pricingLimit typeBilling
PLN-FREE (Example)FreeUSD 0100,000 API callsNoneHard limitn/a
PLN-TEAM (Example)TeamUSD 500 per month1,000,000 API calls; 100 GB storageGraduated tiers (section 7)Soft limit with overageMonthly in arrears, card
PLN-ENT (Example)EnterpriseContractPer contractContract rate card; prepaid commitmentSoft limit, alertsAnnual commitment, monthly usage statement
[PLN-ID][Plan][Fee][Included][Pricing][Limit][Billing]

3. Billable metrics

Metric IDMetricSource event typeCountsExcludesAggregationUnit and roundingPeriod boundary
MET-001 (Example)API callscom.example.api.request.completedRequests completed with status 2xx or 3xx; 4xx billed only where the price book says soHealth checks, internal service accounts, requests rejected by quotaSum of countCall; no roundingCalendar month, UTC
MET-002 (Example)Storagecom.example.storage.snapshotBytes stored per tenant, sampled hourlySoft-deleted data inside the [7-day] recovery windowAverage of hourly snapshotsGB-month, rounded to 2 decimalsCalendar month, UTC
MET-003 (Example)Active seatscom.example.seat.activityDistinct users with at least one sign-in in the periodService users, support impersonationUnique countSeatCalendar month, tenant time zone
MET-004 (Example)AI tokenscom.example.ai.inference.completedInput plus output tokens of completed callsCalls that failed before generationSum1,000 tokens, rounded up per periodCalendar month, UTC
[MET-NNN][Metric][Event type][Counts][Excludes][Sum / Max / Unique / Average / Last][Unit][Boundary]

Rules for metric definitions:

  • Measure at the point where the action is complete and its outcome is known, not at request receipt.
  • Prefer metrics the customer can verify from their own logs or console.
  • State the time zone and the period boundary; an event at 23:59:59 UTC must fall in one period only.
  • Version metric definitions. A definition change applies from a stated period and never re-rates closed periods silently.

4. Usage event contract

Usage events use the CloudEvents 1.0.2 format. CloudEvents requires the context attributes id, source, specversion and type, and requires producers to keep the combination of source and id unique for each distinct event; consumers may treat events with the same source and id as duplicates. The metering pipeline uses that pair as the idempotency key.

{
  "specversion": "1.0",
  "id": "4f1c2a9e-7b1d-4d8e-9a55-2f0c1e7d9b10",
  "source": "//api.example.com/regions/eu-west/gateway-07",
  "type": "com.example.api.request.completed",
  "subject": "tenant/t-10442",
  "time": "2026-10-23T09:14:07.512Z",
  "datacontenttype": "application/json",
  "dataschema": "https://schemas.example.com/usage/api-request/2",
  "data": {
    "tenantId": "t-10442",
    "subscriptionId": "sub-88310",
    "metric": "MET-001",
    "quantity": 1,
    "dimensions": { "region": "eu-west", "apiProduct": "search" },
    "statusClass": "2xx"
  }
}
FieldRule
idAssigned by the producer when the billable action completes; stable across retries
sourceIdentifies the producing component instance; with id forms the idempotency key
typeReverse-DNS event type; one type per billable action
timeEvent time in UTC; decides the billing period
subjectTenant reference, used for partitioning
dataschemaVersioned schema; a breaking change gets a new version and a new type or schema URI
data.quantityNon-negative number in the metric's base unit; pre-aggregated events state the window they cover

Corrections are new events of a correction type (for example com.example.usage.adjustment) that reference the original id and carry a signed quantity and a reason code. Never edit or delete a stored usage event. Register the event types in the event catalogue described in the event-driven architecture design (architecture/event-driven-architecture-design).

5. Metering pipeline

5.1 Stage responsibilities

StageResponsibilityGuarantee
Producer bufferWrite usage to a transactional outbox or local durable buffer in the same unit of work as the actionNo usage lost if the pipeline is unavailable
IngestionAccept batches; authenticate producers; return acknowledgement after durable writeAt-least-once delivery
ValidationCheck schema version, tenant existence and subscription; route failures to the dead-letter storeNo silent drops
DeduplicationKeep a key store of source + id for at least the maximum retry and replay horizon ([35 days])Effectively once per key
Raw storeAppend-only, partitioned by tenant and event date, immutableReplay and audit
AggregationMaintain running totals per tenant, metric and period; recompute from the raw store on demandTotals reproducible from events
RatingApply the price book version valid for the periodDeterministic charges

5.2 Late and out-of-order events

RuleExample value
Events assigned to period by time, not arrivalAlways
Late window during which events still join the open period72 hours after period end
Period closePeriod end plus 72 hours; invoice generated after close
Events arriving after closeBilled in the next period as a prior-period adjustment line, with original event time kept
Future-dated events (more than [5 minutes] ahead of server time)Rejected to the dead-letter store

5.3 Capacity estimate

Example: 12,000 events per second on average gives 12,000 x 86,400 = 1,036,800,000 events per day. At 600 bytes per event that is about 622 GB of raw usage per day, or about 246 TB for 396 days (13 months) before compression. Consequence: pre-aggregate high-volume metrics at the producer in one-minute windows per tenant and dimension (keeping counts exact), and keep per-request events only where customers need line-level evidence. Size the deduplication store for the keys of the full 35-day horizon, or deduplicate pre-aggregated windows by window key instead.

6. Entitlements and plans

The entitlement service holds, per tenant, the active plan, features, included quantities, limits and contract terms. Products ask it, through a cached local client, whether a feature or quantity is allowed. The billing system is the commercial source; changes flow to the entitlement service as events, so the product never depends on the billing system being available.

Entitlement IDTypePlan valuesEnforcement pointCache time to live
ENT-001 (Example)Feature flag: single sign-onTeam: off; Enterprise: onIdentity service5 min
ENT-002 (Example)Included API calls per monthFree: 100,000; Team: 1,000,000; Enterprise: contractQuota service1 min
ENT-003 (Example)Rate limit per secondFree: 10; Team: 100; Enterprise: 500API gateway1 min
ENT-004 (Example)Storage limitFree: 1 GB; Team: 500 GB; Enterprise: contractStorage service15 min
[ENT-NNN][Type][Values][Point][TTL]

Plan changes in the middle of a period are prorated by the billing system for fees; usage metrics switch rate at the effective timestamp of the change, which the rating engine reads from the subscription history. Design feature flags with the configuration service design (system-design/design-config-feature-flag-service).

7. Rating and aggregation

Rate with decimal arithmetic in the currency's minor units, round once per invoice line using the rounding rule agreed with finance ([half-up to 2 decimals]), and store the price book version, the quantities and the result with each rated line.

7.1 Worked example: graduated versus volume tiers

Example price book for MET-001 on PLN-TEAM: first 1,000,000 calls included; 1,000,001 to 10,000,000 at USD 0.20 per 1,000 calls; above 10,000,000 at USD 0.10 per 1,000 calls. Tenant t-10442 used 14,500,000 calls in the month.

TierCalls in tierRateGraduated charge
1 (included)1,000,000USD 0USD 0
29,000,000USD 0.20 per 1,000USD 1,800
34,500,000USD 0.10 per 1,000USD 450
Total usage14,500,000USD 2,250

With the platform fee of USD 500, the graduated invoice is USD 2,750. Under volume tiers, where all billable calls take the rate of the tier reached, the 13,500,000 calls above the included amount would cost 13,500 x USD 0.10 = USD 1,350, and the invoice would be USD 1,850 (here the included allowance is deducted before the volume rate applies; state this in the price book). The two models differ by USD 900 for the same usage, which is why the price book must name the tier mode explicitly.

7.2 Worked example: prepaid commitment with drawdown

Example: an Enterprise customer prepays USD 30,000 of credits for 12 months at the contract rate card. Monthly usage rated at the contract rate card is USD 2,750 (illustrative, and not the Team invoice of section 7.1, which includes a platform fee), so 12 months consume USD 33,000. Credits run out during the eleventh month (10 x 2,750 = 27,500 leaves 2,500, which covers most of month 11); the remaining USD 3,000 is overage billed monthly in arrears at the contract overage rate. Send a commitment alert at [75 %] drawdown (USD 22,500, reached during month 9) so the account team can propose a renewal or top-up.

8. Quotas, limits and overage

LimitPlanTypeWarningAt limitOverage
Monthly API callsFreeHardEmail and console at 80 % and 100 %Requests rejected with HTTP 429 and a problem details body naming the limitNone; upgrade path shown
Monthly API callsTeamSoft80 %, 100 %, 150 %Requests continueGraduated tier pricing
Request rateAllHardResponse headers with remaining capacityThrottle with HTTP 429 and Retry-AfterNone
Monthly spend cap set by customerTeamCustomer-defined hard50 %, 80 %, 100 %Usage metrics with a cap stop; others continueNone beyond the cap
[Limit][Plan][Type][Warning][Action][Overage]

Quota decisions use the aggregator's running totals plus a local allowance per instance, so the hot path does not call a central service for every request. Accept a small overshoot (bounded by the allowance size) and state it in the terms. Rate limiting itself is designed with the rate limiter design (system-design/design-rate-limiter).

9. Invoicing and billing integration

ConcernOwnerInterface
Customer, subscription and price book masterBilling systemEvents to entitlement service and rating engine
Usage rating[Rating engine in metering / billing system]Rated line items per tenant, metric, period
TaxesBilling system with tax engineTax lines on invoice
Invoice issue and deliveryBilling systemInvoice event to product console and email
PaymentPayment processor via billing systemPayment status events
Credit notes and adjustmentsBilling system, approved by financeAdjustment events referencing invoice lines
Journal entriesBilling system to general ledgerSummarised journals per period

Send rated usage as idempotent line items keyed by tenant, metric, period and price book version, so resending after a failure cannot double-bill. Record money movements with the double-entry patterns in the payment ledger design (system-design/design-payment-ledger). Marketplace sales (cloud marketplaces) need usage reported to the marketplace's own metering interface; treat each marketplace as another billing channel with its own reconciliation.

10. Revenue recognition hooks

Revenue recognition follows the organisation's accounting policies under ASC 606 (United States GAAP) or IFRS 15 (International Financial Reporting Standards), decided by revenue accounting. The metering and billing design supplies the data below; it does not decide the accounting treatment.

HookData suppliedConsumer
Contract and performance obligation referenceContract ID, line IDs, start and end dates, commitment amountsRevenue system
Usage by periodRated usage per tenant, metric and period, with event-time basisRevenue system
Commitment drawdownOpening balance, drawdown, expiry, overage per periodRevenue system and deferred revenue schedules
Credits and refundsAdjustment events with reason codesRevenue system
Period close statusFlag that a period is closed and its totals are finalRevenue and finance close

11. Accuracy, reconciliation and audit

Check IDCompareGranularityToleranceFrequencyOwner
REC-001 (Example)Producer-side counters vs ingested eventsTenant, metric, hour0 after late windowHourly, final at close[@metering-lead]
REC-002 (Example)Raw store recomputation vs aggregator totalsTenant, metric, period0Daily and at close[@metering-lead]
REC-003 (Example)Aggregated quantities vs rated linesTenant, metric, period0At close[@billing-architect]
REC-004 (Example)Rated lines vs invoice linesInvoice line0After invoicing[@finance-systems-lead]
REC-005 (Example)Invoices vs ledger journalsCurrency, period0Monthly close[@revenue-accounting-lead]
REC-006 (Example)Dead-letter store backlogEventEmpty at close, or each item dispositionedDaily[@metering-lead]
[REC-NNN][Compare][Granularity][Tolerance][Frequency][@owner]

Audit rules: keep raw events, price book versions, rating outputs and adjustments for the retention period; log every manual adjustment with requester, approver and reason; give customers a usage export that sums to their invoice lines; and test the reconciliation jobs with seeded errors (duplicates, late events, missing hours) before go-live.

12. Tenancy, security and privacy

  • Derive the tenant from the authenticated context at the producer, never from client input, and validate it at ingestion against the subscription. Apply the tenancy patterns of the multi-tenancy design (architecture/multi-tenancy-design).
  • Authenticate producers with workload identities; only registered sources may emit each event type.
  • Separate duties: engineers deploy rating code; finance approves price books; nobody does both for the same change.
  • Minimise personal data in usage events: use pseudonymous user IDs for seat metrics and keep the mapping in the product.
  • Encrypt usage stores at rest; restrict raw event access to named roles, with access logged.
  • Keep usage in region where residency commitments apply and move only aggregates across regions.

13. Operations and service levels

IndicatorTargetAlert
Ingestion availability99.95 % monthlyBurn rate over [2x] for [1 h]
Event-to-console freshness95 % of events visible within [15 min]Freshness over [30 min]
Volume anomaly per tenant and metricWithin [3] standard deviations of the trailing 28-day patternDrop or spike outside the band
Dead-letter rateUnder [0.01 %] of eventsAbove threshold for [15 min]
Period close durationWithin [72 h] after period endClose not complete at [60 h]

Write runbooks for replay from the raw store, re-rating a period before invoicing, issuing a correction after invoicing, and handling a producer that sent wrong quantities. Keep them with the service runbook (dev/runbook).

14. Trade-offs, decisions and risks

DecisionOptionsChoice (Example)ReasonRevisit if
Who rates usageMetering service; billing platformBilling platform for standard plans; metering rates contract rate cardsKeeps price books in one place for most plansBilling platform cannot express contract terms
Event granularityPer action; pre-aggregated windowsPre-aggregated one-minute windows for API calls, per action for AI tokensVolume and cost versus evidenceCustomers require per-call evidence
DeduplicationStreaming window; persistent key storePersistent key store, 35-day horizonProducers may retry for days after outagesStorage cost exceeds [budget]
Quota enforcementCentral check per request; local allowanceLocal allowance with bounded overshootLatency and availabilityOvershoot complaints
Build or buy meteringIn-house pipeline; usage-billing product[Decision][Reason][Trigger]
IDRiskMitigationOwner
MTR-R-001 (Example)Under-billing from dropped events goes unnoticedREC-001 and volume anomaly alerts[@metering-lead]
MTR-R-002 (Example)Over-billing from duplicates damages trustIdempotency on source + id; customer usage export[@billing-architect]
MTR-R-003 (Example)Metric definition changes re-rate closed periodsVersioned definitions effective from a stated period[@product-pricing-lead]
MTR-R-004 (Example)Metering outage blocks the productProducer outbox; product does not wait on metering[@sre-lead]
[MTR-R-NNN][Risk][Mitigation][@owner]

15. Glossary and references

TermMeaning in this document
Billable metricPrecisely defined quantity that a price applies to
EntitlementWhat a tenant is allowed to use under its plan or contract
RatingApplying a price book to aggregated quantities to produce charges
Price bookVersioned set of prices, tiers and rules for a plan or contract
DrawdownConsumption of prepaid credits by rated usage
Late eventUsage event that arrives after its period's normal processing time
Idempotency keyValue that identifies an event so that repeats are recognised; here source + id
ReferenceVersion or date checkedUse
CloudEvents specification, cloudevents.io and github.com/cloudevents/spec1.0.2 (latest release; specversion value "1.0")Section 4
AWS Well-Architected Framework, SaaS Lens, docs.aws.amazon.comPublication date 4 April 2023Tenant cost, tiering and operations themes
RFC 9457, Problem Details for HTTP APIs2023Error bodies at limits
ASC 606 Revenue from Contracts with Customers (FASB); IFRS 15 Revenue from Contracts with Customers (IASB)Names onlySection 10
[Billing platform documentation][Version][Use]

Standard and licence note

Based on the CloudEvents 1.0.2 specification (Apache License 2.0) for the event envelope and on common SaaS metering and billing practice; tenant cost and tiering themes are aligned with the AWS Well-Architected SaaS Lens, which is cited and not reproduced. ASC 606 and IFRS 15 are named only; no text of either standard is used, and the revenue rows are a documentation format, not accounting advice. The structure, rules and worked examples are original to this collection. Check the current official specifications and your accounting policies before use. AWS and AWS Well-Architected are trademarks of their owners; this template is not affiliated with or endorsed by them. Template licence: MIT.

संबंधित टेम्पलेट