Database / Mnesia intermediate to advanced Interview questions
How do you handle a transaction that needs to retry after being aborted due to a deadlock?
When Mnesia detects a deadlock between two transactions, it aborts one of them automatically, but it
doesn't retry it for you — the calling code gets back {aborted, Reason} and is responsible
for deciding whether and how to retry.
retry_transaction(Fun, Retries) when Retries > 0 -> case mnesia:transaction(Fun) of {atomic, Result} -> {ok, Result}; {aborted, {deadlock, _}} -> timer:sleep(rand:uniform(50)), %% small random backoff retry_transaction(Fun, Retries - 1); {aborted, Reason} -> {error, Reason} end; retry_transaction(_Fun, 0) -> {error, max_retries_exceeded}.
A short, randomized backoff before retrying helps avoid two competing transactions immediately re-colliding in the same way; a bounded retry count avoids looping forever if the underlying contention doesn't clear. This retry logic is application-level code you write yourself — Mnesia's job ends at correctly detecting and aborting one side of the deadlock, not resubmitting the work.
More Related questions...