Overview
This post walks through a real error I hit in production: duplicate key value violates unique constraint. We explore the stack trace, reproduction, and a robust fix.
Key points
- Validate first, write once patterns
- Database-level ON CONFLICT DO NOTHING
- Safe upserts with unique indexes
Code
// Example with PostgreSQL
await db.user.create({ email })
.catch(e => {
if (e.name === 'SequelizeUniqueConstraintError') {
return db.user.findOne({ where: { email } })
}
throw e
})
Takeaways
Prefer database constraints and idempotent endpoints over optimistic UI-only checks.