← PHP / Laravel · Contents

PHP-043 / Advanced

Check-then-act race condition for inventory or coupons

A04:2021 Insecure Design · CWE-362 Race Condition · CWE-367 TOCTOU

Why is this a problem?

Concurrent requests use the same balance or coupon twice.

How to fix it

php
DB::transaction(function () use ($id) {
    $c = Coupon::lockForUpdate()->findOrFail($id);
    abort_if($c->used_count >= $c->limit, 409);
    $c->increment('used_count');
});

Further reading