Sobes.tech
Senior

You were given an application, and you encountered a deadlock in the database. How will you act?

sobes.tech AI

Answer from AI

When encountering a deadlock in a database, I would act as follows:

  1. Analyze logs and traces — understand which transactions and queries are involved in the deadlock.
  2. Determine the order of locks — find out which resources are being locked and in what order.
  3. Optimize transactions:
    • Reduce the duration of lock holding.
    • Break large transactions into smaller ones.
    • Ensure all transactions acquire resources in the same order.
  4. Use transaction isolation levels — possibly lower the isolation level if acceptable.
  5. Implement retries — add logic to retry transactions in case of deadlock.

In C#, you can handle the SqlException with the error code corresponding to deadlock and retry the transaction:

try
{
    // transaction code
}
catch (SqlException ex) when (ex.Number == 1205) // deadlock
{
    // retry the transaction
}

The main goal is to understand the causes of deadlock and eliminate them at the application and database level.

You were given an application, and you encountered a… - sobes.tech