Refactored the upsert query for postgres to be atomic