Sobes.tech
Junior — Middle

Was there a situation where problems occurred when saving data to the database during message sending?

sobes.tech AI

Answer from AI

Yes, there was a situation where problems with saving data to the database occurred when sending messages. The main reason was that write and send operations were performed separately, without a unified transaction, which led to desynchronization: the message was sent, but the data was not saved, or vice versa.

To solve this problem, I implemented transactional processing using the "Unit of Work" pattern and a transaction mechanism in the database. In C# with Entity Framework, it looked like this:

using (var transaction = context.Database.BeginTransaction())
{
    try
    {
        context.Messages.Add(messageEntity);
        context.SaveChanges();

        messageSender.Send(messageEntity);

        transaction.Commit();
    }
    catch
    {
        transaction.Rollback();
        throw;
    }
}

Thus, if message sending failed, changes in the database were rolled back, ensuring data integrity and system consistency.