I have a Python Webapp with Flask and SQLAlchemy, and there's a system update process that occurs in multiple threads. When I run it, I'm getting a DeadlocK from Postgres.
The queries that appear in the logs are the following.
ERROR: deadlock detected
DETAIL: Process 2269053 waits for ShareLock on transaction 42979254; blocked by process 2269014.
Process 2269014 waits for ShareLock on transaction 42979253; blocked by process 2269053.
Process 2269053: UPDATE sequence SET item_list='{"item_list": [162, 164]}' WHERE sequence.id = 1978
Process 2269014: UPDATE sequence SET item_list='{"item_list": [162, 165]}' WHERE sequence.id = 1977
HINT: See server log for query details.
while updating tuple (102,44) in relation "sequence"
STATEMENT: UPDATE sequence SET item_list='{"item_list": [162, 164]}' WHERE sequence.id = 1978
I see that they are 2 different PK's, from my understanding when an update is performed only the row is locked and the statements are from 2 different rows. There's clearly something I'm misunderstanding so I wanted to ask if someone could help me clarify why this deadlocks happens and how can I solve it?
Thank you