Refactor SQL transactions to minimise deadlocks