Database

Use Database Constraints as Application Invariants

Enforce uniqueness, relationships and valid ranges in the database so correctness survives concurrent requests and multiple code paths.

Application validation improves user feedback, but it cannot be the only protection for important data rules. Multiple requests can race, background jobs may bypass form validation and future code paths may forget an application-level check. Database constraints provide a final consistency boundary.

Use unique constraints

If an email address, external identifier or slug must be unique, enforce that rule with a unique index. A prior SELECT check is useful for friendly feedback but cannot prevent two concurrent requests from both passing before either inserts.

Model relationships with foreign keys

Foreign keys can prevent orphaned records and define deletion behavior. Choose cascade, restrict or set-null behavior deliberately. Review existing data before adding constraints because invalid historical rows can block the migration.

Constrain valid values

Use NOT NULL, suitable data types, check constraints where supported by the deployed database version, and carefully designed defaults. Application-level validation should still explain errors in user-friendly terms.

Handle constraint errors

Map known constraint violations to meaningful application outcomes. Do not expose raw SQL errors to visitors. Keep logging detailed enough for operators to identify the violated invariant without disclosing sensitive values.

Checklist

  • Enforce uniqueness with unique indexes.
  • Use foreign keys for required relationships.
  • Constrain nullability and valid values.
  • Clean historical data before adding constraints.
  • Translate database errors into safe application responses.
Share this page Help other developers discover this resource.