Skip to main content
Back to Community & Earn Hub
Q&A Questionai-agents +150 pt Bounty

Stripe Billing Meters for AI SaaS Agents: How to report real-time LLM token usage & MCP tool credits without blocking FastAPI response latency?

@priya_sharma4 days ago 1538 views

Like most US AI SaaS teams, we are moving away from unlimited $20/month seats to Stripe Billing Meters (v1/billing/meter_events) to charge accurately for frontier LLM tokens and expensive MCP tool executions (e.g., headless browser runs).

The Latency & Double-Billing Problem

Right now, after our FastAPI agent finishes streaming tokens:

python
# Naive inline Stripe call
stripe.billing.MeterEvent.create(
    event_name="agent_tokens_consumed",
    payload={"stripe_customer_id": cust_id, "value": str(total_tokens)},
)

In production:

  1. Calling Stripe's REST API inline adds 250–400ms to request teardown, and if Stripe has a transient 502 or rate limit, our SSE stream throws an error after the user already got their answer!
  2. Retrying failed background jobs without deterministic event IDs causes duplicate billing for the same agent turn.

How do we aggregate high-frequency token usage in Redis and flush idempotent meter events to Stripe cleanly?

2 Answers

Community Answers

@aarav_sharma Accepted Answer4 days ago

Never call stripe.billing.MeterEvent.create() on the hot FastAPI request path! Stripe's Billing Meters API is built specifically for high-throughput asynchronous batching with built-in identifier idempotency (24-hour deduplication window).

Here is the production pattern using Redis HINCRBY + a periodic background worker:


1. Accumulate Usage in Redis in <0.5ms (Hot Path)

At the end of an agent turn, atomically increment a time-bucketed Redis hash key (YYYYMMDDHHMM 1-minute bucket) so 1,000 rapid tool calls collapse into 1 Stripe API call per customer per minute:

python
from datetime import datetime, timezone

async def record_usage_fast(redis, customer_id: str, tokens: int):
    # Bucket by minute so we stay well below Stripe's 1,000 req/s meter rate limit
    bucket = datetime.now(timezone.utc).strftime("%Y%m%d%H%M")
    key = f"usage:stripe:{bucket}"
    await redis.hincrby(key, customer_id, tokens)
    await redis.expire(key, 7200)  # 2-hour safety TTL

2. Flush Completed Buckets Asynchronously with Deterministic Idempotency

Every 60 seconds, a background worker reads completed minute buckets (bucket < current_minute) and sends one idempotent MeterEvent per customer using identifier=f"{bucket}:{customer_id}":

python
import stripe

async def flush_usage_bucket(redis, bucket: str):
    key = f"usage:stripe:{bucket}"
    entries = await redis.hgetall(key)

    for raw_cust_id, raw_tokens in entries.items():
        cust_id = raw_cust_id.decode() if isinstance(raw_cust_id, bytes) else raw_cust_id
        tokens = int(raw_tokens)
        if tokens <= 0:
            continue

        # Stripe guarantees deduplication for 24h on identical `identifier`!
        await stripe.billing.MeterEvent.create_async(
            event_name="agent_tokens_consumed",
            payload={
                "stripe_customer_id": cust_id,
                "value": str(tokens),
            },
            identifier=f"tok:{bucket}:{cust_id}",
        )
        await redis.hdel(key, cust_id)

Why This Works in Production:

  • 0ms FastAPI Overhead: User responses finish immediately without waiting on Stripe's API.
  • Zero Double-Billing: Even if your Celery/cron worker crashes halfway through a bucket and retries, Stripe's identifier deduplicates identical events automatically.
@devon_brooks3 days ago

Moving Stripe MeterEvent reporting off the FastAPI request path into a 60s Redis HINCRBY batch flusher cut our p99 chat latency by 310ms immediately. Stripe's 24h identifier idempotency window handles worker retries cleanly.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.