The Real Fullstack

The Deadlock

Alice pays Bob while Bob pays Alice. Both requests hang until the database kills one. Why?

エンジニア8 分タイムラインシミュレーターコード課題
javasqlpostgresql

この課題はまだ日本語に翻訳されていません。英語版を表示しています。

ミッション:Reproduce the deadlock by choosing how lock acquisitions interleave, then choose a locking strategy that can never deadlock without serialising unrelated transfers.背景 · 学習目標 ▾

Pocketly's transfer service locks the source account, then the destination account. Monitoring shows rare bursts of “deadlock detected” errors in PostgreSQL and hung worker threads in the Java service — always when two users pay each other at the same moment.

ミッション: Reproduce the deadlock by choosing how lock acquisitions interleave, then choose a locking strategy that can never deadlock without serialising unrelated transfers.

学習目標

  • Recognise the circular-wait condition behind deadlocks.
  • Prevent deadlocks with a global lock ordering.
  • Compare ordering, timeouts with back-off and coarse locks.
シミュレーションシミュレーション値

シミュレーションを実行すると出力が表示されます。

シミュレーションを実行
void transfer(Account from, Account to, long amount) {  synchronized (from) {          // T1 locks A, T2 locks B …    synchronized (to) {          // … then each waits for the other forever      from.withdraw(amount);      to.deposit(amount);    }  }}

簡略化

Each transfer takes exactly two locks. Real databases detect deadlocks and abort one transaction after a timeout; the Java synchronized version would hang forever. 教育用モデルです。数値は挙動を示すためのもので、ベンチマークではありません。

コンセプト

先に取り組むと役立つ課題

関連する課題

参考資料