DEV Community

Cover image for PostgreSQL Schema vs Database: Which Should Separate Your Modules or Tenants?
Son Tran
Son Tran

Posted on Originally published at schemity.com

PostgreSQL Schema vs Database: Which Should Separate Your Modules or Tenants?

Disclosure: I build Schemity, a desktop ERD tool - this post is from our blog and uses it for the examples.

TL;DR: Use schemas to separate modules that still reference each other: a foreign key, a join and a transaction all cross a schema and none crosses a database. Use a separate database only when two parts must never share a transaction, a connection or a backup. For tenants, a schema each works for tens or hundreds: 1,000 tenants of 10 empty tables took 427 MB and 50,415 catalog rows on PostgreSQL 18.3.

In PostgreSQL, put two modules in separate schemas of one database when they still reference each other, and in separate databases only when they must share nothing. A foreign key, a join and a transaction all cross a schema boundary, and none of them crosses a database boundary, so the choice is really a choice about what the database will still check for you.

Everything below ran on PostgreSQL 18.3 in a throwaway container, with default settings, on this database:

CREATE SCHEMA identity;
CREATE SCHEMA billing;

CREATE TABLE identity.users (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL UNIQUE,
    created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE identity.audit_log (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id bigint NOT NULL REFERENCES identity.users (id),
    action text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE billing.invoices (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id bigint NOT NULL REFERENCES identity.users (id),
    total numeric(12,2) NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX invoices_user_id_idx ON billing.invoices (user_id);
CREATE TABLE billing.audit_log (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    invoice_id bigint NOT NULL REFERENCES billing.invoices (id),
    action text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);
CREATE VIEW billing.user_totals AS
    SELECT u.id, u.email, sum(i.total) AS total
    FROM identity.users u JOIN billing.invoices i ON i.user_id = u.id
    GROUP BY u.id, u.email;
Enter fullscreen mode Exit fullscreen mode

identity.users holds 1,000 rows and billing.invoices holds 1,000,000 (87 MB with its indexes).

Postgres schema vs database: what is the difference?

A schema is a namespace inside one database, and a database is a separate catalog that a connection cannot see out of.

The PostgreSQL manual puts it in two sentences: a client connection "can only access data in a single database", and "Unlike databases, schemas are not rigidly separated". Everything in this table follows from that:

Two schemas, one database Two databases, one server
Foreign key between them Works Refused: cross-database references are not implemented
Join in one query Works Refused, same error (only through postgres_fdw or dblink)
One transaction over both Yes No: two connections, atomic only with two-phase commit
Connection One One per database
Roles Shared Shared (roles belong to the server)
Extensions Installed once Installed per database
Empty cost 2 ms to create, no files 44 ms to create, 7.6 MB on disk
Move a table across ALTER TABLE ... SET SCHEMA, 2.6 ms Dump and restore
Dump or restore one alone pg_dump -n, not self-contained pg_dump, self-contained

If you come from MySQL, a PostgreSQL schema is what MySQL calls a database: there CREATE SCHEMA is a synonym for CREATE DATABASE, and two of them on one server can join and reference each other.

What can cross a schema boundary that cannot cross a database?

A foreign key, a view, a join and a transaction cross a schema, and a database boundary refuses all four.

The setup above already does it: billing.invoices.user_id references identity.users, and billing.user_totals joins the two schemas. Against a second database on the same server, both are refused with the same message:

SELECT * FROM crm.public.contacts;
-- ERROR:  cross-database references are not implemented: "crm.public.contacts"

CREATE TABLE billing.x (contact_id bigint REFERENCES crm.public.contacts (id));
-- ERROR:  cross-database references are not implemented: "crm.public.contacts"
Enter fullscreen mode Exit fullscreen mode

The usual workaround, postgres_fdw, gives you the join back and not the key. A foreign table can be queried, but it cannot be the target of a foreign key:

CREATE TABLE billing.fdw_child (user_id bigint REFERENCES remote.users (id));
-- ERROR:  referenced relation "users" is not a table
Enter fullscreen mode Exit fullscreen mode

So once two modules live in two databases, nothing stops an invoice from pointing at a user that was deleted. That is the same trade as dropping a foreign key between two modules, made for every key at once.

Does a separate schema isolate a module?

A schema isolates access and names, and it does not isolate dependencies.

Access first. A role granted only the billing tables cannot read identity directly, and the foreign key into identity is still enforced for it:

CREATE ROLE billing_app LOGIN;
GRANT USAGE ON SCHEMA billing TO billing_app;
GRANT SELECT, INSERT ON billing.invoices, billing.audit_log TO billing_app;
SET ROLE billing_app;

SELECT count(*) FROM identity.users;
-- ERROR:  permission denied for schema identity
INSERT INTO billing.invoices (user_id, total) VALUES (999999, 5);
-- ERROR:  insert or update on table "invoices" violates foreign key constraint "invoices_user_id_fkey"
Enter fullscreen mode Exit fullscreen mode

That is the property a module boundary wants: the billing code cannot query users, and it still cannot invent one. Mind the views, though. A view runs with its owner's privileges, so after GRANT SELECT ON billing.user_totals TO billing_app the same role read u1000@example.com out of identity.users through it.

Names second. Both schemas have an audit_log, and which one an unqualified name means depends on the session's search_path. With the default path ("$user", public) the name finds neither and SELECT count(*) FROM audit_log fails with relation "audit_log" does not exist. With SET search_path TO billing, identity it is billing.audit_log; swap the order and the same query reads identity.audit_log, and an unqualified CREATE TABLE lands in whichever schema is first. Qualify every name in code that touches more than one schema.

Dependencies are what a schema does not contain. identity.users cannot be dropped, and neither can its id column or its primary key, because of a key that lives in billing:

DROP TABLE identity.users;
-- ERROR:  cannot drop table identity.users because other objects depend on it
Enter fullscreen mode Exit fullscreen mode

DROP SCHEMA identity CASCADE does go through, and takes four objects with it, two of them in the other schema: the constraint invoices_user_id_fkey on billing.invoices and the view billing.user_totals, reported only in a NOTICE.

How hard is it to move a table later?

Between schemas a move is a catalog update that took 2.6 ms for a million rows, and between databases it is a dump and a restore that loses every key crossing the boundary.

ALTER TABLE billing.invoices SET SCHEMA identity took 2.6 ms on the 1,000,000-row table. Its relfilenode was 16420 before and after, so no data was rewritten, and the foreign key from billing.audit_log followed it: its definition read REFERENCES identity.invoices(id) afterwards. A view that reads the table by name in another schema keeps working too, because PostgreSQL tracks it by object id.

Moving both schemas to a new database with pg_dump | psql took 2.3 seconds for the same data, which is fast, and is not the hard part. The hard part is moving one. A dump of billing alone, taken before the role above existed, is not self-contained:

$ pg_dump -n billing --schema-only shop | psql billing_db
ERROR:  relation "identity.users" does not exist
ERROR:  relation "billing.user_totals" does not exist
ERROR:  schema "identity" does not exist
Enter fullscreen mode Exit fullscreen mode

Both tables arrive, the view does not, and the only foreign key left is the one inside the schema. invoices_user_id_fkey is gone and cannot be put back, because its target is now in another database. Starting with schemas keeps the move to a database open; starting with databases makes the move back a data-cleaning project, since rows written without the key may already be orphans.

Should each tenant get its own schema or its own database?

A schema per tenant works for tens or hundreds of tenants and gets expensive in the thousands, because every table costs catalog rows and files even when it is empty.

I created 1,000 tenant schemas of 10 small tables each, with no rows in any of them:

Measured on PostgreSQL 18.3, default settings Result
Creating all 1,000 in one transaction Failed at the 288th: out of shared memory, hint to raise max_locks_per_transaction (default 64)
Creating them one transaction per tenant Worked
Rows in pg_class 50,415 (a new database has 415)
Database size, zero rows of data 427 MB
pg_dump --schema-only of the database 2.9 s, 7.1 MB of SQL
pg_dump --schema-only -n tenant_500 0.54 s
DROP SCHEMA tenant_1000 CASCADE 17 ms

Each empty table brings three 8 kB files: the index for its key, the sequence for its identity and the index of its TOAST table. That is 234 MB, and the rest is the catalog describing them: pg_attribute alone was 91 MB, pg_depend 33 MB and pg_class 24 MB. A migration then has to run 1,000 times, and anything that touches many tenants in one transaction meets the lock limit that stopped the first attempt.

A database per tenant costs more per tenant (7.6 MB and 44 ms each, empty) and buys the hard boundary: a tenant can be backed up, restored, moved to another server or deleted alone, and no query can join two of them. It also means one connection pool per tenant, since a connection belongs to one database.

For most products the third option is the right default: one set of tables with a tenant_id column, with composite foreign keys or row-level security keeping tenants apart.

Which should I use: a schema or a database?

Choose a schema unless you can name the thing the two parts must never share.

  • Modules of one application (billing, identity, catalog): schemas. You keep the keys between them, one migration, one backup, and a role per module if you want the access boundary.
  • A tenant that must be restored, moved or deleted alone, or that has a contractual isolation requirement: a database.
  • Many small tenants: neither, use a tenant_id column.
  • Two applications with different release cycles and no shared rows: databases.
  • Staging and production: separate servers, not either of these.

How do you find the foreign keys that cross schemas?

Compare the schema of each foreign key's table with the schema of the table it references in pg_constraint.

SELECT con.conname,
       con.conrelid::regclass  AS referencing_table,
       con.confrelid::regclass AS referenced_table
FROM pg_constraint con
JOIN pg_class c ON c.oid = con.conrelid
JOIN pg_class p ON p.oid = con.confrelid
WHERE con.contype = 'f' AND c.relnamespace <> p.relnamespace;
Enter fullscreen mode Exit fullscreen mode

On the example it returns one row: invoices_user_id_fkey, from billing.invoices to identity.users. That list is the real coupling between your schemas, and it is the list of keys you would lose by splitting them into databases. Views are the other half: billing.user_totals reads identity.users and appears in no foreign key list.

How does Schemity read a database with several schemas?

Schemity reads one schema per diagram and reports the keys and views from other schemas that depend on its tables.

Schemity is database design software that reads your live database, shows the impact of every schema change before it runs, and keeps the diagram as a file in Git. For a PostgreSQL connection, the Schema field in the connection dialog loads the database's schemas so you pick one, and the diagram draws that schema's tables. A diagram of billing shows invoices and audit_log with the key between them; invoices.user_id keeps its foreign key marker with no line, because the table at the other end is in identity, and the field's details name the target as identity.users.id. A migration that has to add the key again writes REFERENCES "identity"."users", so it cannot land on a users table of the current schema.

Schemity reading the billing schema of a PostgreSQL 18.3 database: invoices and audit_log joined by a relationship line, the user_totals view beside them, and invoices.user_id selected with its foreign key marker and no line. The field details panel shows FK ticked, type BIGINT, References identity.users.id (ON DELETE NO ACTION, ON UPDATE NO ACTION) and the index invoices_user_id_idx (user_id).

Open the identity diagram and plan a change to users.id, and impact analysis (Schemity Pro) lists what the diagram cannot draw: the foreign key invoices_user_id_fkey on billing.invoices and the view billing.user_totals, each with what PostgreSQL will do. Delete the users table and the planned DROP TABLE ... CASCADE would take both with it, which PostgreSQL reports only in a NOTICE, so the finding says they are dropped too. A drop of the id column is refused while the key exists, a rename is followed, and a type change is refused unless the two columns can still be compared. On this example the view refuses a type change first (cannot alter type of a column used by a view or rule). With the view, the identity and the key inside identity out of the way, bigint to integer or numeric passed, and to text or uuid failed with foreign key constraint "invoices_user_id_fkey" cannot be implemented. That is how you understand your schema one module at a time without losing the edges between modules.

Schemity's change preview for dropping identity.users on PostgreSQL 18.3: users outlined in red with its line to audit_log, the planned migration ending in DROP TABLE IF EXISTS "users" CASCADE, and three impact findings. The second says 2 objects depend on users: view billing.user_totals depends on users.email and foreign key invoices_user_id_fkey on billing.invoices depends on users.id, each with "CASCADE drops it too, and the database reports that only as a notice."

Import SQL does the same for a dump: when the file holds more than one schema it lists them to pick from, and it keeps two tables of the same name in different schemas apart, so neither audit_log overwrites the other.

If your modules share one schema instead, a context view gives you the per-module picture without moving anything. A context view is a focused sub-diagram that displays a chosen subset of the main diagram while the main view remains the single source of truth.

When a table turns out to sit in the wrong module, the cycle it creates is the usual symptom, covered in circular dependencies between modules.

Top comments (0)