AI features have an awkward billing property: every request costs real money, the exact cost is only known after the response finishes, and users will absolutely fire two requests at the same time. If your credit check is read balance, compare, decrement, two concurrent requests can both pass the check and both spend the same credits.
Here is the pattern that closes that hole in plain Laravel: an append-only ledger, a conditional atomic decrement, and a reserve-then-settle flow for streaming responses where the final token count is unknown up front.
The race in the naive version
$wallet = $user->wallet; // balance: 10
if ($wallet->balance >= 8) {
$this->callAi($user); // request A and B both pass here
$wallet->decrement('balance', 8);
}
Two concurrent requests both read balance = 10, both pass the >= 8 check, both call the provider, and the balance lands at -6. You just gave away 14 credits of inference for 10.
Fix 1: make the spend conditional in the database
Never separate the check from the decrement. Push both into one atomic statement and inspect the affected row count:
$affected = DB::update(
'UPDATE wallets SET balance = balance - ? WHERE id = ? AND balance >= ?',
[$cost, $wallet->id, $cost]
);
if ($affected === 0) {
throw new InsufficientCreditsException();
}
The WHERE balance >= ? clause is evaluated by the database engine under its row lock, so the check and the spend are one indivisible operation. The loser of the race gets 0 affected rows and a clean exception, not a negative balance.
Fix 2: the ledger is the source of truth, the balance is a cache
A single mutable balance column tells you where you are but not how you got there. Keep an append-only credit_ledger table and treat the cached balance as a performance shortcut:
Schema::create('credit_ledger', function (Blueprint $table) {
$table->id();
$table->foreignId('wallet_id')->index();
$table->bigInteger('amount'); // signed: negative = spend, positive = grant/refund
$table->string('reason'); // purchase, monthly_grant, ai_request, refund
$table->string('reference')->unique(); // idempotency key, see below
$table->timestamps();
});
The reference column carries a unique constraint. Every mutation - a purchase webhook, a monthly grant, an AI charge, a refund - writes its ledger row with a deterministic reference (for example ai-req-{request_uuid} or the provider's event id). A retried webhook or a double-submitted form hits the unique key and becomes a no-op. That one constraint is what makes the whole meter safe to replay.
Fix 3: reserve, then settle, for streaming
Chat-style AI has unknown cost up front: you only know the token count when the stream ends. Charging a flat estimate overcharges short answers and undercharges long ones. The clean shape is:
- Reserve the maximum plausible cost before the first token, using the conditional update from Fix 1. If the reservation fails, the request never reaches the provider.
- Stream the response to the browser.
-
Settle when usage is known: refund
reserved - actualin one ledger write with the same request's reference key.
$reserved = DB::transaction(function () use ($wallet, $reservation, $requestId) {
// Gate on the ledger insert: exactly one caller wins per request id.
$inserted = DB::table('credit_ledger')->insertOrIgnore([
'wallet_id' => $wallet->id,
'amount' => -$reservation,
'reason' => 'ai_reservation',
'reference' => "ai-req-{$requestId}",
'created_at' => now(),
'updated_at' => now(),
]);
if ($inserted === 0) {
return false; // replay of an already-reserved request id
}
$spent = DB::update(
'UPDATE wallets SET balance = balance - ? WHERE id = ? AND balance >= ?',
[$reservation, $wallet->id, $reservation]
);
// Throws, which rolls the ledger row back too - no charge without funds.
abort_if($spent === 0, 402, 'Insufficient credits');
return true;
});
// The flag leaves the transaction with you: a replay must NOT reach the provider.
if (! $reserved) {
return response()->json(['status' => 'already-processing']);
}
// ... stream the provider response ... $actualUsage known at stream end:
DB::transaction(function () use ($wallet, $actualUsage, $requestId) {
// Settle against the committed reservation, not the caller's word.
$reservation = DB::table('credit_ledger')
->where('reference', "ai-req-{$requestId}")
->lockForUpdate()
->value('amount'); // stored negative
if ($reservation === null) {
return; // no committed reservation: stray callback, reject it
}
$refund = max(abs($reservation) - $actualUsage, 0);
// Terminal row even when the refund is zero, so the FIRST settlement
// outcome wins and a later conflicting callback is a no-op.
$inserted = DB::table('credit_ledger')->insertOrIgnore([
'wallet_id' => $wallet->id,
'amount' => $refund,
'reason' => 'ai_settlement',
'reference' => "ai-settle-{$requestId}",
'created_at' => now(),
'updated_at' => now(),
]);
if ($inserted === 1 && $refund > 0) {
$wallet->increment('balance', $refund);
}
});
Several details work together here, and each is easy to get wrong. Both mutations gate on insertOrIgnore against the unique reference: only the caller that wins the insert performs the balance write, so a settlement that runs twice (queue retry, browser reconnect replaying the completion callback) inserts zero rows on the second pass and skips the increment. An unconditional increment after a deduplicated insert still refunds twice. The reservation returns a flag the caller must check before dispatching provider work: a replayed request id that only skips the database write would still call the provider and stream a free answer. Settlement reads the committed reservation row as the refund basis and rejects callbacks for request ids that never reserved. And the settlement row is terminal even at zero: without it, a first callback that legitimately refunds nothing leaves the door open for a second, conflicting callback to invent a refund later. Finally, each pair of writes runs in one transaction, which closes the crash window: the ledger row and the balance update land together or not at all.
Failure handling
If the provider errors mid-stream, settle with actual = 0: the full reservation returns through the same path. One code path for every outcome - success, partial stream, total failure - is what keeps refunds exactly-once instead of best-effort.
What this buys you - and what it doesn't
Scoped precisely, the pattern gives you:
- No negative balances from spending, under any concurrency (the conditional
UPDATEis arbitrated by the database's row lock). - Exactly-once debit and refund effects per request id: replays of the same reservation or settlement are no-ops.
- An auditable row for every credit movement, with a reason and a unique reference.
Those guarantees rest on prerequisites you must actually keep: the unique index on reference exists; every mutation goes through these gated paths (no back-door decrement elsewhere); the request id is minted once per user action and reused by every retry of that same action; the reservation is sized at or above the maximum possible charge; and wallet and ledger live in the same database so both writes share one transaction. It also does not make the provider call itself idempotent - the reservation flag is what keeps a replayed request from reaching the provider at all, and if your provider has its own idempotency keys, use those too.
The ledger table is a few lines of migration, and the atomic spend is one DB::update. The interesting part is not the code volume but deciding that the database, not your PHP process, arbitrates the race.
Disclosure: this article was generated by an AI assistant. The patterns described are drawn from working Laravel application code.
Correction (Nov 24, 2026): the first version of this article's settlement example deduplicated the ledger row but incremented the balance unconditionally, which would have refunded twice on a retry, and its reservation example could not stop a replay from reaching the provider call. Both snippets now gate on insertOrIgnore inside one transaction, the reservation returns a flag the caller checks before dispatching, and settlement validates against the committed reservation row and records a terminal row even at zero refund. If you copied the earlier example, please update it.
Top comments (0)