Skip to the page

Correctness under concurrency · core

Constraints: let the database guard your data

Constraints (PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK) make the database reject invalid data no matter which code path writes it, and a UNIQUE constraint is the only reliable way to stop duplicates under concurrency.

The notes

What you must know

  • PRIMARY KEY: unique and not null; identifies a row. FOREIGN KEY: the referenced row must exist; ON DELETE CASCADE / RESTRICT / SET NULL decides what happens to children.
  • UNIQUE: no two rows share the value. An app-level 'check if email exists, then insert' races; the constraint does not. Catch the unique-violation error (Postgres 23505) and return 409.
  • NOT NULL for required columns; DEFAULT for sensible defaults (created_at DEFAULT now()).
  • CHECK (qty >= 0), CHECK (status IN ('pending','paid','failed')); a CHECK passes when the expression is NULL, so combine with NOT NULL.
  • Partial unique index for business rules: one active subscription per user (UNIQUE ... WHERE status = 'active').
  • Postgres does not index foreign key columns automatically; add indexes for joins and cascading deletes.
  • Validation in the API gives friendly messages; constraints are the final guarantee.

The red pen

Common traps: mistake → fix

  • Mistake: We check uniqueness in code, so no UNIQUE constraint is needed

    Fix: two concurrent signups both pass the check.

  • Mistake: CHECK (age >= 18) rejects missing ages

    Fix: NULL passes a CHECK; add NOT NULL.

Easy to hard

Questions interviewers ask, easy to hard

  1. Which constraints do you use and why?
  2. Two users sign up with the same email at the same millisecond. What stops a duplicate?
  3. ON DELETE CASCADE vs RESTRICT: when would you use each?
  4. How do you enforce 'only one active subscription per user'?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview