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

더 읽기