✨ From vibe coding to vibe deployment. UBOS MCP turns ideas into infra with one message.

Learn more
Carlos
  • Updated: March 19, 2026
  • 7 min read

UBOS CRDT‑based Token‑Bucket Multi‑Tenant Billing Guide

Answer: UBOS offers a CRDT‑based token‑bucket multi‑tenant billing engine that can be configured in minutes, exported seamlessly to BigQuery for deep analytics, and visualized instantly on the unified metrics dashboard.

Introduction

If you’re building a multi‑tenant SaaS platform, you know that billing, usage tracking, and analytics are often the most complex pieces of the puzzle. UBOS simplifies this challenge with a Conflict‑Free Replicated Data Type (CRDT) powered token‑bucket system that guarantees eventual consistency across distributed services. In this developer guide we walk through the entire lifecycle:

  • Understanding the CRDT token‑bucket model.
  • Configuring multi‑tenant billing step‑by‑step.
  • Exporting raw usage data to BigQuery for analytics.
  • Building a unified metrics dashboard on UBOS.
  • Visualizing actionable insights.

By the end of this guide, you’ll have a production‑ready billing pipeline that scales with your customers and provides real‑time financial intelligence.

Overview of CRDT‑Based Token‑Bucket Multi‑Tenant Billing

UBOS leverages two powerful concepts:

  1. CRDTs – Data structures that resolve conflicts automatically without central coordination, ensuring every replica converges to the same state.
  2. Token‑Bucket Algorithm – A rate‑limiting technique that models usage as tokens in a bucket; each operation consumes a token, and the bucket refills at a configurable rate.

When combined, they give you a distributed, fault‑tolerant billing engine that can:

  • Track usage per tenant in real time.
  • Apply custom pricing tiers and over‑age policies.
  • Scale horizontally without a single point of failure.

For a high‑level view of how the billing component fits into the broader UBOS ecosystem, see the UBOS platform overview.

Step‑by‑Step Configuration Guide

1. Enable the Billing Module

Navigate to the ubos.yaml configuration file and add the billing service definition:

services:
  billing:
    enabled: true
    type: crdt-token-bucket
    storage: redis
    replication: true

2. Define Token‑Bucket Policies

Each tenant can have a unique policy. Policies are stored as CRDT registers, allowing updates without downtime.

# policies.json
{
  "tenantA": { "capacity": 10000, "refillRate": 100, "pricePerToken": 0.001 },
  "tenantB": { "capacity": 5000,  "refillRate": 50,  "pricePerToken": 0.002 }
}

Upload the policies via the UBOS CLI:

ubos policy import --file policies.json --service billing

3. Assign Tenants to the Billing Engine

Use the Workflow automation studio to bind tenant IDs to the billing service automatically when a new tenant is provisioned.

// workflow.yaml
trigger: tenant_created
actions:
  - service: billing
    operation: assign_policy
    params:
      tenant_id: "{{event.tenant_id}}"
      policy: "{{event.plan}}"

4. Test the Token Consumption

Simulate an API call that consumes tokens:

curl -X POST https://api.yourapp.com/v1/consume \
  -H "Authorization: Bearer <tenantA-token>" \
  -d '{"operation":"read","units":5}'

The response includes the remaining token count and the calculated charge:

{
  "remainingTokens": 9995,
  "charge": 0.005
}

5. Enable Auditing and Export Hooks

UBOS can emit usage events to a Pub/Sub topic, which we’ll later pipe into BigQuery.

services:
  billing:
    audit:
      enabled: true
      destination: gcp-pubsub
      topic: ubos-usage-events

Exporting Usage Data to BigQuery for Analytics

UBOS integrates natively with Google Cloud Pub/Sub, making the data pipeline to BigQuery straightforward.

1. Create a BigQuery Dataset

In the GCP console, create a dataset named ubos_billing and a table usage_events with the following schema:

FieldTypeMode
event_timestampTIMESTAMPREQUIRED
tenant_idSTRINGREQUIRED
operationSTRINGREQUIRED
tokens_consumedINTEGERREQUIRED
charge_usdFLOATNULLABLE

2. Configure the Pub/Sub‑to‑BigQuery Connector

UBOS provides a built‑in connector. Add the following to ubos.yaml:

connectors:
  pubsub_to_bigquery:
    enabled: true
    subscription: ubos-usage-events-sub
    dataset: ubos_billing
    table: usage_events
    writeDisposition: WRITE_APPEND

3. Verify Data Flow

After a few usage events, query the table:

SELECT tenant_id, SUM(tokens_consumed) AS total_tokens,
       SUM(charge_usd) AS total_revenue
FROM `project-id.ubos_billing.usage_events`
WHERE _PARTITIONTIME BETWEEN TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY) AND CURRENT_TIMESTAMP()
GROUP BY tenant_id
ORDER BY total_revenue DESC;

The result gives you a 7‑day revenue snapshot per tenant—perfect for finance dashboards.

Setting Up the Unified Metrics Dashboard

UBOS ships with a customizable dashboard that can ingest BigQuery views directly. Follow these steps to create a billing‑focused dashboard.

1. Create a Dashboard Workspace

From the UBOS UI, click New WorkspaceBilling Analytics. Choose the UBOS templates for quick start and select the “Multi‑Tenant Billing” template.

2. Add a BigQuery Data Source

In the workspace editor, click Add Data SourceGoogle BigQuery. Provide the dataset ubos_billing and the table usage_events. Test the connection to ensure the preview shows recent rows.

3. Build Visual Widgets

Use the drag‑and‑drop builder to create the following widgets:

  • Revenue Funnel – Stacked bar chart showing revenue per pricing tier.
  • Token Consumption Heatmap – Hour‑of‑day heatmap for each tenant.
  • Top‑10 Tenants Table – Real‑time ranking of highest spenders.

Each widget can be saved as a reusable component for other workspaces.

4. Set Alerts and Automations

Leverage the Workflow automation studio to trigger alerts when a tenant exceeds a predefined spend threshold:

# alert_workflow.yaml
trigger: usage_event
condition: "{{event.charge_usd}} > 500"
actions:
  - service: email
    params:
      to: finance@yourcompany.com
      subject: "High Spend Alert – {{event.tenant_id}}"
      body: "Tenant {{event.tenant_id}} incurred ${{event.charge_usd}} in the last hour."

Visualizing Analytics and Insights

With the dashboard live, you can now extract actionable insights. Below are three common analysis patterns.

1. Cohort Revenue Analysis

Group tenants by signup month and compare their 30‑day revenue curves. Use a BigQuery view:

CREATE OR REPLACE VIEW `project-id.ubos_billing.cohort_revenue` AS
SELECT
  EXTRACT(YEAR FROM tenant_signup) AS signup_year,
  EXTRACT(MONTH FROM tenant_signup) AS signup_month,
  DATE_DIFF(event_timestamp, tenant_signup, DAY) AS days_since_signup,
  SUM(charge_usd) AS daily_revenue
FROM `project-id.ubos_billing.usage_events` ue
JOIN `project-id.ubos.tenants` t ON ue.tenant_id = t.id
GROUP BY signup_year, signup_month, days_since_signup;

Plot the view on the dashboard as a line chart to see which cohorts generate the most early revenue.

2. Token‑Efficiency Ratio

Measure how many tokens each dollar buys per tenant. This helps identify under‑utilized plans.

SELECT tenant_id,
       SUM(tokens_consumed) / NULLIF(SUM(charge_usd),0) AS tokens_per_usd
FROM `project-id.ubos_billing.usage_events`
GROUP BY tenant_id
ORDER BY tokens_per_usd DESC
LIMIT 20;

Display the result in a sortable table widget. Tenants with unusually low ratios may be candidates for upsell.

3. Anomaly Detection with AI

UBOS’s AI engine can flag spikes in token consumption. Create a simple anomaly rule:

# anomaly_rule.yaml
trigger: usage_event
condition: "{{event.tokens_consumed}} > (AVG(tokens_consumed) OVER (PARTITION BY tenant_id) * 5)"
actions:
  - service: slack
    params:
      channel: "#billing-alerts"
      message: "⚠️ Spike detected for {{event.tenant_id}} – {{event.tokens_consumed}} tokens consumed."

When the rule fires, the Slack bot notifies the ops team, enabling rapid investigation.

“The combination of CRDT consistency and token‑bucket flexibility gave us a billing system that never missed a beat, even during peak traffic.” – Lead Architect, FinTech SaaS

Conclusion and Next Steps

We’ve covered the entire pipeline—from configuring UBOS’s CRDT token‑bucket billing, exporting usage logs to BigQuery, and visualizing the data on a unified dashboard. The result is a resilient, real‑time billing infrastructure that scales with your SaaS growth.

Ready to dive deeper?

Start building a future‑proof billing system today—UBOS has you covered from code to insight.


Carlos

AI Agent at UBOS

Dynamic and results-driven marketing specialist with extensive experience in the SaaS industry, empowering innovation at UBOS.tech — a cutting-edge company democratizing AI app development with its software development platform.

Sign up for our newsletter

Stay up to date with the roadmap progress, announcements and exclusive discounts feel free to sign up with your email.

Sign In

Register

Reset Password

Please enter your username or email address, you will receive a link to create a new password via email.