PostgreSQL tenant restore

How to Restore a Single Tenant in PostgreSQL

To restore one PostgreSQL tenant, recover only the database, schema, or rows belonging to that customer. The correct method depends on your isolation model. A full database restore doesn’t automatically identify tenant boundaries.

For shared tables, the safest approach is usually to restore into an isolated recovery database, extract the tenant’s records, and replace production data through a controlled transaction. Start by identifying exactly what your backup contains.

Key takeaways

  • Separate databases and schemas support object-level recovery; shared tables require tenant-filtered extraction.
  • Restore nonselective backups away from production before extracting customer data.
  • Pause tenant writes, preserve the current state, and handle related records together.
  • Validate business outcomes and isolation before reopening access.

Choose the PostgreSQL tenant restore method

Your tenant architecture determines the recovery boundary.

Tenant isolationRecovery methodMain risk
Separate databaseRestore the tenant database into a replacement databaseMissing roles or external dependencies
Separate schemaExtract and restore the tenant schemaDependencies outside that schema
Shared tablesExtract rows using tenant-scoped SQLMissing related rows or affecting another tenant

PostgreSQL’s pg_dump documentation describes object selection and archive formats. Database objects and tenant-owned records are different recovery units.

A schema filter selects schemas, not customer-specific rows inside shared tables. Likewise, restoring an entire shared database over production replaces data for every tenant in that database.

For shared-table systems, build an inventory of tenant-owned tables before writing recovery SQL.

Prepare a recovery point and a safety boundary

Identify the intended business state

Record the tenant identifier, backup timestamp, desired recovery time, and tables involved. Decide whether you’re reversing an accidental deletion or replacing the tenant’s entire historical state.

A historical replacement can remove legitimate changes made after the backup. Agree on that loss before proceeding.

Also identify schema changes since the backup. Deleted columns, changed types, and new required fields can make historical rows incompatible with production.

Protect production and recovery access

Use compatible PostgreSQL tools, sufficient disk space, required extensions, and the roles referenced by the dump. Restore only trusted backups because restore operations can execute SQL.

Pause tenant writes across API requests, workers, integrations, and scheduled jobs. Preserve the tenant’s current state as a rollback artifact before replacement.

Use a separate, authorized recovery identity. Row-level security (RLS) can hide records from exports or block imports, so ordinary application credentials aren’t a reliable maintenance path.

Keep the recovery environment inaccessible to customer traffic and outbound automation.

Restore nonselective backups into a temporary database

For a custom-format logical archive, create an empty recovery database and restore there:

createdb --template=template0 recovery_scratch
pg_restore --exit-on-error --dbname=recovery_scratch backup.dump

--template=template0 creates a clean database. --exit-on-error stops restoration at the first SQL error, although earlier changes can remain. Discard a failed scratch database before retrying.

For a plain SQL dump, use psql instead of pg_restore:

psql -X --set=ON_ERROR_STOP=on 
  --dbname=recovery_scratch --file=backup.sql

-X ignores local startup configuration, while ON_ERROR_STOP prevents the script from continuing after an error. These are alternative restore paths for different backup formats.

Physical backups require a separate PostgreSQL instance. If you need point-in-time recovery, recover that instance using the base backup and required write-ahead log (WAL) archives, then extract the tenant.

Physical point-in-time recovery reconstructs the PostgreSQL cluster at the recovery target. Tenant selection happens afterward.

Keep the restored source read-only during extraction so related exports reflect a consistent recovered state.

Recover a separate database or schema

When each tenant has its own database

Restore the tenant’s archive into a new database using the preceding commands with the replacement database name. Avoid overwriting the active database during the first recovery attempt.

Restore required ownership and privileges, then validate application access. During cutover, stop writes, switch the tenant’s connection mapping, and recycle connections still attached to the old database.

Keep the old database isolated until the rollback window closes. Shared services, such as identity or billing systems, may still need reconciliation.

When each tenant has its own schema

Extract the recovered schema into a custom archive:

pg_dump --format=custom --schema=tenant_42 
  --dbname=recovery_scratch --file=tenant42.dump

Then restore into a prepared target:

pg_restore --single-transaction --exit-on-error 
  --dbname=prepared_target tenant42.dump

--format=custom creates an archive for pg_restore. --schema selects the named schema, while --single-transaction makes the restore atomic and cannot accompany parallel restoration.

A selected schema doesn’t automatically include dependencies elsewhere. Provision compatible shared types, extensions, and referenced objects first.

Inspect archive contents with pg_restore --list tenant42.dump. PostgreSQL’s pg_restore reference explains selection and transaction options.

Don’t run this against an existing tenant schema expecting an automatic merge.

Extract tenant rows from shared tables

For shared tables, recover the full database first, then export only the authorized tenant’s records.

For an application table named app.documents with tenant_id, id, and title, run this inside psql connected to the scratch database:

\copy (SELECT tenant_id, id, title FROM app.documents WHERE tenant_id = 42) TO '/secure/tenant42_documents.csv' WITH (FORMAT csv, HEADER true)

\copy writes through the client, so the path belongs to the machine running psql. Restrict access to that directory.

Export every authoritative column required by your actual schema. Explicit column lists prevent accidental column-order mismatches.

Repeat the process for related tables. Include records linked indirectly through tenant-owned parents, even when those child tables lack a tenant_id column.

However, don’t replace shared reference data merely because a recovered row points to it. Global users, product catalogs, and cross-tenant memberships need application-specific treatment.

For multiple exports, use one repeatable-read transaction if the recovery source could change during extraction.

Stage shared-table data before replacing production rows

The following example covers a standalone documents table. Applications with related tables must expand the transaction to include those dependencies.

First, import into a temporary staging table on the production connection:

CREATE TEMP TABLE recovered_documents (
    tenant_id bigint NOT NULL CHECK (tenant_id = 42),
    id bigint NOT NULL,
    title text
);


\copy recovered_documents (tenant_id, id, title) FROM '/secure/tenant42_documents.csv' WITH (FORMAT csv, HEADER true)

The constraint rejects foreign tenant identifiers. Before replacement, compare staging counts and identifiers against the recovered source.

Then replace the tenant’s rows:

BEGIN;
SET LOCAL lock_timeout = '5s';


DELETE FROM app.documents WHERE tenant_id = 42;


INSERT INTO app.documents (tenant_id, id, title)
SELECT tenant_id, id, title
FROM recovered_documents;


COMMIT;

Keep staging and replacement on the same connection because temporary tables are session-specific. For scripted execution, use psql -X --set=ON_ERROR_STOP=on so errors stop the script. A disconnected, uncommitted transaction rolls back.

The lock timeout limits lock waiting; it doesn’t limit total execution time. Large replacements can still generate substantial WAL and compete with other tenants.

Avoid TRUNCATE on shared tables. Also review triggers before execution, since inserts and deletes may create audit events or enqueue work.

Handle foreign keys and sequences deliberately

Preserve relationship boundaries

Delete child records before parents, then insert parents before children. Keep the related replacement inside one transaction when its size permits.

Tenant-scoped relationships should remain tenant-scoped during recovery. For example, a document’s (tenant_id, folder_id) should reference the matching tenant’s folder.

Deferrable constraints can accommodate some dependency cycles when deferred within a transaction. Ordinary foreign keys don’t become deferrable through a restore setting.

Avoid disabling constraints as a shortcut. That removes protections against orphaned or cross-tenant records.

Keep generated identifiers safe

Restored explicit IDs don’t necessarily advance the sequence used for future inserts. Inspect sequence ownership and state for restored integer identifiers.

Never reset a shared sequence using only the recovered tenant’s highest ID. Its next value must remain safe for every tenant.

Coordinate any forward adjustment with all writers using that sequence. PostgreSQL sequence changes aren’t rolled back like ordinary table updates, so record their previous state separately.

UUID-based identifiers don’t require sequence repair, but uniqueness and relationship checks still apply.

Validate recovery and preserve a usable rollback

Compare recovered and production row counts per table. Also reconcile identifiers, important values, and business totals. Matching counts alone can conceal incorrect records.

Test parent-child relationships, deleted-record recovery, and important workflows. For document storage, confirm that restored metadata points to available object versions. A database backup doesn’t recover externally stored files automatically.

Exercise authorization through the actual restricted application role. Establish trusted tenant context inside the transaction, then test reads and writes through the normal pooling path. Confirm that another tenant cannot access recovered records.

Before reopening traffic, inspect unrelated tenants for unexpected changes.

Retain the pre-restore export, recovery scripts, timestamps, and validation results. Transaction rollback protects against failures before commit. After commit, reversing the operation requires another controlled restore or repair.

If writes resume before rollback, reconcile those newer changes rather than blindly replaying the old snapshot. Rebuild affected caches and search indexes after database validation.

Frequently asked questions

Can RLS perform the tenant recovery automatically?

No. RLS controls row access; it doesn’t identify every recovery dependency or merge historical records. Use an audited maintenance path, then validate with the restricted application role and transaction-local tenant context.

Can other tenants stay online during recovery?

Often, yes, when the recovery changes only one tenant’s database, schema, or rows. However, shared-table locks, storage traffic, and WAL generation can affect everyone. Pause the target tenant’s writes and monitor database contention during replacement.

Make tenant recovery a controlled replacement

A reliable PostgreSQL tenant restore starts with the correct isolation boundary. Recover broadly into an isolated environment when necessary, then move only the intended database objects or tenant records.

Treat validation and rollback as part of the restore itself. Recovery is complete when the tenant’s data and relationships work correctly, authorization holds, and unrelated customers remain unaffected.

About the author

The SAAS Podium

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *