Preventing deadlock while logging via Entity Framework

tech: C#, Web App, Web API, Entity Framework, database

We were getting database deadlock errors alot -- not all the time -- but alot. We tracked it down to logging each webapi call that occurs for a web app operation. One operation, like search, results in multiple webapi calls. The calls were being executed at the same time and therefore being logged at the same time. These simultaneous operations were contending with each other -- causing deadlock.

The log code was innocent enough:

Context.ActivityAudits.Add(model);
Context.SaveChanges();

And the resulting SQL that Entity Framework generated and executed was not too surprising:

exec sp_executesql N'INSERT [dbo].[ActivityAudit]([RequestId], [Method], [Path], [IpAddress], [Date], [StatusCode], [Error], [UserName])
VALUES (@0, @1, @2, @3, @4, @5, NULL, @6)
SELECT [Id]
FROM [dbo].[ActivityAudit]
WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()'

Well, the INSERT is totally expected. And, when you think about how EF works, the SELECT makes sense too. After adding a record, it reads the new record's ID (primary key) to load back into the model object. Thing is, since this is for logging, the consuming code will never need the ID since it will never modify the object.

I made a guess that the problem was the SELECT and I was right. I don't understand why that is causing a deadlock, but it can and does sometimes.

I wanted to tell EF to not generate the SELECT ... to tell EF that we don't need or want the ID. After some googling I came to the conclusion that EF does not support this. You can't tell EF _not_ to read the ID.

So, I turned to custom SQL. I changed the code to this:

string command = @"
INSERT ActivityAudit([RequestId], [Method], [Path], [IpAddress], [Date], [StatusCode], [Error], [UserName])
VALUES(@RequestId, @Method, @Path, @IpAddress, @Date, @StatusCode, @Error, @UserName)";
Context.ExecuteSqlCommand(
command,
new SqlParameter("RequestId", (object)model.RequestId ?? DBNull.Value),
new SqlParameter("Method", (object)model.Method ?? DBNull.Value),
new SqlParameter("Path", (object)model.Path ?? DBNull.Value),
new SqlParameter("IpAddress", (object)model.IpAddress ?? DBNull.Value),
new SqlParameter("Date", model.Date),
new SqlParameter("StatusCode", model.StatusCode),
new SqlParameter("Error", (object)model.Error ?? DBNull.Value),
new SqlParameter("UserName", (object)model.UserName ?? DBNull.Value));

It's lengthy and it's error-prone since it's not generated by EF. But, it does eliminate the deadlocks. So, not ideal, but gets the job done.

Note that the reference parameter values are all like (object)val ?? DBNull.Value. This is required since passing null will cause a runtime error. Have to use DBNull.Value instead of null.

Comments

Popular posts from this blog

Unable to execute a sync in a worker thread

Worst dialog message I've ever seen