Transfers occasionally fail even though the database shows no obvious CPU or memory pressure, and the error reports deadlock detected. More memory will not fix this kind of problem: two transactions each hold a lock the other needs, creating a circular wait. This article reproduces that cycle in an isolated test database, then validates consistent lock ordering and whole-transaction retries. The experiment creates just two rows. It does not modify business tables or change global database settings.
1. Define the test scope and distinguish the errors
IronSSH dedicated servers with AMD EPYC 7543P provide 128GB or 256GB of DDR4-3200 ECC memory, but hardware capacity does not change database locking semantics. After payment, check the address and credentials in the console, connect to Linux over SSH, and establish test connections using your existing database administration method. There is no need to expose a new public database endpoint.
Run the following commands in a separate test database, using an account with permission to create tables. Open two psql sessions connected to the same database as the same user, and label them A and B. Start by running this in both:
\set VERBOSITY verbose
SHOW deadlock_timeout;
SET lock_timeout = '0';
SET statement_timeout = '60s';
Verify that the displayed deadlock detection delay is shorter than the statement timeout used here. Otherwise, have an administrator check the test environment before proceeding. This disables only the current session's lock-wait timeout, preventing it from ending the statement before deadlock detection can run.
Distinguish three outcomes: 40P01 means a deadlock, 55P03 commonly indicates a lock-wait timeout or an inability to acquire a lock, and 57014 means query cancellation. Do not count all three as deadlocks, and never terminate a database process simply because it is waiting.
Run this exercise only in an isolated test database. Do not keep pasting commands into a window that is waiting. Observe the result first, then explicitly commit or roll back so that no transaction is left holding locks.
2. Create a row-lock cycle with two sessions
Create the table and check the starting balances
Run this once in A, before starting a transaction:
CREATE TABLE deadlock_lab (
id integer PRIMARY KEY,
balance integer NOT NULL CHECK (balance >= 0)
);
INSERT INTO deadlock_lab VALUES (1, 100), (2, 100);
SELECT * FROM deadlock_lab ORDER BY id;
This table name is reserved for the exercise. If it already exists, establish who owns it and what it is for before proceeding. Do not work around the conflict by overwriting or dropping it. Both rows start at 100, for a total of 200. These values are the baseline for checking rollback behavior.
First, update the first row in A:
BEGIN;
UPDATE deadlock_lab SET balance = balance - 10 WHERE id = 1;
Then update the second row in B:
BEGIN;
UPDATE deadlock_lab SET balance = balance - 20 WHERE id = 2;
Each session now holds a lock on one row. Return to A and run the next statement. It should wait:
UPDATE deadlock_lab SET balance = balance + 10 WHERE id = 2;
Leave A waiting and run this in B:
UPDATE deadlock_lab SET balance = balance + 20 WHERE id = 1;
The cycle is now complete. Once the deadlock is detected, one session receives 40P01 and the other continues. Do not assume that A or B will always be the one that fails. Run ROLLBACK; in the failed session and COMMIT; in the successful session, then query the balances of both rows.
If A succeeds, the balances should be 90 and 110. If B succeeds, they should be 120 and 80. Either way, the total is 200. If you get another result, first check the execution order and how each transaction was ended. Do not treat one pair of numbers in a screenshot as the only correct outcome.
3. Capture evidence that explains the cycle
Open a separate observer connection with the necessary monitoring permissions. While A is waiting and before B issues its second update, run:
SELECT pid, application_name, state,
wait_event_type, wait_event,
pg_blocking_pids(pid) AS blockers,
xact_start, query
FROM pg_stat_activity
WHERE datname = current_database()
AND pid <> pg_backend_pid()
ORDER BY pid;
At this point, you will usually see only A blocked by B, not a complete deadlock. After B issues its second update, the detector may break the cycle too quickly for the observer query to capture both sessions waiting. The process IDs, transaction wait relationships, and SQLSTATE in the client's error details are therefore often more useful than an activity-view snapshot taken afterward.
Record the connection process IDs for this experiment, the statement order, error code, final balances, and the actions taken to end both the failed and successful transactions. In a business environment, also correlate the evidence with a request identifier, but do not include complete customer parameters, passwords, or connection strings in diagnostic material.
In monitoring output, a row-lock wait may appear as a wait for another transaction to finish rather than an explicit indication that a particular row is locked. Counting entries in pg_locks is not enough to establish the root cause. Do not broaden an ordinary application account's monitoring permissions merely to collect evidence.
4. Use a consistent lock order and interleave the sessions again
First, confirm that A and B have both ended their previous transactions. Then reset the balances in one session:
UPDATE deadlock_lab SET balance = 100;
This time, both sessions acquire the target row locks in ascending primary-key order before making changes. Run this in A:
BEGIN;
SELECT id FROM deadlock_lab
WHERE id IN (1, 2)
ORDER BY id
FOR UPDATE;
UPDATE deadlock_lab SET balance = balance - 10 WHERE id = 1;
UPDATE deadlock_lab SET balance = balance + 10 WHERE id = 2;
Do not commit yet. Run the same locking query in B:
BEGIN;
SELECT id FROM deadlock_lab
WHERE id IN (1, 2)
ORDER BY id
FOR UPDATE;
B should wait. It continues only after A runs COMMIT;. Then complete the transfer in the opposite direction in B:
UPDATE deadlock_lab SET balance = balance - 20 WHERE id = 2;
UPDATE deadlock_lab SET balance = balance + 20 WHERE id = 1;
COMMIT;
SELECT * FROM deadlock_lab ORDER BY id;
The balances should be 110 and 90, still totaling 200. This run demonstrates that the specified code path now produces an ordered wait instead of a circular one. It does not prove that the entire system can never deadlock. Updates across multiple tables, triggers, and foreign-key checks can also introduce lock dependencies and must be included in the same lock-order review.
In this example, the primary keys do not change, and the rows being ordered are clearly defined. Do not infer that arbitrary complex queries or execution plans automatically provide a global lock order.
5. Retry the whole business operation, not a single SQL statement
After receiving 40P01, first roll back the failed transaction. Then start a new transaction, read the current state again, validate the balances, and perform all the changes. Do not reuse a balance read before the failure and resend only the final UPDATE. That separates decisions that belong to a single business operation.
At a minimum, define a maximum number of attempts, an overall time budget, and a delay with random jitter. After each failure, release transaction and connection resources before waiting. Return an explicit failure when the retry budget is exhausted. If a network interruption leaves the commit outcome unknown, do not simply retry it as a deadlock. Look up the operation's result using its business operation identifier.
A database rollback does not retract notifications or external requests that have already been sent. One approach is to write pending events and business changes in the same database transaction, then handle delivery through a separate process. Both delivery and consumption still require deduplication using a stable operation identifier. A successful transaction commit does not mean that an external action ran exactly once.
Finish by checking four acceptance criteria: deliberately acquiring locks in opposite orders produces 40P01; the failed transaction leaves no partial debit behind; both transfers complete with the correct balances after lock ordering is made consistent; and exhausting the retry budget leaves no open transactions or duplicate side effects. When finished, close the test connections and have the table's creator drop the test table. Keep the reproduction steps together with the acceptance results so that deadlock mitigation amounts to more than a one-off parameter change.
Frequently asked questions
Will adding server memory fix PostgreSQL deadlocks?
No. Deadlocks arise from circular waits between transactions. Address lock ordering, shorten transactions, and retry complete transactions after deadlock failures; memory capacity does not remove the dependency cycle.
Can I retry only the failed UPDATE after SQLSTATE 40P01?
No. Roll back the failed transaction and start a new one that repeats the entire business operation, including reads and validation. Bound retry attempts and elapsed time, and protect external side effects with idempotency.
AMD EPYC 7543P Dedicated Server
From $444.5/month