title: Correct concurrency handling using EF Core 2.1 with SQL Server
body: <p>I am currently working on an API using ASP.NET Core Web API along with Entity Framework Core 2.1 and a SQL Server database. The API is used to transfer money from two accounts A and B. Given the nature of the B account which is an account that accepts payments, a lot of concurrent requests might be executed at the same moment. As you know if it's not well managed, this can result in some users not seeing their payments arrive.</p>
  
  <p>Having spent days trying to achieve concurrency I can't figure out what the best approach is. For the sake of simplicity I created a test project trying to reproduce this concurrency issue.</p>
  
  <p>In the test project, I have two routes: request1 and request2 each one perform a transfer to the same user the first one have an amount of 10 and the second one is 20. I put a <code>Thread.sleep(10000)</code> on the first one as follows:</p>
  
  <pre><code>    [HttpGet]
      [Route("request1")]
      public async Task&lt;string&gt; request1()
      {
          using (var transaction = _context.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
          {
              try
              {
                  Wallet w = _context.Wallets.Where(ww =&gt; ww.UserId == 1).FirstOrDefault();
                  Thread.Sleep(10000);
                  w.Amount = w.Amount + 10;
                  w.Inserts++;
                  _context.Wallets.Update(w);
                  _context.SaveChanges();
                  transaction.Commit();
              }
              catch (Exception ex)
              {
                  transaction.Rollback();
              }
          }
          return "request 1 executed";
      }
  
      [HttpGet]
      [Route("request2")]
      public async Task&lt;string&gt; request2()
      {
          using (var transaction = _context.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
          {
              try
              {
                  Wallet w = _context.Wallets.Where(ww =&gt; ww.UserId == 1).FirstOrDefault();
                  w.Amount = w.Amount + 20;
                  w.Inserts++;
                  _context.Wallets.Update(w);
                  _context.SaveChanges();
                  transaction.Commit();
              }
              catch (Exception ex)
              {
                  transaction.Rollback();
              }
          }
          return "request 2 executed";
      }
  </code></pre>
  
  <p>After executing request1 and request2 after in a browser, the first transaction is rolled back due to:</p>
  
  <pre><code>InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.
  </code></pre>
  
  <p>I can also retry the transaction but isn't there a better way? using locks ?</p>
  
  <p>Serializable, being the most isolated level and the most costly too is as said in the documentation:</p>
  
  <blockquote>
    <p>No other transactions can modify data that has been read by the current transaction until the current transaction completes.</p>
  </blockquote>
  
  <p>Which means no other transaction can update data that has been read by another transaction, which is working as intended here since the update in the request2 route wait for the first transaction (request1) to commit.</p>
  
  <p>The problem here is we need to block read by other transactions once the current transaction has read the wallet row, to solve the problem I need to use locking so that when the first select statement in request1 executes, all the transactions after need to wait for the 1st transaction to finish so they can select the correct value. Since EF Core have no support for locking I need to execute a SQL query directly, so when selecting the wallet I'll add a row lock to the current row selected</p>
  
  <pre><code>//this locks the wallet row with id 1
  //and also the default transaction isolation level is enough
  Wallet w = _context.Wallets.FromSql("select * from wallets with (XLOCK, ROWLOCK) where id = 1").FirstOrDefault();
  Thread.Sleep(10000);
  w.Amount = w.Amount + 10;
  w.Inserts++;
  _context.Wallets.Update(w);
  _context.SaveChanges();
  transaction.Commit();
  </code></pre>
  
  <p>Now this works perfectly even after executing multiple request the result of the transfers all combined is correct. In addition to that am using a transaction table that holds every money transfer made with the status to keep a record of each transaction in case something went wrong am able to compute all wallets amount using this table.</p>
  
  <p>Now there are other ways of doing it like:</p>
  
  <ul>
  <li>Stored procedure: but I want my logic to be in the application level</li>
  <li>Making a synchronized method to handle the database logic: this way all the database requests are executed in a single thread, I read a blog post that advise about using this approach but maybe we'll use multiple servers for scalability</li>
  </ul>
  
  <p>I don't know if I'm not searching well but I can't find good material for handling pessimistic concurrency with Entity Framework Core, even while browsing Github, most of code I've seen don't use locking.</p>
  
  <p>Which bring me to my question: is this the correct way of doing it?</p>
  
  <p>Cheers and thanks in advance.</p>