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.…