Every AI feature eventually needs an answer to the question "how much has this user spent". The first version everyone writes is a credits integer on the users table, and the first version everyone writes is wrong in the same two ways: two concurrent requests can read the same balance and both spend it, and when the number is wrong you have no idea why, because the number is all you kept.
Here is the version the kit this series is drawn from ships instead: an append-only ledger where the balance is derived, never stored, every change is a row with a reason, and the exactly-once guarantees live in the database schema rather than in hopeful application code. It is under 300 lines across the service, the model, the enum, two migrations and the tests.
The schema is the contract
Schema::create('credit_transactions', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->cascadeOnDelete(); $table->string('type', 20); $table->integer('amount'); $table->integer('balance_after'); $table->string('reason')->nullable(); $table->json('meta')->nullable(); $table->timestamps(); $table->index(['user_id', 'id']); }); Four transaction types, one enum: grant (signup allowance, admin generosity), purchase (money arrived), debit (usage), adjustment (support fixing something by hand). amount is signed - positive for everything that adds, negative for debits - and balance_after is the running balance the moment the row was written. The balance of an account is the balance_after of its newest row. Nothing is ever updated or deleted, so "how did this account get here" is a SELECT, not an archaeology project.
A second migration adds the column that makes webhook deliveries safe:
Schema::table('credit_transactions', function (Blueprint $table) { $table->string('billing_reference')->nullable()->after('reason'); }); // Backfill from JSON meta (driver-portable). if (DB::getDriverName() === 'sqlite') { DB::table('credit_transactions') ->whereNotNull('meta') ->update(['billing_reference' => DB::raw("json_extract(meta, '$.billing_reference')")]); } else { DB::table('credit_transactions') ->whereNotNull('meta') ->update(['billing_reference' => DB::raw("json_unquote(json_extract(meta, '$.billing_reference'))")]); } Schema::table('credit_transactions', function (Blueprint $table) { $table->unique('billing_reference'); // nullable; multiple NULLs allowed }); The unique index is nullable because most rows have no billing reference at all, and Postgres, MySQL and SQLite all allow any number of NULLs in a unique column. The backfill matters if you already shipped the reference inside the JSON meta column: promote it to a real column before you put an index on it, and do the extraction in SQL so the migration works on a production table. Note the driver branch - SQLite and MySQL disagree on whether json_extract quotes strings, and a migration that ignores that backfills quoted garbage into the column you are about to index.
Every write goes through one method
private function apply(User $user, CreditTransactionType $type, int $amount, ?string $reason, array $meta, ?string $idempotencyKey = null): ?CreditTransaction { return DB::transaction(function () use ($user, $type, $amount, $reason, $meta, $idempotencyKey) { // Lock the user row to serialize concurrent credit writes. User::whereKey($user->id)->lockForUpdate()->firstOrFail(); if ($idempotencyKey !== null && $user->creditTransactions()->where('meta->billing_reference', $idempotencyKey)->exists()) { return null; // already granted by an earlier or concurrent delivery } $balance = $this->balance($user) + $amount; if ($balance < 0) { throw InsufficientCreditsException::forUser(max(0, $balance - $amount)); } try { return $user->creditTransactions()->create([ 'type' => $type, 'amount' => $amount, 'balance_after' => $balance, 'reason' => $reason, 'billing_reference' => $idempotencyKey, 'meta' => $meta ?: null, ]); } catch (UniqueConstraintViolationException $e) { // The unique index on billing_reference is the final gate: // a concurrent delivery that passed the in-lock check loses // here instead of double-granting (matters where row locks // are weak, e.g. SQLite). if ($idempotencyKey !== null) { return null; } throw $e; } }); } Three decisions in here are worth stealing.
The lock is on a row that exists. Pessimistic locking only serializes anything if every contender locks the same existing row. The user row is the natural choice: every credit write belongs to exactly one user, the row definitely exists, and any database with real row locks (Postgres, MySQL) will now run one writer's balance-read and insert at a time. Locking something that might not exist yet - the transaction row you are about to insert - is the classic version of this mistake: in Postgres there is nothing to lock, and in MySQL two transactions take gap locks and deadlock on the insert.
The idempotency check happens inside the lock. A webhook that arrives twice - and it will - finds its billing_reference already recorded and returns null, a no-op, instead of granting twice. Checking before the lock is the race: two concurrent deliveries both see "not granted yet" and both grant. This is not hypothetical; reproducing it takes two threads and a barrier at the SQL level, and the kit carries exactly that scar - the first version of this code checked before locking, and a simulated concurrent redelivery of the same first payment produced two grant rows and a doubled balance.
The unique index is the final gate, not the lock. The in-lock check handles databases with honest row locks. Where row locks are weak or absent between connections - SQLite being the everyday case in test suites - two writers can still both pass the check, and then the unique index on billing_reference decides: the loser's insert raises UniqueConstraintViolationException, which the code converts to the same null no-op. Exactly-once is enforced by the schema, which cannot be talked out of it by a scheduler retry, a double click, or a provider redelivering an event.
A failed charge throws InsufficientCreditsException inside the transaction, so it rolls back and leaves no row at all - a user who tries to spend 50 with 10 keeps exactly 10 and an empty ledger, not a partial record.
Metering AI: charge once, after the stream, from the provider's own numbers
The debit side is where the ledger meets the AI module. The chat component pre-flights the balance so an empty account never starts a stream it cannot pay for:
// Check the balance before persisting anything, so an empty // account never leaves half-finished conversations behind. // AiManager re-checks inside the transaction before charging. if (! $credits->hasCredits($user)) { $this->addError('prompt', InsufficientCreditsException::forUser($credits->balance($user))->getMessage()); return; } The actual charge happens only when the stream completes, computed from the usage figures the provider returns, not from a client-side estimate:
/** @var Completion $completion */ $completion = $stream->getReturn(); $credits = $this->creditsFor($modelConfig, $completion->usage); AiUsage::create([/* provider, model, token counts, credits_charged */]); $this->credits->charge($user, $credits, "ai:{$modelKey}", [ 'conversation_id' => $conversationId, 'prompt_tokens' => $completion->usage->promptTokens, 'completion_tokens' => $completion->usage->completionTokens, ]); Rates live in config, per model, as credits per 1,000 input and output tokens:
private function creditsFor(array $modelConfig, CompletionUsage $usage): int { $credits = ($usage->promptTokens / 1000 * $modelConfig['input_credits_per_1k']) + ($usage->completionTokens / 1000 * $modelConfig['output_credits_per_1k']); return max(1, (int) ceil($credits)); } Rounding up with a floor of one is a deliberate posture: a reply that cost fractions of a credit still costs one, which keeps the free tier honest and the arithmetic explainable to anyone staring at their ledger. Every charge writes an AiUsage row (what the provider said the tokens were) and a ledger row (what that cost) with the same numbers, so support questions compare two rows instead of two systems.
The ordering - stream first, charge after - means a user pays for what they actually received, including the provider's own token count, and a stream that dies halfway charges nothing. The alternative, charging up front and refunding on failure, fills the ledger with pairs of rows that exist only to describe accidents.
The purchase path is the same door
Plan activations and renewals come through webhooks carrying a provider-side id - a transaction id, or a synthesized activation:provider:subscription_id for the first payment of a subscription. That id is the idempotencyKey, and because every credit write funnels through apply(), the purchase path inherits the same three-layer protection: lock, in-lock check, unique index. The contract the tests pin:
$first = $credits->purchase($user, 500, 'plan:personal', ['billing_reference' => $reference], idempotencyKey: $reference); $second = $credits->purchase($user, 500, 'plan:personal', ['billing_reference' => $reference], idempotencyKey: $reference); $this->assertNotNull($first); $this->assertNull($second, 'duplicate billing reference must be a no-op'); $this->assertSame(1, $user->creditTransactions()->count()); $this->assertSame(500, $credits->balance($user)); True parallel HTTP delivery cannot be expressed inside one PHP process, so the concurrency contract is pinned in-process like this and the real race is a manual procedure for a live environment. At the time of writing the unit and feature tests around this service - balance arithmetic, refusal semantics, the no-trace failure, one-grant-per-reference, and the no-key path still granting freely - pass at 11 tests and 33 assertions, with the full kit suite at 60.
What is deliberately not here
No cached balance column on the users table: one derived number, one source of truth, no cache to invalidate. No event sourcing framework: the ledger is just a table you can read with SELECT and reason about without a mental model tax. No Redis: the database that stores the money-adjacent rows also enforces their uniqueness. And no per-request metering during the stream - usage is charged once, when the provider has said its final word on the token count.
If you take one idea: put the exactly-once guarantee in the schema, and treat application-level checks as performance, not correctness. The lock makes the common case fast and clean; the unique index makes the worst case correct.
This article was generated by an AI assistant. The code above comes from a working Laravel 13 codebase and is covered by its tests, but walk the code before you trust it with real money - your concurrency model, database engine and pricing arithmetic are your own.

