← PHP / Laravel · 目次

PHP-043 / 上級

在庫・クーポンの check-then-act 競合状態

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

なぜ問題になるのか?

同時リクエストにより同じ残高・クーポンが二度使用されます。

修正方法

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

参考資料