Race conditions in production depend on real concurrency and timing, so investigation relies on evidence first. 1. Collect evidence - Logs and traces for affected orders: order ID, trace ID, thread name and instance or pod name, with precise timestamps. Look for overlapping processing of the same order, duplicate events, retries after timeouts and rebalances. - Database history: status transitions, version columns, audit records — what sequence of updates produced the bad state? - Thread dumps (jstack, or jcmd <pid> Thread.print) and JFR (Java Flight Recorder) recordings if the issue includes hangs or lock contention; JFR shows lock waits and thread states with low overhead in production. 2. Common causes to suspect - Read-modify-write without locking: two threads load the same order, both change it, and the last write wins (lost update). - Shared mutable state in singleton beans (fields in @Service classes, non-thread-safe objects such as SimpleDateFormat or HashMap accessed by several threads). - Check-then-act sequences ("if not processed, then process") without atomicity. - Duplicate message delivery (Kafka rebalances, retries) without idempotency. - @Async or CompletableFuture code mutating shared collections; ThreadLocal context leaking between pooled threads. - Transactions that are too wide or too narrow, or self-invocation bypassing @Transactional. 3. Reproduce deliberately - Write a stress test: many threads (or virtual threads) hitting the same order concurrently with a CountDownLatch to start them simultaneously, against a real database (Testcontainers). - Add artificial delays at suspicious points to widen the race window. - Use jcstress for low-level concurrency primitives, and run tests repeatedly. 4. Fix the root cause - Optimistic locking (@Version) with retry, or atomic conditional updates (UPDATE ... WHERE status = 'PENDING'). - Pessimistic locks (SELECT FOR UPDATE) for short critical sections that need them. - Idempotency keys for requests and an inbox table for messages; Kafka keys so one order's events go to one partition. - Make beans stateless; use thread-safe structures (ConcurrentHashMap with atomic compute, AtomicReference) or immutable objects. - Distributed locks (database advisory locks, Redis with careful lease handling) only when unavoidable. 5. Prevent recurrence - Keep the concurrency test in the suite, add invariant checks and alerts (orders in impossible states, duplicate payments), and run reconciliation jobs that detect and repair inconsistencies.
Ravindra Wadile · · 0 likes