Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BIDatabase conceptSeniorCommonTroubleshooting

How would you test and diagnose database locks, blocking and deadlocks?

Answer

Create controlled concurrent transactions that acquire the same resources in known orders, then measure waiting, timeout, cancellation and rollback behaviour. A deadlock forms a cycle of sessions waiting on one another, so the database normally aborts one participant and the application must handle that failure safely. Inspect active sessions, lock views and query logs; verify consistent lock ordering, short transaction scope, bounded waits, safe retries and no duplicated business effect.

Strong answer includes

  • distinguishes ordinary blocking from a deadlock cycle
  • uses controlled concurrent sessions and lock diagnostics
  • verifies rollback, timeout and idempotent retry behaviour

Practical example

Create a deterministic deadlock in two sessions
Dialect · DBMS-dependentRuntime · static example

A deadlock experiment must coordinate at least two real concurrent sessions.

-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- then wait and update id = 2
UPDATE accounts SET balance = balance + 10 WHERE id = 2;

-- Session B
BEGIN;
UPDATE accounts SET balance = balance - 20 WHERE id = 2;
-- then wait and update id = 1
UPDATE accounts SET balance = balance + 20 WHERE id = 1;

Each session holds one row lock and then requests the row held by the other session, creating a wait cycle. The database should abort one participant; the application test then verifies rollback, bounded retry and no duplicated business effect.

Expected result: One transaction is chosen as the deadlock victim and rolled back rather than both waiting forever.

#database#locking#deadlocks#concurrency

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery