Video in progress

Senior 🧪 Testing

Two parallel requests could redeem the same coupon twice. How do you reproduce such a database race in an integration test?

@Transactional
public void redeem(String code, long userId) {
    Coupon c = couponRepo.findByCode(code).orElseThrow();
    if (c.getUsed() >= c.getLimit()) throw new CouponExhaustedException();
    c.setUsed(c.getUsed() + 1);
    redemptionRepo.save(new Redemption(c, userId));
}

I line several threads up at a "start" with a CountDownLatch, call the same operation in parallel against a real database, and check the invariant: the coupon must have been used once. I run the test with many iterations, because the race doesn't show up every time.

📖 Answer

This code has a classic "read-modify-write" race: two transactions read used = 0 at the same time, both pass the check, both write used = 1, and a coupon with a limit of 1 was redeemed twice.

The test:

@Test
void couponCannotBeRedeemedTwiceConcurrently() throws Exception {
    String code = saveCoupon(limit(1)).getCode();
    int threads = 8;
    var start = new CountDownLatch(1);
    var pool = Executors.newFixedThreadPool(threads);
    List<Future<Boolean>> results = new ArrayList<>();

    for (int i = 0; i < threads; i++) {
        long userId = i;
        results.add(pool.submit(() -> {
            start.await();
            try { couponService.redeem(code, userId); return true; }
            catch (CouponExhaustedException | ObjectOptimisticLockingFailureException e) { return false; }
        }));
    }
    start.countDown();
    long ok = 0;
    for (Future<Boolean> f : results) if (f.get(5, SECONDS)) ok++;   // f.get() throws checked exceptions; the test method declares throws Exception

    assertThat(ok).isEqualTo(1);
    assertThat(redemptionRepo.countByCouponCode(code)).isEqualTo(1);
}

Important conditions: the test itself must not be @Transactional (otherwise the threads don't see the data in other transactions), the database must be real (H2's locking behavior is different), and run the test with @RepeatedTest(20).

Options for the fix: an optimistic lock with @Version, SELECT ... FOR UPDATE, or a single atomic UPDATE coupon SET used = used + 1 WHERE code = ? AND used < limit_count and checking the number of rows changed. The last is the simplest and fastest.

For lower-level lock-free code (your own ConcurrentHashMap wrapper, AtomicLong logic) there's a dedicated tool like jcstress: it finds problems at the memory model level, which an ordinary JUnit test can't see.