How to avoid deadlocks in Postgres?

I run several servers, and each of them runs commands with several updates, such as these

UPDATE user SET ... WHERE user_id = 2;
UPDATE user SET ... WHERE user_id = 1;
UPDATE user SET ... WHERE user_id = 3;

If there is a concurrenct update, for example:

UPDATE user SET ... WHERE user_id = 1;
UPDATE user SET ... WHERE user_id = 2;

Then I will encounter an error deadlock detected

Currently, my fix is ​​to order client-side update instructions and always ensure that the identifiers are in the same order. those. I always sort the client side operatorASC by user_id

This seems to pose the problem so far, but I still have questions:

  • Is this (ordering) a good solution to eliminate deadlock errors?
  • If I start making updates with multiple tables, should I also order instructions through the tables?
+4
1

- , . . , .

: .

Serializable . ; , , . , , , , - . , , " ", , , ( ) .

. , , , .

0

All Articles