Question

I've an issue with deadlock..

I'm trying to provide sql dependency on updates to my database.

I do this by creating a trigger on a series of tables. When tables are modified, I increment a integer in a secondary table eg. [dbo].[counters]. I then place a SQL dependency on this table to know which table is updated from code.

However, the target tables that I'm placing the triggers on could be used in a transaction, in which case, It's very easy to deadlock the transaction.

i.e. tbl1 has trigger on insert/update/delete to update counter table tbl2 has trigger on insert/update/delete to update counter table

transaction A occurs on thread1 tbl1 is modified, which triggers an update on counter table

transaction B occurs on thread2 tbl2 is modified, which triggers an update on counter table, thread 2 is now blocked waiting for thread1

meanwhile on thread1, transaction A continues, and updates another table, (either tbl1 or tbl2)

Now deadlock occurs and one of the thread is choosen as the victim.

My question is, if there is a better way to create the triggers to remove possibility of a deadlock? Anyone know how the default SQLDependency in ASP.NET would work to get around this issue?

Was it helpful?

Solution 2

Ok to summarize,

deadlock was caused by different transaction taking a range lock and row lock at the same time on the incrementing table.

ASP.NET SQLDependency uses ROWLOCK hint for the triggers to remove the deadlock scenario. It however this introduces blocking behavior so that if 2 transactions are modifying the same incrementing table, the transactions are essentially serialized.

A recommendation from MS Support is to change ROWLOCK Hint to READPAST. This reduces the blocking behavior if different rows within the incrementing table are being modified simutaneously.

Since notification does not require absolute ACID properties of the RDBMS, An advanced strategy could be to use a non blocking global variable like context_info as a set of binary flags to store the fact that a row has changed (this would remove the blocking on the same table), however requires logic change on the calling application to handle and reset the variables.

OTHER TIPS

Can you tolerate unused counter values? If so, just drop out of the transaction when updating the counters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top