1

I have one controller method which creates new order in database with incremental custom order id (i.e. ABC000005)

Order table has below fields

Id (PK)
Name
CustomOrderId
DateTime

To implement that I have written a method like below

var lastOrder = _dbContext.Order.OrderByDescending(x=>x.DateTime).First();
var lastOrderCustomId = lastOrder.CustomOrderId;

// Some other code which takes around 2 seconds

var newOrderId = //Calculation to increment custom order id (i.e. ABC000005 to ABC000006)
var newOrder = new Order();
newOrder.Name = "abc";
newOrder.DateTime = DateTime.UtcNow;
newOrder.CustomOrderId = newOrderId;
_dbContext.Order.Add(newOrder);
_dbContext.SaveChanges();

Above code works well when there are sequential requests to server, but when there are concurrent requests 2 requests will fetch same CustomOrderId from database and creates two new identical CustomOrderId values in database.

One of the solution I had implemented to overcome this was to use thread lock above the code so that only one thread can access this code, but in that case concurrent requests takes more time and overall functionality to create order slows down.

Is there any other solution to this particular problem?

Rushi Soni
  • 1,088
  • 1
  • 13
  • 21

1 Answers1

0

Locking isn't the way for this as this needs to wait until one thread finish procesing. One way to overcome this is through caching.

  1. When you get a request to create a new order, check in cache whether latest_custom_order_id is present or not.
  2. If not present then fetch previous custom order id and calculate next order id.
  3. If present then calculate customer order id using that order id.
  4. Update value of cache key with the latest order id. eg. "latest_custom_order_id":"ABC0004"
  5. Save order
Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
  • This will also fail in case of two concurrent request checks and gets value from cache simultaneously, i.e. two requests executes 3rd step simultaneously and increment CustomOrderId with same value – Rushi Soni Oct 11 '18 at 11:42