주문 처리 워커를 4개 띄워서 돌리는데 하루에 몇번씩 deadlock detected 가 납니다. 트래픽 몰리는 저녁 시간대에만 그래요..
postgres 15 이고 node 에서 pg 라이브러리 씁니다. 서버 로그는 이렇게 찍혀요
2026-10-11 21:37:12.481 KST [48213] ERROR: deadlock detected
2026-10-11 21:37:12.481 KST [48213] DETAIL: Process 48213 waits for ShareLock on transaction 9182741; blocked by process 48199.
Process 48199 waits for ShareLock on transaction 9182736; blocked by process 48213.
Process 48213: UPDATE inventory SET stock = stock - $1 WHERE product_id = $2
Process 48199: UPDATE inventory SET stock = stock - $1 WHERE product_id = $2
2026-10-11 21:37:12.481 KST [48213] HINT: See server log for query details.
2026-10-11 21:37:12.481 KST [48213] CONTEXT: while updating tuple (1532,17) in relation "inventory"
2026-10-11 21:37:12.481 KST [48213] STATEMENT: UPDATE inventory SET stock = stock - $1 WHERE product_id = $2코드는 대충 이렇습니다
await client.query('BEGIN')
for (const item of order.items) {
await client.query(
'UPDATE inventory SET stock = stock - $1 WHERE product_id = $2',
[item.qty, item.productId]
)
}
await client.query('INSERT INTO order_events (order_id, type) VALUES ($1, $2)', [order.id, 'stock_reserved'])
await client.query('COMMIT')같은 행을 동시에 업데이트하면 뒤에 온게 그냥 기다렸다가 하는거 아닌가요? 쿼리도 UPDATE 하나뿐인데 왜 데드락이 나는지 이해가 안됩니다. 격리수준을 바꿔야 되는건지 몇일째 보고 있는데 모르겠네요
댓글 0