smartyfy.mrindigi.com

Databases & SQL Master Course — 138. Deadlocks and Retries

Lesson 138 Deadlocks and Retries

Verification scope and lab safety

PostgreSQL 18 only. These scripts were checked against official documentation but were not executed on that engine in the authoring environment. Every result below is a reasoned expectation, not observed output. Use a dedicated disposable local lab with the required privileges, never an existing application database. No server installation, credential changes, or external database operation is part of this lesson.

Prerequisites and objectives

Complete optimistic concurrency and explicit transaction boundaries. You will build a two-row deadlock timeline, distinguish a cycle from ordinary waiting, and design a bounded whole-transaction retry that does not duplicate external side effects or reuse decisions derived from an aborted attempt.

A wait is not automatically a deadlock

If B waits for a row held by A and A can finish independently, the dependency is one-way. A deadlock requires a cycle: A waits for something B holds while B waits for something A holds. PostgreSQL detects deadlocks and aborts a participant so the other transaction can progress. Which participant is selected is not a correctness guarantee for application code.

Deadlocks can happen even when each statement is valid and every transaction would succeed alone. Common causes include acquiring related rows in inconsistent orders or combining several lock types without one ordering convention. Short transactions reduce exposure, but shortness alone does not make cycles impossible.

Prepare a disposable shared fixture

Use two interactive connections to the same dedicated PostgreSQL 18 lab database. Ensure schema lab138 is unused. Create and commit the fixture before opening the experimental transactions so both sessions can access it. No server was available for execution here; the schedule and outcomes are documentation-reviewed expectations.

BEGIN;
CREATE SCHEMA lab138;
CREATE TABLE lab138.bins(id integer PRIMARY KEY,qty integer NOT NULL CHECK(qty>=0));
INSERT INTO lab138.bins VALUES(1,10),(2,10);
COMMIT;
Reasoned failure classification for retry design
Outcome Meaning Response
Deadlock SQLSTATE 40P01 A lock dependency cycle was broken Rollback and reconsider a bounded whole attempt
Serialization SQLSTATE 40001 Attempt could not satisfy isolation guarantees Retry the complete transaction when appropriate
Constraint violation Data or business precondition failed Correct or reject; do not blindly repeat unchanged input

Worked practice

Exercise 1

Create the two opposing lock dependencies without changing inventory.

Worked solution
-- Connection A
BEGIN;
SELECT id FROM lab138.bins WHERE id=1 FOR UPDATE;
-- Connection B
BEGIN;
SELECT id FROM lab138.bins WHERE id=2 FOR UPDATE;
-- Connection A: submit; this statement should wait.
SELECT id FROM lab138.bins WHERE id=2 FOR UPDATE;
-- Switch to B while A is waiting. Do not wait for A first.
SELECT id FROM lab138.bins WHERE id=1 FOR UPDATE;
-- After the deadlock error, run ROLLBACK in both sessions. Reading each client outcome comes first.

The pending statement in A is essential. If you wait for it to finish before switching to B, you never submit the request that closes the cycle. Use separate clients and inspect both outcomes. Execute ROLLBACK in each connection after resolution, including the survivor, so no lab reservation remains open.

Exercise 2

Replace opposing order with a shared ascending identity order.

Worked solution
-- Connection A
BEGIN;
SELECT id FROM lab138.bins WHERE id=1 FOR UPDATE;
SELECT id FROM lab138.bins WHERE id=2 FOR UPDATE;
-- Connection B
BEGIN;
SELECT id FROM lab138.bins WHERE id=1 FOR UPDATE;
-- B waits here. Switch to A.
ROLLBACK;
-- Return to B after its pending SELECT completes.
SELECT id FROM lab138.bins WHERE id=2 FOR UPDATE;
ROLLBACK;

Both transactions now acquire row one before row two. Waiting remains possible, but the specific opposite-order cycle is removed. A real application must apply a consistent convention across every path that takes these resources; fixing one endpoint while another retains reverse order leaves the underlying risk.

Exercise 3

Write one complete transfer attempt that can be retried as a unit.

Worked solution
BEGIN;
SELECT id,qty FROM lab138.bins WHERE id=1 FOR UPDATE;
SELECT id,qty FROM lab138.bins WHERE id=2 FOR UPDATE;
UPDATE lab138.bins SET qty=qty-2 WHERE id=1 AND qty>=2;
-- Continue only if the debit affected exactly one row.
UPDATE lab138.bins SET qty=qty+2 WHERE id=2;
-- Continue only if the credit affected exactly one row.
COMMIT;

The affected-row branches are application control flow, not executable SQL comments. Never paste this success path into an unattended client that ignores those conditions. A retry starts again at BEGIN, reacquires rows, rereads quantities, and reevaluates the debit. Retrying only the failed credit can preserve an obsolete assumption or omit earlier work that was rolled back.

Exercise 4

Specify a bounded retry and inspect the resulting inventory invariant.

Worked solution
SELECT id,qty FROM lab138.bins ORDER BY id;
SELECT SUM(qty) AS total_units FROM lab138.bins;

For this teaching policy, allow at most three complete attempts within a request deadline. On 40P01 or a retryable 40001, roll back, release the connection appropriately, wait using bounded jitter, and start a fresh attempt. On a failed quantity precondition, return a business rejection. If the deadline or attempt budget expires, return a retriable service outcome without claiming the transfer succeeded.

Retries include decisions, not just SQL text

A transaction may read several rows, choose an identifier, calculate a quantity, and then write. All logic whose result depends on those reads belongs to the retryable unit. Reusing a cached calculation after the database aborted its transaction can reproduce the same unsafe choice with newer locks.

Do not send an email, charge a payment, or invoke another irreversible service on every attempt. Those effects are not undone by SQL ROLLBACK. Keep external effects outside the retried body, or use a separately designed transactional outbox and an idempotent delivery process. Even an effect after COMMIT needs handling for a lost commit acknowledgement.

Retry classification should use structured SQLSTATE values supplied by the driver, not a fragile substring search of localized messages. Log an operation identifier, attempt count, state code, and duration without logging secrets or full sensitive parameters. A growing deadlock rate is evidence to investigate access order, indexes, and transaction length, rather than simply increasing the retry limit.

Pitfalls, cleanup, and summary

Never assume the same connection is always the deadlock victim. Do not label every lock wait a deadlock, and do not treat every constraint error as transient. After both sessions have ended, remove only the fixture created for this lab.

DROP TABLE lab138.bins;
DROP SCHEMA lab138;

The strongest design combines a consistent acquisition order, short coherent transactions, explicit error classification, and a bounded whole-operation retry. A retry is recovery from an aborted attempt, not permission to repeat unrelated external actions.

Knowledge check

Question 1

Which dependency pattern is a deadlock?

  1. B waits for A while A can finish without B
  2. A waits for B’s resource while B waits for A’s resource
  3. Two transactions read the same committed row
  4. A query takes longer than its previous execution
Answer and explanation

B. A dependency cycle distinguishes deadlock from ordinary contention.

Question 2

What must the client do after submitting A’s waiting request in the first exercise?

  1. Switch to B and submit the request that closes the cycle
  2. Wait for A to finish before issuing any command in B
  3. Commit A from B’s connection
  4. Assume the waiting SELECT already returned its row
Answer and explanation

A. The interactive schedule needs both outstanding dependencies.

Question 3

What is the correct retry unit after a retryable aborted transfer?

  1. Only the statement that reported the error
  2. Only COMMIT on the aborted transaction
  3. The old calculated debit without rereading balances
  4. The complete transaction and its read-dependent decision logic
Answer and explanation

D. An aborted attempt invalidates its transaction state and potentially its decisions.

Question 4

Which failure should not be blindly retried unchanged under this policy?

  1. A debit precondition showing insufficient units
  2. A classified transient deadlock with attempts remaining
  3. A retryable serialization failure within the deadline
  4. A lock cycle resolved by aborting this attempt
Answer and explanation

A. Insufficient units is a business outcome, not evidence that the same input will succeed after waiting.

Question 5

Why keep an external email send out of each retry attempt?

  1. Email delivery automatically inherits database savepoints
  2. A deadlock guarantees the email server rolled back too
  3. SQL rollback cannot undo an email already sent
  4. COMMIT deduplicates every external API call
Answer and explanation

C. Database atomicity does not extend automatically to separate services.

Dialect verification notes

The target is PostgreSQL 18. Engine execution remains pending. SQLite was not used as a substitute for executing these dialect-specific scripts. Record actual server version, session settings, results, and errors when running the local lab. Python is not a learner prerequisite.

Primary references