- Updated: March 25, 2026
- 3 min read
Implementing Usage‑Based (Metered) Billing in the OpenClaw SaaS Boilerplate
## Introduction
Implementing usage‑based (metered) billing in the OpenClaw SaaS boilerplate enables developers to charge customers based on actual consumption of resources or features. This article walks you through the design, configuration, and deployment steps, including code snippets, Stripe integration, and best‑practice recommendations.
—
### 1. Architectural Overview
– **OpenClaw Core**: Handles tenant management, feature toggles, and usage tracking.
– **Metering Service**: Collects usage events (e.g., API calls, storage bytes) and stores them in a time‑series database.
– **Billing Service**: Periodically aggregates usage, creates Stripe invoice items, and triggers invoice generation.
– **Stripe**: Payment gateway for subscription and one‑time usage charges.
—
### 2. Designing the Metering Model
1. **Define Metered Features**
{
“features”: [
{“id”: “api_calls”, “unit”: “call”, “price_per_unit”: 0.001},
{“id”: “storage_gb”, “unit”: “GB”, “price_per_unit”: 0.10}
]
}
2. **Create Usage Events**
python
def record_event(tenant_id, feature_id, quantity):
event = {
“tenant_id”: tenant_id,
“feature_id”: feature_id,
“quantity”: quantity,
“timestamp”: datetime.utcnow().isoformat()
}
redis.rpush(‘usage_events’, json.dumps(event))
3. **Persist Events**
Use a lightweight time‑series DB (e.g., InfluxDB) or a regular relational table with indexes on `tenant_id` and `timestamp`.
—
### 3. Configuring Stripe for Metered Billing
1. **Create a Product & Price in Stripe**
bash
stripe products create –name “OpenClaw API Calls”
stripe prices create \
–unit-amount 0.10 \
–currency usd \
–recurring “interval=month,usage_type=metered” \
–product
2. **Attach the Price to a Subscription**
python
stripe.Subscription.create(
customer=customer_id,
items=[{“price”: METRED_PRICE_ID}],
expand=[“latest_invoice.payment_intent”]
)
3. **Report Usage to Stripe**
python
stripe.SubscriptionItem.create_usage_record(
subscription_item_id,
quantity=usage_quantity,
timestamp=int(time.time()),
action=”set”
)
—
### 4. Implementing the Billing Service
python
import stripe
from datetime import datetime, timedelta
stripe.api_key = os.getenv(‘STRIPE_SECRET_KEY’)
def aggregate_and_bill():
# 1. Get usage for the previous billing period
start = datetime.utcnow().replace(day=1) – timedelta(days=1)
end = datetime.utcnow().replace(day=1)
usage = query_usage(start, end) # Returns dict {tenant_id: {feature_id: qty}}
for tenant_id, features in usage.items():
sub = get_stripe_subscription(tenant_id)
for feature_id, qty in features.items():
item_id = get_subscription_item_id(sub, feature_id)
stripe.SubscriptionItem.create_usage_record(
item_id,
quantity=qty,
timestamp=int(end.timestamp()),
action=’set’
)
# Stripe will automatically generate the invoice at period end.
—
### 5. Deploying to UBOS
1. **Add the Blog Content to the Repository**
bash
mkdir -p ubos/content/blog
cat > ubos/content/blog/usage-based-billing.md <<'EOF'
(Paste the full article markdown here)
EOF
2. **Update `docker-compose.yml`** to include the new service if you run a separate metering container.
3. **Push Changes**
bash
git add .
git commit -m "Add usage‑based billing article"
git push origin main
4. **Deploy with UBOS**
bash
ubos deploy
UBOS will rebuild the Docker images and restart the stack, making the article available at `/blog/usage-based-billing`.
—
### 6. Best‑Practice Recommendations
| Recommendation | Reason |
|—————-|——–|
| **Idempotent Usage Reporting** | Prevent duplicate charges if a job retries. |
| **Graceful Degradation** | If Stripe is unavailable, queue usage records locally and sync later. |
| **Transparent Customer Dashboard** | Show real‑time usage and upcoming invoice details. |
| **Rate Limiting** | Protect your metering endpoint from abuse. |
| **Testing in Stripe Test Mode** | Validate the whole flow without real charges. |
—
### 7. Conclusion
By following the steps above, you can extend the OpenClaw SaaS boilerplate with robust usage‑based billing powered by Stripe. This enables flexible monetisation models while keeping the developer experience smooth.
—
**Reference**: For more details on hosting OpenClaw on UBOS, see the guide at https://ubos.tech/host-openclaw/