What is a hold/charge credit ledger?
A hold/charge credit ledger is a usage based billing mechanism: a balance built from signed ledger rows, where spending happens in two steps: a temporary hold at the start of work and a permanent charge at the end. The hold is not a charge. It is a reservation that reduces the available balance without counting as revenue or usage.
The three-step lifecycle is the whole idea:
- Hold. Before posting work, subtract the expected cost from the available balance and record a
HOLDrow tied to the job id. - Charge. When the result comes back, write a
CHARGErow and void the hold. The charge is the durable spend. - Release. When the job fails, times out or is cancelled, write a
RELEASErow. The reservation disappears and the balance returns to what it was.
A ledger with these rows answers three different questions without recomputing anything: what a customer has been granted, what is currently reserved, and what has actually been spent. A single mutable balance column answers none of them, and it cannot explain a support ticket that says “the number went down twice”.
| Ledger kind | Direction | When it is written |
|---|---|---|
GRANT |
credit | Monthly allowance or signup credits |
TOPUP |
credit | A paid top-up pack |
HOLD |
debit against availability | Before work is posted |
RELEASE |
credit | Work failed, timed out or was cancelled |
CHARGE |
debit | Work succeeded |
REFUND |
credit | A charge is reversed by policy |
EXPIRE |
debit | A bucket reaches its expiry date |
ADJUST |
either | An audited operator correction |
Why not just charge when the job succeeds?
Charging only on success is the obvious design, and it overspends under concurrency. Two runs read the same balance, each decides it can afford its own work, and both post. The database never sees a conflict because neither run wrote anything at the moment it checked.
A balance of 10 credits, two runs that each need 8:
| Time | Run A | Run B | Stored balance |
|---|---|---|---|
| t0 | reads balance = 10, needs 8, proceeds | — | 10 |
| t1 | — | reads balance = 10, needs 8, proceeds | 10 |
| t2 | posts 8 tasks | posts 8 tasks | 10 |
| t3 | charges 8 | charges 8 | −6 |
The negative balance is not a database bug. It is what happens when a check and a write are not in the same transaction.
Holding before work fixes this because the check and the debit become one atomic step. The second run either sees a reduced balance and refuses, or waits for the first transaction to commit and then reads the truth. There is no window in which two runs both believe the same credits are free.
The ledger schema that makes drift visible
The ledger is deliberately small: one row per credit movement, scoped to an account, tagged with a bucket and a job. The account row carries no balance column; the balance is the sum of the ledger’s deltas, grouped by bucket. That choice costs a query and buys an audit trail that cannot disagree with itself.
| Column | Purpose |
|---|---|
accountId |
Tenant scope; every read is filtered by it |
delta |
Signed integer, negative for debits |
kind |
One of the eight kinds above |
bucket |
MONTHLY or TOPUP |
runId |
Ties a hold, charge or release to one job |
stripeEventId |
Unique; makes a payment event apply once |
expiresAt |
Set on top-ups and signup grants |
note, actorUserId, createdAt |
Why, who, when |
Two details carry most of the weight. First, stripeEventId is unique, so a replayed webhook cannot grant credits twice; the second insert fails and the handler treats it as already processed. Second, runId is what makes the job’s own arithmetic checkable: for one run, the holds minus releases minus charges must net to zero once the run is finished.
How do you make hold and charge atomic?
Hold, charge and release each run as one transaction that starts by locking the account row. The lock is the serialisation point: two concurrent holds on the same account cannot both read the pre-hold balance.
The shape is short enough to show. It is simplified to the parts that matter; the real functions also handle the monthly/top-up split and the error types.
export async function hold(accountId: string, n: number, runId: string) {
return db.$transaction(async (tx) => {
// One lock per account: every credit mutation queues behind it.
const rows = await tx.$queryRaw<{ id: string }[]>`
SELECT id FROM "Account" WHERE id = ${accountId} FOR UPDATE`;
if (rows.length === 0) throw new Error("account_not_found");
const { monthly, topup } = await balanceIn(tx, accountId);
if (monthly + topup < n) {
throw new InsufficientCredits({ needed: n, available: monthly + topup });
}
await tx.creditLedger.create({
data: { accountId, delta: -n, kind: "HOLD", bucket: pickBucket(monthly, n), runId },
});
});
}
Five invariants make the ledger testable. They are worth writing as assertions because every one of them has a realistic way to break:
- Availability never goes negative. Sum of all deltas for an account, across both buckets, is at least zero at every commit.
- A charge never exceeds its hold. A job cannot charge more than the reservation that authorised it.
- A release returns exactly its hold. Not the current balance, not a recomputed cost.
- A finished run nets to zero. Holds minus charges minus releases equals zero for that
runId. - A refund never exceeds its charge. Partial refunds are cumulative and capped.
The FOR UPDATE lock is doing real work. PostgreSQL blocks other transactions that try to update, delete or lock the same row until the first commits, and a waiting SELECT … FOR UPDATE then returns the updated row. That is what a shared balance needs. An optimistic retry loop works too, but every contended hold becomes a retry storm on one row.
Bucket priority, expiry and plan changes
Bucket priority is a product rule with an accounting consequence. Monthly credits are spent first because they reset at renewal and do not roll over; top-ups are spent next, oldest first, because they expire after 12 months. Without a fixed order, a customer could burn paid top-ups while a monthly allowance expired unused.
Expiry is a scheduled job, not a lazy read. expireTopups() writes EXPIRE rows for top-up buckets past their date, so the ledger stays true even for accounts that never log in.
Plan changes add three more cases:
- Upgrade. Stripe prorates the charge, and the account immediately receives the difference between the new and old monthly allowances, adjusted for the time left in the period.
- Downgrade. The new allowance starts at the period end. Changing it immediately would take back credits the customer already paid for.
- Annual plans. Credits are still granted monthly. A daily worker job does it, and it is idempotent through a synthetic event id of
annual:<subscriptionId>:<YYYY-MM>, so a retry on the 1st cannot double-grant.
Cancellation is the fourth case. The account stays active until the period end, then unused monthly credits are expired, paid top-ups stay usable, and reports stay readable for 90 days. The important part is that cancellation is expressed as ledger rows and a status field, not as a deletion. Nothing about a customer’s history disappears because a subscription ended.
Idempotency: the same event twice
Every distributed system delivers the same message twice, and a credit ledger is where that becomes expensive. Four separate mechanisms cover the cases the system actually sees.
Payment events. The StripeEvent table stores each processed event id as a primary key. A replayed invoice.paid hits the duplicate key and stops. The handler also wraps its own work in a try/catch: if the handler fails, the dedupe row is deleted and a 500 is returned, so the retry can run instead of being suppressed as a duplicate forever.
Top-up grants. A top-up only grants when session.payment_status is paid. Delayed payment methods land later as checkout.session.async_payment_succeeded; a failed async payment logs a warning and changes no balance.
Charges. charge(runId, n) is keyed by the run. A duplicate postback that tries to charge the same run twice finds the charge already recorded and does nothing.
Late arrivals. A charge that arrives after a refund does nothing. A charged lookup is never refunded, even if a failure event or a timeout sweep arrives later. These are not theoretical: both are covered by tests in packages/core/test/credits-lookups.test.ts, because the ordering of a provider callback, a timeout and a user retry is not something the code can assume.
The pattern behind all four is the same: make the operation’s identity part of the data, then let a unique constraint or a lookup enforce it. “Charge this run” is idempotent; “subtract 40” is not.
What the run record has to store
The run record stores three credit totals (creditsHeld, creditsCharged, creditsRefunded) and a status that explains how they got there. The ledger says what happened to credits; the run says why, and the two have to agree. Each run stores creditsHeld, creditsCharged and creditsRefunded alongside its status, and the status list is small enough to reason about: QUEUED, HELD, POSTED, PARTIAL, DONE, FAILED, PAUSED_NO_CREDITS.
Three endings matter. Done means every run item resolved and the hold became a charge. Partial means the run hit its 60-minute limit with items still pending: pending items are refunded, resolved items stay charged, and the run is marked PARTIAL rather than failed. Paused means the hold failed at the start because the balance was short; no work is posted, the project records pausedReason, and one credits.exhausted event fires per period rather than one per scheduled attempt.
Feature jobs use the same pattern with a partial charge. A local grid scan that finishes 7 of 9 tiles charges ceil(credits × completed / total); if every tile fails, the whole hold is released. Daily housekeeping fails and releases any feature job still open after 6 hours, covering the callback that never arrived.
Comparison: four ways to meter credits
| Approach | Overspend risk | Customer-visible accuracy | Failure handling | Audit quality |
|---|---|---|---|---|
| Charge on success only | High under concurrency | Balance lags usage | Failed work is free, so retries are free too | Sparse |
| Mutable balance column | Low if locked | Immediate | Manual correction | None |
| Hold/charge ledger | Low, enforced by the lock | Reserved vs spent are separate | Release is a first-class row | Every movement is a row |
| Postpaid invoice at period end | None from the ledger; collection risk sits with the vendor | Customer sees a bill, not a balance | Disputes replace retries | Invoice-level only |
Which should you choose?
Use a hold/charge ledger when work is expensive, asynchronous, and shared across a team or account: rank checks, image generation, scraping jobs, AI agent runs. Use a mutable balance with a lock when the work is synchronous and cheap, and the ledger’s extra rows buy nothing. Postpaid invoicing fits enterprise contracts with negotiated terms, not self-serve products. The deciding question is not “how do we store a number” but “can two jobs start at the same moment and both be wrong”.
What broke and what we changed
A deadlock between concurrent feature jobs. Two jobs that locked rows in different orders could wait on each other. The fix was to lock the account row first, before any job row, in every path that spends credits. A consistent lock order removes the cycle; retrying a deadlock would have hidden it.
A double charge on a double click. Starting the same keyword-discovery job twice in quick succession held credits twice. The fix was to detect the identical in-progress lookup and return the existing one, so the second click is a no-op rather than a second charge. The general rule: the request that starts expensive work needs its own idempotency key, not just the callback that finishes it.
The low-credit warning moved to the hold. It fires when credits are held, once per period, which is the moment the available balance actually drops. A warning tied to a balance read can land before the spend that matters, and the customer reads it as noise.
The refund order had to be written down, not inferred. The rules now state it explicitly: a charged lookup is never refunded, even if a failure event or a timeout sweep arrives later, and a charge that arrives after a refund does nothing. Both orderings have tests, because the arrival order of a provider callback, a timeout and a retry is not something the code can assume.
Related
Frequently asked questions
What is the difference between a hold and a charge?
A hold reserves credits while work is in flight; a charge records that the work succeeded and the credits are spent. The hold reduces the available balance immediately, so a second job cannot reserve the same credits, but it does not count as usage. When the job finishes, the hold is replaced by the charge. When it fails, the hold is released.
Why not just check the balance before starting a job?
Because the check and the debit are separate statements, and another job can commit between them. Two runs can both read the same balance and both proceed. A hold performs the check and the debit inside one transaction that locks the account row, so the second run sees the reduced balance or waits for the first to commit.
Do cached results still cost a credit?
Yes, by product design. A same-day cache hit costs the vendor nothing, but the customer is buying a check, not a network call, and the pricing is per check. The API tells the caller when a result came from cache, so the behaviour is visible rather than surprising. Fresh checks skip the cache and cost the same one credit.
What happens to credits when a run times out?
Anything still pending is released back to the balance, and anything already resolved stays charged. The run is marked PARTIAL, not FAILED, because some of the work did complete. This avoids both extremes: charging for work that never happened, and giving away work that did.
How do you stop a replayed payment webhook from granting credits twice?
The processed event id is stored as a unique row. A replay hits the duplicate key and stops before any grant is written. The handler deletes that row and returns an error if its own work fails, so a genuine retry is not mistaken for a duplicate. Unique constraints, not in-memory flags, are what survive a restart.
Should the balance be a column or a sum of the ledger?
Use a sum of the ledger when you need an audit trail and the volume is manageable; the balance cannot disagree with the rows because it is the rows. Use a cached column when the account has millions of rows and you can rebuild it from the ledger on demand. Do not maintain a mutable column as the only source of truth: every correction becomes a silent edit.
