Skip to main content

Race-safe upsert with ON CONFLICT and conditional update

Insert or update a user’s daily usage counter atomically without SELECT-then-INSERT race conditions.

Official Reference

Model Answer & Explanation

INSERT INTO daily_usage (user_id, day, tokens)
VALUES ($1, CURRENT_DATE, $2)
ON CONFLICT (user_id, day)
DO UPDATE SET tokens = daily_usage.tokens + EXCLUDED.tokens
RETURNING tokens;

Never implement upsert in app code as SELECT -> if missing INSERT else UPDATE (that races under concurrency). Use INSERT ... ON CONFLICT (user_id, day) DO UPDATE SET tokens = usage.tokens + EXCLUDED.tokens. Only update when incoming data is newer if ordering matters.

Follow-up Interview Question · Why does ON CONFLICT require a matching UNIQUE constraint or non-partial unique index?

Module Context & References

PostgreSQL & Redis · Practice SQL & schema drills The classic SQL queries, locking patterns and optimization problems tested repeatedly
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.