Why this matters
Application checks are race-prone; DB constraints are authoritative and fast.
Enforce uniqueness at the database level (unique indexes/constraints) for identifiers and natural keys.
Application checks are race-prone; DB constraints are authoritative and fast.
Side-by-side examples engineers can pattern-match during review.
# check in app only
if db.exists('SELECT 1 FROM users WHERE email = ?', [email]):
raise ValueError('duplicate')ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email);if email in emails: ...CREATE UNIQUE INDEX idx_users_email ON users(email)From the same buckets as this rule.
Review SQL/database migrations for operations that can lock large tables or cause downtime. Examples: creating indexes without CONCURRENTLY (Postgres), ALTER COLUMN TYPE on big tables, adding NOT NULL without backfill, long-running updates without batching. Require an online migration strategy (CONCURRENTLY, backfill in batches, dual-write/expand-contract) and a rollback plan.