Menu

Metering AI usage in Laravel with a credit ledger - atomic balance updates that survive concurrency
📰

Metering AI usage in Laravel with a credit ledger - atomic balance updates that survive concurrency

DEV Community: laravel·Keel·6 days ago
#gMU6pRc1
#devtolaravel#devto#dev#balance#reservation
Long article (1523 words) — no AI summary yet.
Reading 0:00
15s threshold

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 ) ; }

Enter fullscreen mode

Exit fullscreen mode

Two concurrent requests both read balance = 10 , both pass the >= 8 check, both call the provider, and the balance lands at -6.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.