problem with concurrent updates on my database table

Viewed 347

Different microservices might execute at the same time the following command on my database table

> update table_2 set final_date='23123123' where section_id=10  

The section_id might have 50K rows. What might go wrong if multiple connection execute the same command (and same values)? How can I prevent a potential problem?

2 Answers

Obviusly if the command will execute multiple times this will cause you having a headache because you will not get what you want. So try to determine the logic before then apply it correctly.For example you can decide to take only the first change that arrive and discard the others after catching them (you can give a message like 'record locked can't be modified!').

First, nothing will go "wrong" in your application. (unless you somehow exceed the maximum connections allowed by either the database or your application) The database itself will handle not allowing multiple connections to "update" the same row at "the same time". Unless you explicitly state otherwise in your SQL statement, the default locking mechanisms will force your multiple attempts to update the same row into a queue.

Now your concern is the data integrity. Determine what IS a problem, and what ISN'T, trying to fix your application layer to prevent multiple nodes firing the same request at the same time may not be worth the time and trouble if just letting the database manage multiple requests delivers a suitable result.

I offer several solutions that will reduce the number of UPDATES executed but not the number of connections your application will use to the database.

Add more logic to your UPDATE statement - for example only update if the existing value for final date is more than 5 sec old (or 5 minutes, or 5 hours, whatever fits your use case). It should not have to be a large value because these statements would execute quickly if requested at the same time by the application nodes.

AND/OR checkout "skip locked" here: https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html

it will essentially take the first node's request and then all others that attempt an update simply stop if they attempt to update while the row is locked. This could take the place of the logic above, but only for requests that occur WHILE the row is already locked by a previous UPDATE.

Related