2 13.5. Serialization Failure Handling #
4 Both Repeatable Read and Serializable isolation levels can produce
5 errors that are designed to prevent serialization anomalies. As
6 previously stated, applications using these levels must be prepared to
7 retry transactions that fail due to serialization errors. Such an
8 error's message text will vary according to the precise circumstances,
9 but it will always have the SQLSTATE code 40001
10 (serialization_failure).
12 It may also be advisable to retry deadlock failures. These have the
13 SQLSTATE code 40P01 (deadlock_detected).
15 In some cases it is also appropriate to retry unique-key failures,
16 which have SQLSTATE code 23505 (unique_violation), and exclusion
17 constraint failures, which have SQLSTATE code 23P01
18 (exclusion_violation). For example, if the application selects a new
19 value for a primary key column after inspecting the currently stored
20 keys, it could get a unique-key failure because another application
21 instance selected the same new key concurrently. This is effectively a
22 serialization failure, but the server will not detect it as such
23 because it cannot “see” the connection between the inserted value and
24 the previous reads. There are also some corner cases in which the
25 server will issue a unique-key or exclusion constraint error even
26 though in principle it has enough information to determine that a
27 serialization problem is the underlying cause. While it's recommendable
28 to just retry serialization_failure errors unconditionally, more care
29 is needed when retrying these other error codes, since they might
30 represent persistent error conditions rather than transient failures.
32 It is important to retry the complete transaction, including all logic
33 that decides which SQL to issue and/or which values to use. Therefore,
34 PostgreSQL does not offer an automatic retry facility, since it cannot
35 do so with any guarantee of correctness.
37 Transaction retry does not guarantee that the retried transaction will
38 complete; multiple retries may be needed. In cases with very high
39 contention, it is possible that completion of a transaction may take
40 many attempts. In cases involving a conflicting prepared transaction,
41 it may not be possible to make progress until the prepared transaction
42 commits or rolls back.