DEV Community

Cover image for 🏁🐘Winning Race Conditions With PostgreSQL

🏁🐘Winning Race Conditions With PostgreSQL

Randall on February 17, 2024

Race conditions suck! They can be extremely difficult to debug, and often only occur naturally in production at the most critical moments (times of...
Collapse
 
akashkava profile image
Akash Kava

No matter what you do, you will still hit the race condition even after using NOT EXISTS, best way is to retry after failure to check if record already exists in next attempt. There should be at least two attempts. First check if record exists, if not try to insert, if insert fails, check if record exists or not.

I have used this method in entity access ORM I have written for typescript and there are two methods such as selectOrInsert, upsert, both of which retries operation at least 3 times.

Collapse
 
mistval profile image
Randall • Edited

Absolutely, or you can choose to just let the error bubble up to the user and they can give it another shot, especially if you expect the error to be very rare under normal conditions. In these cases the goal is to avoid violation of the constraints you want on your data, rather than avoiding errors necessarily.