惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
The Cloudflare Blog
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园_首页
F
Fortinet All Blogs
J
Java Code Geeks
人人都是产品经理
人人都是产品经理
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
爱范儿
爱范儿
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog RSS Feed
博客园 - 聂微东
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
小众软件
小众软件
Y
Y Combinator Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
S
SegmentFault 最新的问题
有赞技术团队
有赞技术团队

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Billing asynchronous work exactly once
Hideki Mori · 2026-06-24 · via DEV Community

Synchronous billing is easy, and that's the problem — it makes you think all billing is easy.

When a request does its work inline, the billable number is in the response by the time you send it. The gateway meters from there — the meter write, retries and all, is its problem, not yours. From your side, synchronous billing is one number in the response.

Asynchronous work breaks that. The request submits a job; the work happens later, in a worker; the result comes back through a poll or a callback. And the thing you bill for — characters processed, pages converted — isn't known when the request arrives. It's known when the job finishes.

So you can't meter at the edge. The meter has to fire from the completion path. And the real difficulty is firing it exactly once per unit of completed work — because requests, polls, and retries all conspire to make that zero times or many times.

This is platform-agnostic. Every submit-process-poll API has it. I'll use the system I run as the example, but the shape is the same anywhere.


Three ways metering goes wrong

On arrival. Carry the synchronous habit over and you meter when the job is submitted. But you don't know the size yet, so you're forced into a crude flat fee — or you bill for work that hasn't happened and might fail. Wrong unit, wrong time.

On retrieval. The subtle one. You wire the meter to fire when the client fetches the result. Now a client who submits a job, lets it run — costing you real money downstream — and never bothers to poll is never billed. You did the work for free. "Completion" is not "the client picked up the result." It's the worker finishing.

Without a fixed quantity. Input characters or output characters? Pages before OCR or after? If you haven't decided exactly what you measure and where, invoices drift and customers argue. Decide once; measure there.

All three point the same way: meter on measured work-completion, with a fixed definition of the unit. Not on arrival. Not on retrieval.


The mechanism: a durable outbox

In synchronous billing the gateway took the numbers off the response and metered them for you. Async takes that away: the numbers exist only in the worker, after the request has returned. So completion itself has to become a durable event.

The completion path writes a metering task — the job's measured quantities — into a durable outbox: a table that is the source of truth for what still needs sending. Something drains it, sends each task to the meter, records the outcome; a failed send stays in the table and is retried until it lands. (In my system a once-a-minute batch does the draining. The interval doesn't matter; the durability does.)

It has a name — the transactional outbox pattern — though it's the sort of thing you'd build without the name. And it is, exactly, the one rule the rest of the system already runs on: when the job finishes, report it reliably — retry as much as possible, return the result. Metering is just one more result that has to be reported reliably. I didn't build a billing system. I pointed the engine's own discipline at billing.


Exactly once = at-least-once × at-most-once

The outbox gives me at-least-once. A meter event is never silently dropped, because a failed send leaves the task in place to retry.

But at-least-once, on its own, double-charges. The classic failure: the send succeeds, the acknowledgement is lost on the way back, the task looks failed, the next run resends — and now it is counted twice.

So at-least-once needs a partner: an idempotent sink. Send the same meter ID twice, it counts once. That is at-most-once.

exactly-once = outbox (at-least-once) × idempotent sink (at-most-once)

Neither half is enough alone. I learned the second one the hard way — the same outbox-and-retry code, pointed at two different metering backends. One deduplicated on the ID and the numbers stayed clean. The other didn't, and the retries double-charged. Same mechanism, different sink, different bill.

So the thing worth writing down isn't "this platform guarantees idempotency." Platforms change. The durable statement is: this pattern requires an idempotent sink. If yours doesn't deduplicate, your retries are a liability, not a safety net.


Bill on success, and survive retries

Two more places it bites.

Success, not completion. Fire the meter on successful completion — not on "the job reached a terminal state." A failed job must not emit a billable event. Wire it to the wrong terminal state and you charge people for errors, then spend your week on refunds.

Partial failure. What you bill on a half-finished job depends on whether half a result is worth anything. A text extraction fans out into many independent calls; if nine of ten succeed and one fails for good, you bill the nine — the successful work has standalone value. Document conversion is the opposite: a file that converts eight of ten pages and then dies isn't eighty percent of a document, it's a corrupted one. No charge, nothing returned. Bill at the granularity where partial output has value.

Retries. The engine retries aggressively — that is the point of it. Meter per attempt and every retry inflates the bill. So the meter is per successful job, fired once — which is exactly what the outbox and the idempotent sink already guarantee. It is not extra work; it falls out of the same design.

It all reduces to one sentence: the billable event is one successfully-completed unit, counted once.


The shape

In synchronous billing the meter is a property of a request arriving. In asynchronous billing it is a property of work finishing — and the discipline is firing it exactly once per successful unit.

It is worth separating what is hard from what is free. The completion wiring — the outbox, the retries — is yours to build. The at-most-once half is the sink's job, if you chose a sink that does it. Get both, and a client polling ten times, a worker retrying five, and a job that half-failed all resolve to the right number of credits.

That is the whole thing. It isn't much once it's drawn — but every line of it is a place I have watched a bill come out wrong.


Built with Claude (Opus).