<p>We're seeing some pernicious, but rare, deadlock conditions in the Stack Overflow SQL Server 2005 database.</p>

<p>I attached the profiler, set up a trace profile using <a href="http://www.simple-talk.com/sql/learn-sql-server/how-to-track-down-deadlocks-using-sql-server-2005-profiler/" rel="noreferrer">this excellent article on troubleshooting deadlocks</a>, and captured a bunch of examples. The weird thing is that <strong>the deadlocking write is <em>always</em> the same</strong>:</p>

<pre><code>UPDATE [dbo].[Posts]
SET [AnswerCount] = @p1, [LastActivityDate] = @p2, [LastActivityUserId] = @p3
WHERE [Id] = @p0
</code></pre>

<p>The other deadlocking statement varies, but it's usually some kind of trivial, simple <strong>read</strong> of the posts table. This one always gets killed in the deadlock. Here's an example</p>

<pre><code>SELECT
[t0].[Id], [t0].[PostTypeId], [t0].[Score], [t0].[Views], [t0].[AnswerCount], 
[t0].[AcceptedAnswerId], [t0].[IsLocked], [t0].[IsLockedEdit], [t0].[ParentId], 
[t0].[CurrentRevisionId], [t0].[FirstRevisionId], [t0].[LockedReason],
[t0].[LastActivityDate], [t0].[LastActivityUserId]
FROM [dbo].[Posts] AS [t0]
WHERE [t0].[ParentId] = @p0
</code></pre>

<p>To be perfectly clear, we are not seeing write / write deadlocks, but read / write.</p>

<p>We have a mixture of LINQ and parameterized SQL queries at the moment. We have added <code>with (nolock)</code> to all the SQL queries. This may have helped some. We also had a single (very) poorly-written badge query that I fixed yesterday, which was taking upwards of 20 seconds to run every time, and was running every minute on top of that. I was hoping this was the source of some of the locking problems!</p>

<p>Unfortunately, I got another deadlock error about 2 hours ago. Same exact symptoms, same exact culprit write.</p>

<p>The truly strange thing is that the locking write SQL statement you see above is part of a very specific code path. It's <em>only</em> executed when a new answer is added to a question -- it updates the parent question with the new answer count and last date/user. This is, obviously, not that common relative to the massive number of reads we are doing! As far as I can tell, we're not doing huge numbers of writes anywhere in the app.</p>

<p>I realize that NOLOCK is sort of a giant hammer, but most of the queries we run here don't need to be that accurate. Will you care if your user profile is a few seconds out of date?</p>

<p>Using NOLOCK with Linq is a bit more difficult as <a href="http://www.hanselman.com/blog/GettingLINQToSQLAndLINQToEntitiesToUseNOLOCK.aspx" rel="noreferrer">Scott Hanselman discusses here</a>.</p>

<p>We are flirting with the idea of using</p>

<pre><code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
</code></pre>

<p>on the base database context so that all our LINQ queries have this set. Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly.</p>

<p>I guess I'm a little frustrated that trivial reads in SQL 2005 can deadlock on writes. I could see write/write deadlocks being a huge issue, but <em>reads?</em> We're not running a banking site here, we don't need perfect accuracy every time.</p>

<p>Ideas? Thoughts?</p>

<hr>

<blockquote>
  <p>Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls?</p>
</blockquote>

<p>Jeremy, we are sharing one static datacontext in the base Controller for the most part:</p>

<pre><code>private DBContext _db;
/// &lt;summary&gt;
/// Gets the DataContext to be used by a Request's controllers.
/// &lt;/summary&gt;
public DBContext DB
{
    get
    {
        if (_db == null)
        {
            _db = new DBContext() { SessionName = GetType().Name };
            //_db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
        }
        return _db;
    }
}
</code></pre>

<p>Do you recommend we create a new context for every Controller, or per Page, or .. more often?</p>

[{'answer_id': 20056, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 3, 'selected': False, 'text': "<blockquote>\n  <p>Will you care if your user profile is a few seconds out of date?</p>\n</blockquote>\n\n<p>Nope - that's perfectly acceptable.  Setting the base transaction isolation level is probably the best/cleanest way to go.</p>\n"}, {'answer_id': 20094, 'author': 'GateKiller', 'author_id': 383, 'author_profile': 'https://Stackoverflow.com/users/383', 'pm_score': 0, 'selected': False, 'text': "<p>I would have to agree with Greg so long as setting the isolation level to read uncommitted doesn't have any ill effects on other queries.</p>\n\n<p>I'd be interested to know, Jeff, how setting it at the database level would affect a query such as the following:</p>\n\n<pre><code>Begin Tran\nInsert into Table (Columns) Values (Values)\nSelect Max(ID) From Table\nCommit Tran\n</code></pre>\n"}, {'answer_id': 20101, 'author': 'jeremcc', 'author_id': 1436, 'author_profile': 'https://Stackoverflow.com/users/1436', 'pm_score': 4, 'selected': False, 'text': '<p>Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls? I originally tried the latter approach, and from what I remember, it caused unwanted locking in the DB. I now create a new context for every atomic operation.</p>\n'}, {'answer_id': 20105, 'author': 'a_hardin', 'author_id': 1497, 'author_profile': 'https://Stackoverflow.com/users/1497', 'pm_score': 1, 'selected': False, 'text': "<blockquote>\n  <p>Will you care if your user profile is a few seconds out of date?</p>\n</blockquote>\n\n<p>A few seconds would definitely be acceptable.  It doesn't seem like it would be that long, anyways, unless a huge number of people are submitting answers at the same time.</p>\n"}, {'answer_id': 20143, 'author': 'bruceatk', 'author_id': 791, 'author_profile': 'https://Stackoverflow.com/users/791', 'pm_score': 0, 'selected': False, 'text': '<p>It\'s fine with me if my profile is even several minutes out of date.</p>\n\n<p>Are you re-trying the read after it fails?  It\'s certainly possible when firing a ton of random reads that a few will hit when they can\'t read.  Most of the applications that I work with are very few writes compared to the number of reads and I\'m sure the reads are no where near the number you are getting.</p>\n\n<p>If implementing "READ UNCOMMITTED" doesn\'t solve your problem, then it\'s tough to help without knowing a lot more about the processing. There may be some other tuning option that would help this behavior.  Unless some MSSQL guru comes to the rescue, I recommend submitting the problem to the vendor.  </p>\n'}, {'answer_id': 20147, 'author': 'jeremcc', 'author_id': 1436, 'author_profile': 'https://Stackoverflow.com/users/1436', 'pm_score': 2, 'selected': False, 'text': "<p>@Jeff - I am definitely not an expert on this, but I have had good results with instantiating a new context on almost every call. I think it's similar to creating a new Connection object on every call with ADO. The overhead isn't as bad as you would think, since connection pooling will still be used anyway.</p>\n\n<p>I just use a global static helper like this:</p>\n\n<pre><code>public static class AppData\n{\n    /// &lt;summary&gt;\n    /// Gets a new database context\n    /// &lt;/summary&gt;\n    public static CoreDataContext DB\n    {\n        get\n        {\n            var dataContext = new CoreDataContext\n            {\n                DeferredLoadingEnabled = true\n            };\n            return dataContext;\n        }\n    }\n}\n</code></pre>\n\n<p>and then I do something like this:</p>\n\n<pre><code>var db = AppData.DB;\n\nvar results = from p in db.Posts where p.ID = id select p;\n</code></pre>\n\n<p>And I would do the same thing for updates. Anyway, I don't have nearly as much traffic as you, but I was definitely getting some locking when I used a shared DataContext early on with just a handful of users. No guarantees, but it might be worth giving a try.</p>\n\n<p><strong>Update</strong>: Then again, looking at your code, you are only sharing the data context for the lifetime of that particular controller instance, which basically seems fine unless it is somehow getting used concurrently by mutiple calls within the controller. In a thread on the topic, ScottGu said:</p>\n\n<blockquote>\n  <p>Controllers only live for a single request - so at the end of processing a request they are garbage collected (which means the DataContext is collected)...</p>\n</blockquote>\n\n<p>So anyway, that might not be it, but again it's probably worth a try, perhaps in conjunction with some load testing.</p>\n"}, {'answer_id': 20172, 'author': 'RobertTheGrey', 'author_id': 1107, 'author_profile': 'https://Stackoverflow.com/users/1107', 'pm_score': 1, 'selected': False, 'text': "<p>I agree with Jeremy on this one. You ask if you should create a new data context for each controller or per page - I tend to create a new one for every independent query.</p>\n\n<p>I'm building a solution at present which used to implement the static context like you do, and when I threw tons of requests at the beast of a server (million+) during stress tests, I was also getting read/write locks randomly.</p>\n\n<p>As soon as I changed my strategy to use a different data context at LINQ level per query, and trusted that SQL server could work its connection pooling magic, the locks seemed to disappear.</p>\n\n<p>Of course I was under some time pressure, so trying a number of things all around the same time, so I can't be 100% sure that is what fixed it, but I have a high level of confidence - let's put it that way.</p>\n"}, {'answer_id': 20204, 'author': 'Michael Sharek', 'author_id': 1958, 'author_profile': 'https://Stackoverflow.com/users/1958', 'pm_score': 2, 'selected': False, 'text': "<p>One thing that has worked for me in the past is making sure all my queries and updates access resources (tables) in the same order.</p>\n\n<p>That is, if one query updates in order Table1, Table2 and a different query updates it in order of Table2, Table1 then you might see deadlocks.</p>\n\n<p>Not sure if it's possible for you to change the order of updates since you're using LINQ.  But it's something to look at.</p>\n"}, {'answer_id': 20224, 'author': 'JEzell', 'author_id': 2308, 'author_profile': 'https://Stackoverflow.com/users/2308', 'pm_score': 5, 'selected': False, 'text': '<p><strong>NOLOCK</strong> and <strong>READ UNCOMMITTED</strong> are a slippery slope. You should never use them unless you understand why the deadlock is happening first. It would worry me that you say, "We have added with (nolock) to all the SQL queries". Needing to add <strong>WITH NOLOCK</strong> everywhere is a sure sign that you have problems in your data layer. </p>\n\n<p>The update statement itself looks a bit problematic. Do you determine the count earlier in the transaction, or just pull it from an object? <code>AnswerCount = AnswerCount+1</code> when a question is added is probably a better way to handle this. Then you don\'t need a transaction to get the correct count and you don\'t have to worry about the concurrency issue that you are potentially exposing yourself to.</p>\n\n<p>One easy way to get around this type of deadlock issue without a lot of work and without enabling dirty reads is to use <code>"Snapshot Isolation Mode"</code> (new in SQL 2005) which will always give you a clean read of the last unmodified data. You can also catch and retry deadlocked statements fairly easily if you want to handle them gracefully.</p>\n'}, {'answer_id': 20473, 'author': 'Jon Galloway', 'author_id': 5, 'author_profile': 'https://Stackoverflow.com/users/5', 'pm_score': 1, 'selected': False, 'text': '<p>Now that I see Jeremy\'s answer, I think I remember hearing that the best practice is to use a new DataContext for each data operation. Rob Conery\'s written several posts about DataContext, and he always news them up rather than using a singleton.</p>\n\n<ul>\n<li><a href="http://blog.wekeroad.com/2007/08/17/linqtosql-ranch-dressing-for-your-database-pizza/" rel="nofollow noreferrer">http://blog.wekeroad.com/2007/08/17/linqtosql-ranch-dressing-for-your-database-pizza/</a></li>\n<li><a href="http://blog.wekeroad.com/mvc-storefront/mvcstore-part-9/" rel="nofollow noreferrer">http://blog.wekeroad.com/mvc-storefront/mvcstore-part-9/</a> (see comments)</li>\n</ul>\n\n<p>Here\'s the pattern we used for Video.Show (<a href="http://www.codeplex.com/videoshow/SourceControl/FileView.aspx?itemId=25033&amp;changeSetId=10876" rel="nofollow noreferrer">link to source view in CodePlex</a>):</p>\n\n<pre><code>using System.Configuration;\nnamespace VideoShow.Data\n{\n  public class DataContextFactory\n  {\n    public static VideoShowDataContext DataContext()\n    {\n        return new VideoShowDataContext(ConfigurationManager.ConnectionStrings["VideoShowConnectionString"].ConnectionString);\n    }\n    public static VideoShowDataContext DataContext(string connectionString)\n    {\n        return new VideoShowDataContext(connectionString);\n    }\n  }\n}\n</code></pre>\n\n<p>Then at the service level (or even more granular, for updates):</p>\n\n<pre><code>private VideoShowDataContext dataContext = DataContextFactory.DataContext();\n\npublic VideoSearchResult GetVideos(int pageSize, int pageNumber, string sortType)\n{\n  var videos =\n  from video in DataContext.Videos\n  where video.StatusId == (int)VideoServices.VideoStatus.Complete\n  orderby video.DatePublished descending\n  select video;\n  return GetSearchResult(videos, pageSize, pageNumber);\n}\n</code></pre>\n'}, {'answer_id': 20727, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 1, 'selected': False, 'text': '<p>You should implement dirty reads.</p>\n\n<pre><code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED\n</code></pre>\n\n<p>If you don\'t absolutely require perfect transactional integrity with your queries, you should be using dirty reads when accessing tables with high concurrency. I assume your Posts table would be one of those.</p>\n\n<p>This may give you so called "phantom reads", which is when your query acts upon data from a transaction that hasn\'t been committed.</p>\n\n<blockquote>\n  <p>We\'re not running a banking site here, we don\'t need perfect accuracy every time</p>\n</blockquote>\n\n<p>Use dirty reads. You\'re right in that they won\'t give you perfect accuracy, but they should clear up your dead locking issues.</p>\n\n<blockquote>\n  <p>Without that, we\'d have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly</p>\n</blockquote>\n\n<p>If you implement dirty reads on "the base database context", you can always wrap your individual calls using a higher isolation level if you need the transactional integrity.</p>\n'}, {'answer_id': 21158, 'author': 'Geoff Dalgas', 'author_id': 2, 'author_profile': 'https://Stackoverflow.com/users/2', 'pm_score': 6, 'selected': True, 'text': '<p>According to MSDN:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/ms191242.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms191242.aspx</a></p>\n\n<blockquote>\n  <p>When either the\n  READ COMMITTED SNAPSHOT or\n  ALLOW SNAPSHOT ISOLATION database\n  options are ON, logical copies\n  (versions) are maintained for all data\n  modifications performed in the\n  database. Every time a row is modified\n  by a specific transaction, the\n  instance of the Database Engine stores\n  a version of the previously committed\n  image of the row in tempdb. Each\n  version is marked with the transaction\n  sequence number of the transaction\n  that made the change. The versions of\n  modified rows are chained using a link\n  list. The newest row value is always\n  stored in the current database and\n  chained to the versioned rows stored\n  in tempdb.</p>\n  \n  <p>For short-running transactions, a\n  version of a modified row may get\n  cached in the buffer pool without\n  getting written into the disk files of\n  the tempdb database. If the need for\n  the versioned row is short-lived, it\n  will simply get dropped from the\n  buffer pool and may not necessarily\n  incur I/O overhead.</p>\n</blockquote>\n\n<p>There appears to be a slight performance penalty for the extra overhead, but it may be negligible.  We should test to make sure.</p>\n\n<p>Try setting this option and REMOVE all NOLOCKs from code queries unless it’s really necessary.  NOLOCKs or using global methods in the database context handler to combat database transaction isolation levels are Band-Aids  to the problem.  NOLOCKS will mask fundamental issues with our data layer and possibly lead to selecting unreliable data, where automatic select / update row versioning appears to be the solution.</p>\n\n<pre><code>ALTER Database [StackOverflow.Beta] SET READ_COMMITTED_SNAPSHOT ON\n</code></pre>\n'}, {'answer_id': 21438, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 2, 'selected': False, 'text': '<p>Setting your default to read uncommitted is not a good idea.  Your will undoubtedly introduce inconsistencies and end up with a problem that is worse than what you have now.  Snapshot isolation might work well, but it is a drastic change to the way Sql Server works and puts a <em>huge</em> load on tempdb.</p>\n\n<p>Here is what you should do: use try-catch (in T-SQL) to detect the deadlock condition.  When it happens, just re-run the query.  This is standard database programming practice.  </p>\n\n<p>There are good examples of this technique in Paul Nielson\'s <a href="https://rads.stackoverflow.com/amzn/click/com/0764542567" rel="nofollow noreferrer" rel="nofollow noreferrer">Sql Server 2005 Bible</a>.</p>\n\n<p>Here is a quick template that I use:</p>\n\n<pre><code>-- Deadlock retry template\n\ndeclare @lastError int;\ndeclare @numErrors int;\n\nset @numErrors = 0;\n\nLockTimeoutRetry:\n\nbegin try;\n\n-- The query goes here\n\nreturn; -- this is the normal end of the procedure\n\nend try begin catch\n    set @lastError=@@error\n    if @lastError = 1222 or @lastError = 1205 -- Lock timeout or deadlock\n    begin;\n        if @numErrors &gt;= 3 -- We hit the retry limit\n        begin;\n            raiserror(\'Could not get a lock after 3 attempts\', 16, 1);\n            return -100;\n        end;\n\n        -- Wait and then try the transaction again\n        waitfor delay \'00:00:00.25\';\n        set @numErrors = @numErrors + 1;\n        goto LockTimeoutRetry;\n\n    end;\n\n    -- Some other error occurred\n    declare @errorMessage nvarchar(4000), @errorSeverity int\n    select    @errorMessage = error_message(),\n            @errorSeverity = error_severity()\n\n    raiserror(@errorMessage, @errorSeverity, 1)\n\n    return -100\nend catch;    \n</code></pre>\n'}, {'answer_id': 21927, 'author': 'Mark Brackett', 'author_id': 2199, 'author_profile': 'https://Stackoverflow.com/users/2199', 'pm_score': 3, 'selected': False, 'text': "<p>Before burning the house down to catch a fly with NOLOCK all over, you may want to take a look at that deadlock graph you should've captured with Profiler.</p>\n\n<p>Remember that a deadlock requires (at least) 2 locks. Connection 1 has Lock A, wants Lock B - and vice-versa for Connection 2. This is an unsolvable situation, and someone has to give.</p>\n\n<p>What you've shown so far is solved by simple locking, which Sql Server is happy to do all day long.</p>\n\n<p>I suspect you (or LINQ) are starting a transaction with that UPDATE statement in it, and SELECTing some other piece of info before hand. But, you really need to backtrack through the deadlock graph to find the locks <em>held</em> by each thread, and then backtrack through Profiler to find the statements that caused those locks to be granted. </p>\n\n<p>I expect that there's at least 4 statements to complete this puzzle (or a statement that takes multiple locks - perhaps there's a trigger on the Posts table?).</p>\n"}, {'answer_id': 22019, 'author': 'Guy', 'author_id': 993, 'author_profile': 'https://Stackoverflow.com/users/993', 'pm_score': 2, 'selected': False, 'text': '<p>Q. Why are you storing the <code>AnswerCount</code> in the <code>Posts</code> table in the first place?</p>\n\n<p>An alternative approach is to eliminate the "write back" to the <code>Posts</code> table by not storing the <code>AnswerCount</code> in the table but to dynamically calculate the number of answers to the post as required.</p>\n\n<p>Yes, this will mean you\'re running an additional query:</p>\n\n<pre><code>SELECT COUNT(*) FROM Answers WHERE post_id = @id\n</code></pre>\n\n<p>or more typically (if you\'re displaying this for the home page):</p>\n\n<pre><code>SELECT p.post_id, \n     p.&lt;additional post fields&gt;,\n     a.AnswerCount\nFROM Posts p\n    INNER JOIN AnswersCount_view a\n    ON &lt;join criteria&gt;\nWHERE &lt;home page criteria&gt;\n</code></pre>\n\n<p>but this typically results in an <code>INDEX SCAN</code> and may be more efficient in the use of resources than using <code>READ ISOLATION</code>.</p>\n\n<p><em>There\'s more than one way to skin a cat.  Premature de-normalisation of a database schema can introduce scalability issues.</em></p>\n'}, {'answer_id': 26558, 'author': 'John Dyer', 'author_id': 2862, 'author_profile': 'https://Stackoverflow.com/users/2862', 'pm_score': 1, 'selected': False, 'text': "<p>So what's the problem with implementing a retry mechanism?  There will always be the possibility of a deadlock ocurring so why not have some logic to identify it and just try again?  </p>\n\n<p>Won't at least some of the other options introduce performance penalties that are taken all the time when a retry system will kick in rarely?  </p>\n\n<p>Also, don't forget some sort of logging when a retry happens so that you don't get into that situation of rare becoming often.</p>\n"}, {'answer_id': 26621, 'author': 'aquinas', 'author_id': 82208, 'author_profile': 'https://Stackoverflow.com/users/82208', 'pm_score': 2, 'selected': False, 'text': "<p>You definitely want READ_COMMITTED_SNAPSHOT set to on, which it is not by default. That gives you MVCC semantics. It's the same thing Oracle uses by default. Having an MVCC database is so incredibly useful, NOT using one is insane. This allows you to run the following inside a transaction:</p>\n\n<p>Update USERS Set FirstName = 'foobar';\n//decide to sleep for a year.</p>\n\n<p>meanwhile without committing the above, everyone can continue to select from that table just fine. If you are not familiar with MVCC, you will be shocked that you were ever able to live without it. Seriously. </p>\n"}, {'answer_id': 27617, 'author': 'Leon Bambrick', 'author_id': 49, 'author_profile': 'https://Stackoverflow.com/users/49', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m pretty uncomfortable about this question and the attendant answers. There\'s a lot of "try this magic dust! No that magic dust!"</p>\n\n<p>I can\'t see anywhere that you\'ve anaylzed the locks that are taken, and determined what exact type of locks are deadlocked.</p>\n\n<p>All you\'ve indicated is that some locks occur -- not what is deadlocking.</p>\n\n<p>In SQL 2005 you can get more info about what locks are being taken out by using:</p>\n\n<pre><code>DBCC TRACEON (1222, -1)\n</code></pre>\n\n<p>so that when the deadlock occurs you\'ll have better diagnostics.</p>\n'}, {'answer_id': 75926, 'author': 'MrB', 'author_id': 13484, 'author_profile': 'https://Stackoverflow.com/users/13484', 'pm_score': 5, 'selected': False, 'text': "<p>The OP question was to ask why this problem occured. This post hopes to answer that while leaving possible solutions to be worked out by others.</p>\n\n<p>This is probably an index related issue. For example, lets say the table Posts has a non-clustered index X which contains the ParentID and one (or more) of the field(s) being updated (AnswerCount, LastActivityDate, LastActivityUserId).</p>\n\n<p>A deadlock would occur if the SELECT cmd does a shared-read lock on index X to search by the ParentId and then needs to do a shared-read lock on the clustered index to get the remaining columns while the UPDATE cmd does a write-exclusive lock on the clustered index and need to get a write-exclusive lock on index X to update it.</p>\n\n<p>You now have a situation where A locked X and is trying to get Y whereas B locked Y and is trying to get X.</p>\n\n<p>Of course, we'll need the OP to update his posting with more information regarding what indexes are in play to confirm if this is actually the cause.</p>\n"}, {'answer_id': 192877, 'author': 'SqlACID', 'author_id': 19797, 'author_profile': 'https://Stackoverflow.com/users/19797', 'pm_score': 0, 'selected': False, 'text': "<p>I would continue to tune everything; how are is the disk subsystem performing? What is the average disk queue length? If I/O's are backing up, the real problem might not be these two queries that are deadlocking, it might be another query that is bottlenecking the system; you mentioned a query taking 20 seconds that has been tuned, are there others? </p>\n\n<p>Focus on shortening the long-running queries, I'll bet the deadlock problems will disappear.</p>\n"}, {'answer_id': 243187, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Had the same problem, and cannot use the "IsolationLevel = IsolationLevel.ReadUncommitted" on TransactionScope because the server dont have DTS enabled (!).</p>\n\n<p>Thats what i did with an extension method:</p>\n\n<pre><code>public static void SetNoLock(this MyDataContext myDS)\n{\n    myDS.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");\n}\n</code></pre>\n\n<p>So, for selects who use critical concurrency tables, we enable the "nolock" like this:</p>\n\n<pre><code>using (MyDataContext myDS = new MyDataContext())\n{\n   myDS.SetNoLock();\n\n   //  var query = from ...my dirty querys here...\n}\n</code></pre>\n\n<p>Sugestions are welcome!</p>\n'}, {'answer_id': 870449, 'author': 'Remus Rusanu', 'author_id': 105929, 'author_profile': 'https://Stackoverflow.com/users/105929', 'pm_score': 3, 'selected': False, 'text': "<p>Typical read/write deadlock comes from index order access. Read (T1) locates the row on index A and then looks up projected column on index B (usually clustered). Write (T2) changes index B (the cluster) then has to update the index A. T1 has S-Lck on A, wants S-Lck on B, T2 has X-Lck on B, wants U-Lck on A. Deadlock, puff. T1 is killed.\nThis is prevalent in environments with heavy OLTP traffic and just a tad too many indexes :). Solution is to make either the read not have to jump from A to B (ie. included column in A, or remove column from projected list) or T2 not have to jump from B to A (don't update indexed column). \nUnfortunately, linq is not your friend here...</p>\n"}]
['https://Stackoverflow.com/questions/20047', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1/']