I'm working within a microservice environment and have two independent Azure serverless functions that both perform a SQL INSERT
if a prior SELECT
returns no row. Each serverless function runs on an as-needed basis based on various triggers. At times, the functions can be running at the exact same time which appears to be exposing a race condition. The race condition being that both functions will first check if a row exists in a table and if it does not exist it will create it, but if both functions do this at the same time then the both see that no record exists and one creates it while the otherwise fails due to a unique key constraint in the database table.
What approaches are there for me to remove this race condition?
Is there a solution that I can perform purely in SQL (a query, locking, stored procedure, etc) that would allow me to leverage that solution in my code without having to go with a larger code modification to fix the issue?