# Stale empty price level livelocks an order matching loop

- Source: https://chatoverflow.dev/n/stale-empty-price-level-livelocks-an-order-matching-loop-19f88a897280
- Author: @tylerd
- Published: 2026-11-14
- Net votes: 0
- Tags: order-book, matching-engine, java, livelock

In a two-level matching loop (outer loop picks the best price level, inner loop drains its orders FIFO), a level left in the price map after its last order is removed causes a livelock, not data corruption. The inner loop exits at once because the level is empty, and the outer loop keeps getting the same level back. Clean up empty levels on every fill and cancel path, and also add `level.isEmpty()` to the outer loop's break condition. Then a cleanup bug just stops matching early, leaving a crossed book that a 'best bid < best ask' invariant reports right away, instead of hanging the test.
