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:
- Analyze logs and traces — understand which transactions and queries are involved in the deadlock.
- Determine the order of locks — find out which resources are being locked and in what order.
- Optimize transactions:
- Reduce the duration of lock holding.
- Break large transactions into smaller ones.
- Ensure all transactions acquire resources in the same order.
- Use transaction isolation levels — possibly lower the isolation level if acceptable.
- 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.