SQL upsert for counters (ON CONFLICT DO UPDATE)

6802
0

Counters are classic race-condition bait. If two requests read, increment, and write, you’ll lose updates under load. I prefer letting Postgres do the atomic work with an upsert: INSERT ... ON CONFLICT ... DO UPDATE to increment the existing value. The benefit is no distributed lock and no transaction dance in application code. I also keep the counter table narrow and indexed by the natural key (like snip_id). If you’re tracking multiple counters, separate columns beat JSON so updates stay cheap.