The Real Fullstack

The Lost Transaction

Each order checked the stock inside a transaction. How did we sell six of five?

工程师8 分钟时间线模拟器代码挑战
sqlpostgresqlspring-data-jpajava

此挑战尚未翻译为简体中文,你正在阅读英文版本。

任务:Make the reservation correct for every interleaving of two concurrent orders.背景 · 学习目标 ▾

Fernway's reservation code loads the product with JPA, checks the stock and saves the new value, all inside @Transactional. During a flash sale, more items were sold than existed. Each transaction committed without error.

任务: Make the reservation correct for every interleaving of two concurrent orders.

学习目标

  • Recognise a lost update hidden behind an ORM entity.
  • Compare pessimistic locking, optimistic versioning and atomic conditional updates.
  • Understand why a transaction alone doesn't serialise read-modify-write.
模拟模拟数据

运行模拟以查看输出。

运行模拟
@Transactionalpublic void reserve(long productId, int qty) {  Product p = products.findById(productId).orElseThrow();   // SELECT stock → 5  if (p.getStock() < qty) throw new OutOfStock();  p.setStock(p.getStock() - qty);                          // UPDATE stock = 2 (blind write)}

简化说明

Two orders, two steps each. Real systems also need to handle the retry or 'out of stock' path in the UI. 教学模型——数字用于说明行为,并非基准测试。

概念

建议先完成

相关挑战

参考资料