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

延伸阅读