Dolev
Dolev

Reputation: 40

Sync two server instances against one database

I'm using C# and the .NET framework, and I have a monolithic server which is connected to a database. I'm uploading the server to AWS and initialize two instances of it.

The problem is in writing to the database.

I'm using Entity Framework and the following is the problem code:

using (var db = new CordioContext())
{
    Student student = db.Students.Where(s => s.Id == studentId).FirstOrDefault();
    student.coursesCount++;
    db.SaveChanges();
} 

When I only have one instance of the server, I can put a lock on the student Id and avoid two threads trying to update the same entity at the same time.

What can I do when I have two different instances which are connected to the same database?

How it's done in microservices architecture?

I have read a little bit about transactions but I'm not sure this will solve my problem.

The example code above is just to explain the problem. In my code, I'm changing many more fields and transfer everything to a SQL query instead of EF code first is very ugly.

Thanks!

Upvotes: 0

Views: 410

Answers (1)

spatik
spatik

Reputation: 41

"updating the same entity at the same time. " - This 'at the same time' is very rare to happen, even if it does since you are already using entity framework, use versioning of the entities. "update XXX set (....) where XXX.version_id=old_version_id+1; This will take care of parallel updates. The DB writes are serialized.

Upvotes: 1

Related Questions