Dragonfly Cloud announces new enterprise security features - learn more

Dragonfly

Question: How can you replicate only one database in PostgreSQL?

Answer

PostgreSQL's built-in replication solutions, such as streaming replication or logical replication, are designed with a cluster-wide approach, meaning they replicate all databases within a PostgreSQL cluster (instance). However, if you need to replicate only a single database, your best approach is to use logical replication.

Logical Replication

Logical replication allows you to replicate data at the granularity of tables. This means you could effectively replicate all tables from one database, achieving database-level replication. Here's how you can set it up:

On the Source Server (Publisher):

  1. Enable Logical Replication: Edit postgresql.conf and set wal_level = logical.
  2. Configure Client Authentication: Edit pg_hba.conf to allow connections from the subscriber server.
  3. Create Publication:
    ```sql
    CREATE PUBLICATION my_publication FOR ALL TABLES;
    ```

Note: Execute this command for each database you want to replicate.

On the Destination Server (Subscriber):

  1. Create Subscription:
    Assuming the publication was created on a source database named source_db, you would execute:
    ```sql
    CREATE SUBSCRIPTION my_subscription
    CONNECTION 'host=source_host port=5432 dbname=source_db user=replica_user password=replica_pass'
    PUBLICATION my_publication WITH (copy_data = true);
    ```

Execute this command in the destination database where you wish to replicate the source database's tables.

Considerations

While PostgreSQL does not natively support single-database physical replication out of the box, logical replication provides a flexible alternative that can meet similar needs with table-level granularity.

Was this content helpful?

Other Common PostgreSQL Questions (and Answers)

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost