Quick answer
Start a PostgreSQL schema with ownership, invariants, and the queries users need. Encode required values, uniqueness, valid relationships, and simple row checks in the database rather than relying entirely on UI validation. Choose indexes from actual filter and ordering patterns. A schema is an integrity and access contract, not just a set of ORM models.
A hypothetical activity tracker provides a useful example: users own sessions, sessions have start and end times, and the interface lists recent sessions for one user. WatersportGPS's public description covers activities across devices, but the portfolio does not expose its database. The schema below is educational and does not claim that project's implementation.
Practical implementation steps
Write invariants before columns
Decide whether an item can exist without an owner, which identifiers are public, and what deletion means. Use foreign keys to prevent dangling relationships. Choose cascade only when deleting the parent should intentionally remove dependents; otherwise restrict deletion or model retention explicitly. A convenience cascade can destroy records that another feature still needs.
Select types for meaning
Use timestamptz for instants that must compare across time zones. It stores the instant, not the original named time zone; retain a separate zone identifier when a product needs local scheduling rules. Use date for calendar-only values. Define null deliberately: an unfinished session can have no end time, while a missing owner should usually be rejected.
Index the query, not every field
For a user-scoped recent-session list, a B-tree beginning with user_id and followed by created_at and a tie-breaker can support the filter and ordering. Verify with representative data and the planner. Each index consumes storage and write work. A foreign key does not automatically create an index on the referencing column; add one when joins or parent changes justify it.
Plan compatible migrations
For an existing application, separate adding a column, backfilling existing records, switching writes and reads, and tightening constraints. Review locks and runtime cost before applying a large change. A migration that succeeds on an empty local database says little about production data quality or old application instances. Define rollback behavior where possible and prefer forward repair when rollback would lose newly written data.
Implementation example
The SQL below is shown inside a bash example to run against an isolated development database with psql. It creates an illustrative schema from scratch; it is not a migration to run on an existing production schema.
psql "$DATABASE_URL" <<'SQL'
CREATE TABLE app_user (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);
CREATE TABLE activity_session (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id bigint NOT NULL REFERENCES app_user(id) ON DELETE RESTRICT,
started_at timestamptz NOT NULL,
ended_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
CHECK (ended_at IS NULL OR ended_at >= started_at)
);
CREATE INDEX activity_session_recent
ON activity_session (user_id, created_at DESC, id DESC);
SQL
The check validates one row's time relationship, and NOT NULL prevents an unknown start time. The database relationship does not authorize a requester to read another user's sessions; enforce that in scoped application queries or a deliberately designed row-security layer. Keep transactions around operations that must write several related records atomically.
Tradeoffs and alternatives
Normalize stable relationships when they need referential integrity and independent queries. JSONB can fit variable attributes, but it does not excuse abandoning validation or indexing strategy. Identity integers and UUIDs each have operational and exposure considerations; choose from the identifier contract rather than fashion. Keep confidential fields out of default API projections regardless of storage type.
Common mistakes
- Putting every invariant only in an ORM hook.
- Using a timestamp without defining time-zone meaning.
- Cascading deletion without a retention decision.
- Assuming foreign keys index the referencing column.
- Adding indexes without measuring query plans and write cost.
Production checklist
- Ownership and public identifiers are explicit.
- Nullability, uniqueness, checks, and foreign keys match the domain.
- Time values distinguish instants and calendar values.
- Important query plans use representative data.
- Migration locks and old-client compatibility are reviewed.
- Application access checks remain separate from integrity constraints.
FAQ
Should all fields be JSONB?
No. Use relational columns for values with stable meaning, relationships, and frequently queried constraints. JSONB is useful when variability is real and its consumers still enforce a contract.
Does a foreign key enforce user ownership?
It enforces a valid relationship between rows. It does not know which authenticated requester may access them. Keep scoped authorization in every read and write path.
Conclusion
Model the domain's invariants first, support the important queries second, and migrate deliberately. A robust schema prevents invalid relationships while leaving authentication, authorization, and API compatibility as explicit application responsibilities.
Primary sources
Related guides and examples
Need this implemented in a real product?
One connected implementation across the interface, application logic, APIs, and data layer.