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

推荐订阅源

Google DeepMind News
Google DeepMind News
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Security Latest
Security Latest
P
Palo Alto Networks Blog
AWS News Blog
AWS News Blog
NISL@THU
NISL@THU
T
Threatpost
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Latest news
Latest news
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
J
Java Code Geeks
P
Privacy International News Feed
阮一峰的网络日志
阮一峰的网络日志
S
Schneier on Security
博客园 - 聂微东
Project Zero
Project Zero
美团技术团队
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Scott Helme
Scott Helme
I
Intezer
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Hacker News: Front Page
S
Security @ Cisco Blogs
博客园 - 司徒正美
O
OpenAI News
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
酷 壳 – CoolShell
酷 壳 – CoolShell
SecWiki News
SecWiki News
月光博客
月光博客
S
Security Affairs
The GitHub Blog
The GitHub Blog
P
Privacy & Cybersecurity Law Blog
S
Secure Thoughts
V
V2EX
S
Securelist
F
Fortinet All Blogs
W
WeLiveSecurity
D
Docker
博客园 - 三生石上(FineUI控件)
Simon Willison's Weblog
Simon Willison's Weblog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Webroot Blog
Webroot Blog
Engineering at Meta
Engineering at Meta

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
I stored AI SaaS credits as a single integer. Then the refunds started.
Velobase · 2026-06-25 · via DEV Community

Once in a while someone on the team writes up a mistake worth keeping. This one is about billing, from the engineer who lived it.

The scary part of launching an AI SaaS is not the empty launch day. It's the first week when real people start paying, burning credits, retrying requests, asking for refunds, running cron jobs, and finding every shortcut you left in the billing code.

Usage-based billing sounds simple when it's a pricing page. It gets messy when every AI action costs money, every retry can double-charge someone, and every support ticket starts with a number your database cannot explain.

My first credit system was one column on the users table: credits. Buy a pack, it goes up. Run a generation, it goes down. I built it in an afternoon and felt clever about how little code it took.

It held up right until real money showed up. One Tuesday I opened the billing dashboard to a refund, a chargeback from a name I didn't recognize, and a buyer who'd been charged twice because his request timed out and retried. Then an email landed that I still remember word for word:

"Why do I have 37 credits? I bought 500 and I've barely touched this."

I opened a psql shell and ran the only query I had:

select credits from users where id = '...'; -- 37

Thirty-seven. That was the whole story my database could tell me.

Not where the other 463 went. Not when. Not why. Every credits = credits - 1 had overwritten the last number and dropped the reason on the floor. I started a reply with "let me look into this" and realized there was nothing to look into.

That email is why I tore the whole thing out and rebuilt it as a ledger. Here's the model, and the exact moment that taught me each part of it.

A counter only remembers the last thing that happened

With a counter, a customer's entire financial history with your product is one mutable integer that any code path can stomp on. The grant, the spend, the refund, the bug, the fix for the bug. They all collapse into a single number, and the moment they do, you've thrown away every question worth asking:

  • "Why is this balance what it is?" You'd need every change that produced it.
  • "Refund this purchase." You'd need to know what that purchase actually granted.
  • "Did a retry double-credit this user?" You'd need to spot the duplicate write.
  • "Do our credits reconcile with Stripe?" You'd need a paper trail on both sides.

A single number answers none of them. Once refunds exist, you don't want the balance. You want the list of things that produced it.

Stop updating the balance. Start appending rows.

The fix is boring, which turns out to be the point. You never update a balance again. You write one signed row per change, and you add them up when you need the number.

create table credit_entries (
  id              bigint generated always as identity primary key,
  user_id         uuid not null references users(id),
  amount          integer not null, -- +grant, -spend, never zero
  reason          text not null,    -- 'purchase' | 'generation' | 'refund' | 'signup_bonus' | 'clawback'
  ref_type        text,             -- 'stripe_payment' | 'job' | 'credit_entry'
  ref_id          text,             -- the thing that caused this row
  idempotency_key text,             -- dedupe retries
  created_at      timestamptz not null default now()
);

create unique index on credit_entries (idempotency_key)
  where idempotency_key is not null;

No updated_at. Rows are written once and never touched again. The balance is a sum:

select coalesce(sum(amount), 0) as balance
from credit_entries
where user_id = $1;

Remember the 37-credit guy? On the ledger, his mystery is just his history, in order:

+500   purchase                    2026-05-02 09:14
 -463  generation (x463 entries)   2026-05-02 -> 05-09
-----
   37  balance

Four hundred and sixty-three generations in a week from someone who'd "barely touched it." I pasted the history into my reply. He wrote back: "oh no. that's my cron job."

Closed in one message, because the data could finally speak for itself.

The retry that gives away free credits

This is the one that actually cost me money. Stripe's webhook delivery is at-least-once, not exactly-once. Duplicate deliveries are the contract, not a bug.

One afternoon Stripe fired checkout.session.completed, my handler granted 500 credits, my server was slow to send back its 200, so Stripe assumed the delivery failed and fired the same evt_ id again. Then a third time.

The buyer pinged me an hour later:

"lol why do I suddenly have 1,500 credits"

Same event, same signature, processed three times, and I had paid for it.

The tempting fix is to check before you write. Don't. That's a race, and two deliveries can both pass the check:

// DON'T: two concurrent deliveries both read "not seen" and both grant
const seen = await db.query.creditEntries.findFirst({
  where: eq(idempotencyKey, eventId),
});

if (!seen) await grant(userId, 500);

Let the database be the referee. Derive a key from the source event and let a unique index throw the duplicate away:

await db.insert(creditEntries)
  .values({
    userId,
    amount: 500,
    reason: "purchase",
    refType: "stripe_payment",
    refId: paymentId,
    idempotencyKey: stripeEventId,
  })
  .onConflictDoNothing({
    target: creditEntries.idempotencyKey,
  });

The second and third deliveries hit the index and do nothing. The grant happens once. You didn't have to make your webhook perfectly exactly-once. The data model swallowed the retry for you.

The double-spend that takes ten milliseconds

Picture a user on hotel wifi mashing "Generate" twice, or someone with two tabs open. They have one credit left.

Request A reads the balance: 1. Ten milliseconds later, before A has written anything, Request B reads the balance: 1. Both decide they're fine. Both generate. The balance lands at -1, and they got two images for the price of less than one.

The bug is reading the balance in app code and then writing based on a number that's already stale. Do the check and the write in one transaction, so the read only sees committed rows:

await db.transaction(async (tx) => {
  const { balance } = await tx
    .select({ balance: sql`coalesce(sum(amount), 0)` })
    .from(creditEntries)
    .where(eq(creditEntries.userId, userId));

  if (balance < cost) throw new InsufficientCredits();

  await tx.insert(creditEntries).values({
    userId,
    amount: -cost,
    reason: "generation",
    refType: "job",
    refId: jobId,
    idempotencyKey: jobId,
  });
});

Run it at serializable, or take a per-user advisory lock, so two transactions can't both clear the check against the same starting balance. Using jobId as the key also means a retried job won't get billed twice.

A refund is just one more row

Forty days after a sale, a chargeback rolls in. The credits it paid for were spent two weeks ago. With a counter you're stuck choosing between editing a history you no longer have and pretending it didn't happen.

On a ledger you append:

insert into credit_entries (user_id, amount, reason, ref_type, ref_id)
values ($user, -500, 'refund', 'credit_entry', $original_entry_id);

The balance drops honestly, goes negative if it has to, and the new row points straight at the purchase it cancels.

Same move when you catch a farmed signup: append a negative clawback instead of reaching into a column and hoping you did the arithmetic right. Refund, chargeback, fraud, a manual fix from support. All the same operation. Write one more row.

Boring on purpose, and boring is exactly what you want anywhere near money.

"Won't the SUM get slow?"

At launch, that balance query was 2ms and I never thought about it. Somewhere around four million rows it was 200ms, and the p95 on every endpoint that checked a balance started to crawl.

The fix isn't to abandon the ledger. You periodically write a checkpoint row that snapshots the balance up to a point in time, then sum only what came after it.

The ledger stays the source of truth, and the checkpoint is a cache you can rebuild any time you stop trusting it. Don't build it before a profiler asks you to. An index on (user_id, created_at) carries you further than you'd guess.

One more habit worth starting early: the day you pay affiliates or hand out referral bonuses, make the movement double-entry. Every credit out of one account is a credit into another, so the books always sum to zero. The first time mine didn't, it was off by a single cent, and double-entry meant I caught it that afternoon instead of six weeks later in a reconciliation nobody had scheduled.

What I'd tell past me

  • Store integer units, never a float. Float math is how you wake up to balances ending in 0.000001 that drift over time.
  • Never delete a ledger row. Wrong entry? Append a reversal. A DELETE breaks the audit trail for good.
  • Give every entry a reason and a reference to whatever caused it. That one column is the difference between answering a dispute in ten seconds and guessing.
  • Keep a cached balance if you want the speed, but treat the ledger as the only truth and re-derive the moment the two disagree.

The honest tradeoff: this is more code than credits -= 1. It's also the difference between reading a customer his own history back and typing "let me look into this" with nothing to look into.

We kept rebuilding this same stack for AI products: Stripe checkout, usage-based billing, usage metering, customer credits, refunds, idempotent webhooks, and a ledger that support can actually explain. So we open-sourced it as Harness, MIT-licensed: github.com/velobase/velobase-harness.

If you're building an AI SaaS and don't want your first real users to become your billing test suite, it may save you a few painful weeks.

If you've run this in production: how do you handle the SUM-vs-snapshot tradeoff? Running totals, checkpoint rows, a cached balance you reconcile on a cron? I'd genuinely like to hear what held up.