●SONNET 4.5 — Sonnet 4.5 was retired from the Claude API on 11/30. Calls now return an error. Move to Sonnet 5.5●PROJECTS — The Enterprise Analytics API now reports daily usage for the new projects experience (beta)●OPUS 4.5 — claude-opus-4-5 retires on 2027/1/22, 52 days from now. The replacement is claude-opus-5-5●LANGUAGE — Some users say Claude switches to another language mid-session while they write in English●NEW — New: Weekly usage looks like it jumped right after a plan upgrade? Check this first●COWORK — Handing Cowork a folder for the first time? Start with a task that only reads files●SONNET 4.5 — Sonnet 4.5 was retired from the Claude API on 11/30. Calls now return an error. Move to Sonnet 5.5●PROJECTS — The Enterprise Analytics API now reports daily usage for the new projects experience (beta)●OPUS 4.5 — claude-opus-4-5 retires on 2027/1/22, 52 days from now. The replacement is claude-opus-5-5●LANGUAGE — Some users say Claude switches to another language mid-session while they write in English●NEW — New: Weekly usage looks like it jumped right after a plan upgrade? Check this first●COWORK — Handing Cowork a folder for the first time? Start with a task that only reads files
Claude × Stripe Meter Events — Building a Usage-Based SaaS
Billing Claude API tokens through Stripe Meter Events: counting cache tokens correctly, the 24-hour identifier dedup window, why caps belong in a Durable Object rather than KV, cancellations, and daily reconciliation — checked against official docs as of November 2026.
The night I finished replaying a month of test traffic, I put two numbers side by side: the total on my Stripe meter, and the total in my own token log. They didn't match. The gap was around ten percent, and Stripe was always the lower one. It took me an uncomfortable evening to find it — my code had never counted a single token that came back from the prompt cache.
If you're about to put usage-based pricing on top of the Claude API, I suspect this is the kind of drift that will hurt you most. Overcharge and you lose trust; undercharge and your costs quietly pile up. What follows rebuilds the whole path as one flow: counting the tokens you should actually bill from Claude's usage, delivering them to Stripe Meter Events without double counts or gaps, enforcing caps, and undoing mistakes.
The stack is Cloudflare Workers + Durable Objects + Stripe, but the reasoning carries over to other platforms. Every price, limit, and API behavior below is what the official docs said when I checked them in November 2026.
Separate counting, stopping, and billing
Most usage-billing trouble comes from asking one component to do three jobs. A Stripe meter aggregates for invoicing — it will never stop a runaway customer. A home-grown cap counter, on the other hand, won't produce an invoice.
My ledger counts, my app stops, Stripe bills. I build these as three separate parts and reconcile them once a day. The steps below follow that order.
Job
Where it lives
What it must guarantee
Count (ledger)
Your own DB (D1 or similar)
One row per request, the identifier, and its send status
Stop (caps)
A Durable Object per customer
Updates for one customer happen in order and are readable immediately
Bill
Stripe Meter + Price
Aggregation, invoice generation, and the finalization grace period
Your options as of November 2026
Stripe used to offer Usage Records for metered billing. Since API version 2025-03-31.basil, legacy metered prices — usage_type=metered without a meter — can no longer be created or attached to subscriptions. If you're starting today, meters are the default path.
Within meters, there are still three ways to report usage:
Approach
Throughput (per Stripe docs)
Good fit
Watch out for
Own counter, compute the bill at month end
Whatever your DB handles
Complex tiering, or a human review before invoicing
You write invoicing, proration, and corrections yourself
Meter Events (API v1)
1,000 calls/sec per account in live mode, plus one concurrent call per customer per meter
Most SaaS products from launch to mid-scale
Parallel sends for the same customer collide
Meter event streams (API v2)
Up to 10,000 events/sec, live mode only
High-volume services
Session tokens expire after 15 minutes and must be recreated
The decision fits in one line: if a single customer can send you several requests per second, use v2; otherwise send v1 events in series. The code in this article uses v1 and serializes per customer through a Durable Object. I haven't run the v2 SDK calls end to end myself, so I'm leaving that code out rather than guessing.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦You'll count billable input as the three-field usage sum with cost weights, so your ledger and Stripe drift to 0
✦You'll stop cross-day double counts by treating your ledger's sent status as truth, since identifier dedup lasts about 24 hours
✦You'll enforce per-customer caps in a Durable Object instead of KV, which allows only 1 write per second per key
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
In the Stripe Dashboard, go to Billing → Meters and create two meters — one for input, one for output. Claude prices input and output differently, so a single combined meter undercharges exactly the customers who generate the most output.
Event name: claude_input_tokens and claude_output_tokens
Aggregation: Sum
Value payload key: tokens
Customer mapping payload key: stripe_customer_id (the default)
Then create a usage-based Price attached to each meter. If your base plan includes an allowance, use graduated tiers with the first tier priced at zero.
claude_output_tokens (example, graduated)
0 – 2,000,000 tokens → 0 (included in the base fee)
2,000,001+ tokens → X per 1M tokens
Keep sandbox and live separate, obviously — but during development I'd also prefix event names with dev_. I skipped that early on and pushed test events into a live meter. A visible prefix would have caught it in seconds.
Step 2: Count the tokens you should actually bill
This is where my ten percent went. In the Messages API usage object, input_tokens excludes cache writes and cache reads. The prompt caching docs describe total input as the sum of three fields:
total input = cache_read_input_tokens + cache_creation_input_tokens + input_tokens
Code that only counts input_tokens starts leaking revenue the moment you enable caching. But billing all three at the same rate has the opposite problem: you never pass the cache discount on. For Sonnet 4.6, the official pricing table (November 2026) lists input at $3, 5-minute cache writes at $3.75, cache reads at $0.30, and output at $15, all per million tokens.
What worked for me was folding input into one cost-weighted number:
// src/lib/billable-tokens.tsimport type Anthropic from "@anthropic-ai/sdk";// Weights that express cache traffic in "plain input token" units.// Ratios of Sonnet 4.6 list prices as of Nov 2026: 3.75 / 3 = 1.25, 0.30 / 3 = 0.1const WEIGHT = { cacheWrite: 1.25, cacheRead: 0.1 } as const;export function billableTokens(u: Anthropic.Usage) { const cacheWrite = u.cache_creation_input_tokens ?? 0; const cacheRead = u.cache_read_input_tokens ?? 0; const input = Math.ceil( u.input_tokens + cacheWrite * WEIGHT.cacheWrite + cacheRead * WEIGHT.cacheRead ); return { input, // sent to claude_input_tokens output: u.output_tokens, // sent to claude_output_tokens raw: { input: u.input_tokens, cacheWrite, cacheRead }, // keep the raw values in the ledger };}
The weighting keeps one customer-facing unit while preserving the ratio to your real cost. I still store the raw, unweighted values. When list prices change, I want to be able to reinterpret old rows correctly instead of guessing.
If you let customers pick models, make the weights a per-model table and refuse to send anything for a model that isn't in it. Failing closed is far cheaper than discovering a mispriced month.
Step 3: Send the meter event — identifier, strings, timestamp
The send itself is short. The contract around it has four parts:
payload is a map of strings. The stripe-node types declare it as { [key: string]: string }.
identifier deduplicates events, but Stripe enforces uniqueness over "a rolling period of at least 24 hours" — not forever.
timestamp must be within the past 35 days and no more than 5 minutes in the future.
Accepted doesn't mean invoiced. Only usage that arrives before the invoice finalizes — by default, a one-hour grace period after the period ends — lands on that invoice.
// src/lib/stripe-meter.tsimport Stripe from "stripe";// Omit apiVersion to use the version the SDK shipped with; if you pin it, match your SDK release.export const stripe = new Stripe(STRIPE_SECRET_KEY, { maxNetworkRetries: 2, // SDK-level retries; the SDK attaches idempotency keys httpClient: Stripe.createFetchHttpClient(),});export type MeterRow = { identifier: string; // e.g. msg_xxx:out eventName: "claude_input_tokens" | "claude_output_tokens"; customerId: string; tokens: number; occurredAt: number; // UNIX seconds, when Claude's response arrived};export async function sendMeterEvent(row: MeterRow) { return stripe.billing.meterEvents.create({ event_name: row.eventName, identifier: row.identifier, timestamp: row.occurredAt, // retries still count at the time of use payload: { stripe_customer_id: row.customerId, tokens: String(row.tokens), }, });}
For the identifier, I use Claude's response ID (the msg_ value) with a suffix per meter. Reusing the bare ID for both input and output makes later investigation confusing, even though they land on different meters.
Write to the ledger first — and handle resends past 24 hours
The easiest thing to miss here is that the dedup window is roughly a day. If a Stripe incident or your own bug stalls delivery and you resend the next day, the same identifier can be counted twice.
So the source of truth for "was this sent?" lives in your ledger. When Claude responds, insert a pending row first; flip it to sent only after Stripe accepts it. The replay job picks up pending rows and nothing else.
// src/jobs/replay-meter.ts (called from a Cron Trigger every 5 minutes)const DAY = 24 * 60 * 60;export async function replayPending(db: D1Database) { const now = Math.floor(Date.now() / 1000); const { results } = await db .prepare("SELECT * FROM meter_ledger WHERE status = 'pending' ORDER BY occurredAt LIMIT 100") .all<MeterRow & { status: string }>(); for (const row of results) { // sequential on purpose: one concurrent call per customer per meter if (now - row.occurredAt > 35 * DAY) { await mark(db, row.identifier, "expired"); // Stripe won't accept it anymore; handle via credits continue; } try { await sendMeterEvent(row); await mark(db, row.identifier, "sent"); } catch (err) { await mark(db, row.identifier, "pending", String(err)); } }}
Here's the ledger table and the two helpers the code above relies on:
// migrations/0001_meter_ledger.sql// CREATE TABLE meter_ledger (// identifier TEXT PRIMARY KEY, -- msg_xxx:in / msg_xxx:out// eventName TEXT NOT NULL,// customerId TEXT NOT NULL,// tokens INTEGER NOT NULL,// occurredAt INTEGER NOT NULL, -- UNIX seconds// status TEXT NOT NULL DEFAULT 'pending', -- pending / sent / expired / canceled / credited// lastError TEXT// );export function insertLedger(db: D1Database, r: MeterRow) { return db .prepare("INSERT OR IGNORE INTO meter_ledger (identifier, eventName, customerId, tokens, occurredAt) VALUES (?, ?, ?, ?, ?)") .bind(r.identifier, r.eventName, r.customerId, r.tokens, r.occurredAt);}export async function mark(db: D1Database, identifier: string, status: string, lastError: string | null = null) { await db.prepare("UPDATE meter_ledger SET status = ?, lastError = ? WHERE identifier = ?") .bind(status, lastError, identifier).run();}
With the identifier as the primary key, writing the same response twice still leaves one row. A row marked sent is never sent again, so you're no longer relying on Stripe's 24-hour window. Rows marked expired need a human; I get a notification on any day where that count isn't zero.
Step 4: Enforce caps — why a Durable Object, not KV
You'll see plenty of examples that keep a monthly counter in Workers KV. I started there too. But KV allows only one write per second to the same key (per the official limits page, November 2026). Rewriting one customer's monthly key on every request starts failing under modest load, and because reads are eventually consistent, two simultaneous requests can both see "under the limit."
Once I accepted that a cap belongs somewhere updates for one customer happen in order, I moved it into a Durable Object per customer.
// src/do/usage-counter.tsimport { DurableObject } from "cloudflare:workers";type Op = { op: "check" } | { op: "add"; tokens: number };export class UsageCounter extends DurableObject { async fetch(req: Request): Promise<Response> { const body = (await req.json()) as Op; const month = new Date().toISOString().slice(0, 7); // 2026-11 const key = `used:${month}`; const limit = 5_000_000; // look this up from the customer's plan const used = (await this.ctx.storage.get<number>(key)) ?? 0; if (body.op === "check") { return Response.json({ ok: used < limit, used, limit }, { status: used < limit ? 200 : 429 }); } const next = used + body.tokens; await this.ctx.storage.put(key, next); return Response.json({ ok: true, used: next, limit }); }}
The caller sends check before calling Claude, and add after the response arrives:
// src/lib/claude-with-metering.tsimport Anthropic from "@anthropic-ai/sdk";import { billableTokens } from "./billable-tokens";export async function callClaude(env: Env, customerId: string, prompt: string) { const counter = env.USAGE_COUNTER.get(env.USAGE_COUNTER.idFromName(customerId)); const pre = await counter.fetch("https://do/", { method: "POST", body: JSON.stringify({ op: "check" }) }); if (pre.status === 429) throw new Error("monthly_limit_reached"); const anthropic = new Anthropic({ apiKey: env.ANTHROPIC_API_KEY }); const res = await anthropic.messages.create({ model: "claude-sonnet-4-6", max_tokens: 2048, // also the ceiling on how far one call can overshoot messages: [{ role: "user", content: prompt }], }); const t = billableTokens(res.usage); const now = Math.floor(Date.now() / 1000); await env.DB.batch([ // ledger first; sending happens later and survives failures insertLedger(env.DB, { identifier: `${res.id}:in`, eventName: "claude_input_tokens", customerId, tokens: t.input, occurredAt: now }), insertLedger(env.DB, { identifier: `${res.id}:out`, eventName: "claude_output_tokens", customerId, tokens: t.output, occurredAt: now }), ]); await counter.fetch("https://do/", { method: "POST", body: JSON.stringify({ op: "add", tokens: t.input + t.output }) }); return res;}
With this shape, the most a customer can exceed the cap by is one call that started just under it — and max_tokens bounds that call. If you can't tolerate even that, reserve max_tokens up front and refund the difference after the response.
A side effect I didn't plan for: because sending goes through the ledger, the Stripe round trip is no longer on the response path.
Step 5: Undo wrong usage — within 24 hours and after
Older write-ups say meter events can't be undone. As of November 2026 you can cancel one with a Meter Event Adjustment by identifier — but only for events sent to Stripe within the last 24 hours.
// Within 24 hours: cancel the event itselfawait stripe.billing.meterEventAdjustments.create({ event_name: "claude_output_tokens", type: "cancel", cancel: { identifier: "msg_xxx:out" },});
Past that window, or once the usage is on a finalized invoice, canceling won't fix the invoice. Issue a credit note against it instead:
// Finalized invoice: offset with a credit noteawait stripe.creditNotes.create({ invoice: invoiceId, credit_amount: amountInSmallestUnit, // credited to the customer balance, applied to the next invoice reason: "duplicate", // duplicate / fraudulent / order_change / product_unsatisfactory memo: "Offsetting a double-counted request",});
Either way, update the ledger row to canceled or credited, and subtract the tokens from the Durable Object's monthly counter. Otherwise the customer hits their cap early for usage you already gave back.
Step 6: Reconcile daily — summaries and error events
The reliable way to know whether events were aggregated is to ask Stripe. Meter Event Summaries give you per-meter totals:
The second signal is events Stripe accepted and later rejected. Asynchronous failures — customer not found, unreadable value, timestamp too old — arrive as v1.billing.meter.error_report_triggered (or v1.billing.meter.no_meter_found when no meter matches the event name). Subscribe to both from an event destination in Workbench using the Thin payload style.
When verifying webhook signatures on Workers, use constructEventAsync rather than the synchronous constructEvent. Stripe's own Workers sample does the same.
Troubleshooting table
Symptom
Likely cause
How to confirm
Fix
Stripe total lower than your ledger
Cache tokens not counted
Sum ledger rows where raw cacheRead is non-zero
Count the three-field sum from Step 2
Sends fail intermittently for one customer
v1 allows one concurrent call per customer per meter
Check whether failures cluster on parallel sends for the same customer
Serialize per customer, or move to v2 streams
Next-day resend counted twice
Identifier uniqueness lasts about 24 hours
Look for the same identifier sent on two different days
Treat ledger "sent" as truth; replay only "pending"
Accepted, but missing from the invoice
Arrived after finalization (default 1-hour grace period)
Compare event timestamp with invoice finalization time
Replay sooner, or extend the grace period (up to 72 hours)
Events never appear in the Dashboard
Wrong customer mapping key or customer ID
meter_event_customer_not_found in error_report_triggered
Match payload keys to the meter configuration
Customer exceeded the cap
KV eventual consistency and the same-key write limit
Check for simultaneous requests from one customer
Move the cap into a Durable Object; bound with max_tokens
Three misconceptions worth correcting
"An identifier prevents double counting forever." Stripe's wording is uniqueness "within a rolling period of at least 24 hours," aimed at immediate retries. Protection against resends across days has to live in your ledger.
"The Customer Portal can handle plan changes for metered plans." The portal's documented limitations say subscriptions with usage-based billing can be canceled there but not updated. Build plan changes in your own UI against the Subscriptions API.
"Just send the token count as a number." The API takes form-encoded values and stripe-node types the payload as strings. String(tokens) is the safe habit. Decimals are accepted too, so decide whether weighted fractions round up or go through as decimals.
Base fee plus overage, and checking your margins
A base fee with an included allowance and per-token overage has been the easiest structure for me to explain to both light and heavy users. Lowering the overage rate on higher tiers gives heavy users a natural reason to move up.
Estimate input and output separately. Say a customer on Sonnet 4.6 uses 8M input tokens in a month — 5M of them cache reads — and 1M output tokens:
Output alone is close to sixty percent of the cost. With one combined meter at a single rate, this customer's bill would have been badly off. I keep the price table in my own spreadsheet and update the weights and estimates on the same day the official pricing changes.
The next thing that will move your numbers: model changes
Once billing runs smoothly, the next shift comes from changing models. The official pricing page notes that Claude 4.7 and later models use a newer tokenizer that produces roughly 30% more tokens for the same text. Same unit price, bigger bill.
Before migrating, run the same inputs through the old and new models, compare usage, and decide up front whether to hold the customer price or raise the included allowance. I'd much rather make that call before the support inbox makes it for me. For concrete numbers on how token counts inflate, see where Haiku 5.5 bills jump on long prompts.
Start by watching the drift reach zero in test mode
You don't need to build all of this at once. Create one meter in test mode, call Claude a handful of times, and confirm the next day that the reconciliation drift is zero. Mix in one cached call, and you'll verify the Step 2 counting at the same time.
A week of zero-drift days before going live — that's the one order of operations I keep, however rushed the launch feels.
Share
Thank You for Reading
Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.