When you commence a transaction that you know will write to the database use BEGIN IMMEDIATE rather than BEGIN DEFERRED. This is preschool-level deadlock avoidance procedures. Always obtain all your required locks all at once and always in the same order, and release them all on failure to acquire a necessary lock.