How to handle Concurrent/Duplicate Transactions in a microservice architecture

microservices

enter image description here

Above Image shows the system design of my application. Things work fine when there is a single instance of my microservice but now I am planning to scale it and have the following concern about it :

How to handle concurrent update request on the same record initiated by two different instances of a microservice.

I know that locking is one of the ways to achieve this goal in a predictable and a cleaner way but it comes at the cost of performance degradation.
CompareAndSwap is another approach that I know where each thread reads a record with some e-tag value and while writing a record the DB compares e-tag value held by a thread to the current value if both match then the write is successful else the exception is thrown by the DB. This is an optimistic approach but here the number of network round-trips between app server and DB are increased that could hamper the performance and lead to increased network traffic.
Is there any better approach to handle this problem?

Best Answer

It seems to me that you have the same problem even with one instance of the microservice.

You can't just throw a load balancer in front of two databases and call it a clustered database.

The standard approaches are

  • Have n microservices share a single database
  • Give each microservice its own database with no shared data
  • Split the database into multiple read and a single write database
  • Shard the data onto multiple databases each one having only part of the data
Related Topic