2 Pods trying to write same value at same moment in DB producing a unique constraint error

12/9/2021

I have 2 pods running each a copy of the same java enterprise application using Hibernate. Underlying is a Oracle DB. The application has a scheduled loader for static data, which is executed each our, defined by a cronjob. The loaded result will be stored to the database. This means, both pods execute the scheduler at the same moment.

After I truncate the table, I store the result as entities with entityManager.merge(..) which I thought should solve the problem, as it should overwrite existing row. This most probably doesn't work because the two EntityManager instances of the pods don't know each other and probably still produce inserts which end up in a conflict.

I was already looking into ignoring the duplicate key error, but was wondering if there might be a cleaner solution.

How can I handle multiple instances which simultaneously write to a db?

-- Herr Derb
concurrency
hibernate
java
kubernetes
oracle

1 Answer

12/9/2021

You need a way to prevent the concurrent access. Have a look at this library https://github.com/lukas-krecan/ShedLock which you can use to implement a locking mechanism using JDBC.

-- Thomas
Source: StackOverflow