Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Docs: Add section on logical replication for setting up CDC from Supabase to a destination (#27087)

Chris Gwilliams34022bd5708c
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
index 0dcb96f727b..b06eb9be02e 100644
--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
@@ -917,10 +917,6 @@ export const database: NavMenuConstant = {
name: 'Database configuration',
url: '/guides/database/postgres/configuration',
},
- {
- name: 'Managing database replication',
- url: '/guides/database/replication',
- },
{
name: 'Query optimization',
url: '/guides/database/query-optimization',
@@ -960,6 +956,22 @@ export const database: NavMenuConstant = {
},
ormQuickstarts,
guiQuickstarts,
+ {
+ name: 'Database replication',
+ url: undefined,
+ items: [
+ { name: 'Overview', url: '/guides/database/replication' },
+ {
+ name: 'Setting up replication',
+ url: '/guides/database/replication/setting-up-replication',
+ },
+ {
+ name: 'Monitoring replication',
+ url: '/guides/database/replication/monitoring-replication',
+ },
+ { name: 'FAQ', url: '/guides/database/replication/faq' },
+ ],
+ },
{
name: 'Extensions',
url: undefined,
diff --git a/apps/docs/content/guides/database/postgres/setup-replication-external.mdx b/apps/docs/content/guides/database/postgres/setup-replication-external.mdx
index 02bbbb939f3..0e74c9df844 100644
--- a/apps/docs/content/guides/database/postgres/setup-replication-external.mdx
+++ b/apps/docs/content/guides/database/postgres/setup-replication-external.mdx
@@ -27,9 +27,9 @@ select pg_create_logical_replication_slot('example_slot', 'pgoutput');
<Admonition type="note">
-This will need a direct connection to your database and you can find the connection info in the [Dashboard](https://supabase.com/dashboard/project/_/settings/database).
+This will need a **direct** connection (not a Connection Pooler) to your database and you can find the connection info in the [Dashboard](https://supabase.com/dashboard/project/_/settings/database).
-You will also need to ensure that ipv6 is supported by your replication destination.
+You will also need to ensure that IPv6 is supported by your replication destination (or you can enable the [IPv4 add-on](/guides/platform/ipv4-address))
If you would prefer not to use the `postgres` user, then you can run `CREATE ROLE <user> WITH REPLICATION;` using the `postgres` user.
diff --git a/apps/docs/content/guides/database/replication.mdx b/apps/docs/content/guides/database/replication.mdx
index 18f2d05a604..ee5445662ff 100644
--- a/apps/docs/content/guides/database/replication.mdx
+++ b/apps/docs/content/guides/database/replication.mdx
@@ -1,93 +1,69 @@
---
-id: 'replication'
-title: 'Replication'
-slug: 'replication'
+title: 'Replication and change data capture'
+description: 'An introduction to logical replication and change data capture'
---
-Replication is a technique for copying the data from one database to another. Supabase uses replication functionality to provide a real-time API. Replication is useful for:
+Replication is the process of copying changes from your database to another location. It's also referred to as change data capture (CDC): capturing all the changes that occur to your data.
-- Spreading out the "load." For example, if your database has a lot of reads, you might want to split it between two databases.
-- Reducing latency. For example, you may want one database in London to serve your European customers, and one in New York to serve the US.
+## Use cases
-Replication is done through _publications_, a method of choosing which changes to send to other systems (usually another Postgres database). Publications can be managed in the [Dashboard](https://supabase.com/dashboard) or with SQL.
+You might use replication for:
-## Manage publications in the dashboard
+- **Analytics and Data Warehousing**: Replicate your operational database to analytics platforms like BigQuery for complex analysis without impacting your application's performance.
+- **Data Integration**: Keep your data synchronized across different systems and services in your tech stack.
+- **Backup and Disaster Recovery**: Maintain up-to-date copies of your data in different locations.
+- **Read Scaling**: Distribute read operations across multiple database instances to improve performance.
-1. Go to the [Database](https://supabase.com/dashboard/project/_/database/tables) page in the Dashboard.
-2. Click on **Publications** in the sidebar.
-3. Control which database events are sent by toggling **Insert**, **Update**, and **Delete**.
-4. Control which tables broadcast changes by selecting **Source** and toggling each table.
+## Replication in Postgres
-<video width="99%" muted playsInline controls={true}>
- <source
- src="https://xguihxuzqibwxjnimxev.supabase.co/storage/v1/object/public/videos/docs/api/api-realtime.mp4"
- type="video/mp4"
- />
-</video>
+Postgres comes with built-in support for replication via publications and replication slots. Refer to the [Concepts and terms](#concepts-and-terms) section to learn how replication works.
-## Create a publication
+## Setting up and monitoring replication in Supabase
-This publication contains changes to all tables.
+- [Setting up replication](/docs/guides/database/replication/setting-up-replication)
+- [Monitoring replication](/docs/guides/database/replication/monitoring-replication)
-```sql
-create publication publication_name
-for all tables;
-```
+<Admonition type="tip">
-## Create a publication to listen to individual tables
+If you want to set up a read replica, see [Read Replicas](/docs/guides/platform/read-replicas) instead. If you want to sync your data in real time to a client such as a browser or mobile app, see [Realtime](/docs/guides/realtime) instead.
-```sql
-create publication publication_name
-for table table_one, table_two;
-```
+</Admonition>
-## Add tables to an existing publication
+## Concepts and terms
-```sql
-alter publication publication_name
-add table table_name;
-```
+### Write-Ahead Log (WAL)
-## Listen to `insert`
+Postgres uses a system called the Write-Ahead Log (WAL) to manage changes to the database. As you make changes, they are appended to the WAL (which is a series of files (also called "segments"), where the file size can be specified). Once one segment is full, Postgres will start appending to a new segment. After a period of time, a checkpoint occurs and Postgres synchronizes the WAL with your database. Once the checkpoint is complete, then the WAL files can be removed from disk and free up space.
-```sql
-create publication publication_name
-for all tables
-with (publish = 'insert');
-```
+### Logical replication and WAL
-## Listen to `update`
+Logical replication is a method of replication where Postgres uses the WAL files and transmit those changes to another Postgres database, or a system that supports reading WAL files.
-```sql
-create publication publication_name
-for all tables
-with (publish = 'update');
-```
+### LSN
-## Listen to `delete`
+LSN is a Log Sequence Number that is used to identify the position of a WAL file in the WAL directory. It is often used to determine the progress of replication in subscribers and calculate the lag of a replication slot.
-```sql
-create publication publication_name
-for all tables
-with (publish = 'delete');
-```
+## Logical replication architecture
-## Remove a publication
+When setting up logical replication, three key components are involved:
-```sql
-drop publication if exists publication_name;
-```
+- `publication` - A set of tables on your primary database that will be `published`
+- `replication slot` - A slot used for replicating the data from a single publication. The slot, when created, will specify the output format of the changes
+- `subscription` - A subscription is created from an external system (i.e. another Postgres database) and must specify the name of the `publication`. If you do not specify a replication slot, one is automatically created
-## Recreate a publication
+## Logical replication output format
-If you're recreating a publication, it's best to do it in a transaction to ensure the operation succeeds.
+Logical replication is typically output in 2 forms, `pgoutput` and `wal2json`. The output method is how Postgres sends changes to any active replication slot.
-```sql
-begin;
- -- remove the realtime publication
- drop publication if exists publication_name;
+## Logical replication configuration
- -- re-create the publication but don't enable it for any tables
- create publication publication_name;
-commit;
-```
+When using logical replication, Postgres is then configured to keep WAL files around for longer than it needs them. If the files are removed too quickly, then your `replication slot` will become inactive and, if the database receives a large number of changes in a short time, then the `replication slot` can become lost as it was not able to keep up.
+
+In order to mitigate this, Postgres has many options and settings that can be [tweaked](/guides/database/custom-postgres-config) to manage the WAL usage effectively. Not all of these settings are user configurable as they can impact the stability of your database. For those that are, these should be considered as advanced configuration and not changed without understanding that they can cause additional disk space and resources to be used, as well as incur additional costs.
+
+| Setting | Description | User-facing | Default |
+| ---------------------------------------------------------------------------------------- | ------------------------------------------------------ | ----------- | ------- |
+| [`max_replication_slots`](https://postgresqlco.nf/doc/en/param/max_replication_slots/) | Max count of replication slots allowed | No | |
+| [`wal_keep_size`](https://postgresqlco.nf/doc/en/param/wal_keep_size/) | Minimum size of WAL files to keep for replication | No | |
+| [`max_slot_wal_keep_size`](https://postgresqlco.nf/doc/en/param/max_slot_wal_keep_size/) | Max WAL size that can be reserved by replication slots | No | |
+| [`checkpoint_timeout`](https://postgresqlco.nf/doc/en/param/checkpoint_timeout/) | Max time between WAL checkpoints | No | |
diff --git a/apps/docs/content/guides/database/replication/faq.mdx b/apps/docs/content/guides/database/replication/faq.mdx
new file mode 100644
index 00000000000..f0bdd97f465
--- /dev/null
+++ b/apps/docs/content/guides/database/replication/faq.mdx
@@ -0,0 +1,41 @@
+---
+id: 'replication-faq'
+title: 'FAQs'
+description: 'Considerations and FAQs when setting up replication'
+sidebar_label: 'FAQs'
+---
+
+# Which connection string should be used?
+
+Always use the direct connection string for logical replication.
+
+Connections through a pooler, such as Supavisor, will not work.
+
+# The tool in use does not support IPv6
+
+You can enable the [IPv4 add-on](/guides/platform/ipv4-address) for your project.
+
+# What is XMIN and should it be used?
+
+Xmin is a different form of replication from logical replication and should only be used if logical replication is not available for your database (i.e. older versions of Postgres).
+
+Xmin performs replication by checking the [xmin system column](https://www.postgresql.org/docs/current/ddl-system-columns.html) and determining if that row has already been synchronized.
+
+It does not capture deletion of data and is **not recommended**, particularly for larger databases.
+
+# Can replication be configured in the Dashboard?
+
+You can view [publications](https://supabase.com/dashboard/project/default/database/publications) in the Dashboard but all steps to configure replication must be done using the [SQL Editor](https://supabase.com/dashboard/project/default/sql/new) or a CLI tool of your choice.
+
+# How to configure database settings for replication?
+
+Yes. Using the Supabase CLI, you can [configure database settings](/guides/database/custom-postgres-config#cli-configurable-settings) to optimize them for your replication needs. These values can vary depending on the activity of your database size and activity.
+
+# What are some important configuration options?
+
+Some of the more important options to be aware of are:
+
+- `max_wal_size`
+- `max_slot_wal_keep_size`
+- `wal_keep_size`
+- `max_wal_senders`
diff --git a/apps/docs/content/guides/database/replication/monitoring-replication.mdx b/apps/docs/content/guides/database/replication/monitoring-replication.mdx
new file mode 100644
index 00000000000..a49b8a8f27a
--- /dev/null
+++ b/apps/docs/content/guides/database/replication/monitoring-replication.mdx
@@ -0,0 +1,94 @@
+---
+title: 'Monitoring replication'
+---
+
+Monitoring replication lag is important and there are 3 ways to do this:
+
+1. Dashboard - Under the [Reports](/guides/platform/reports) of the dashboard, you can view the replication lag of your project
+2. Database -
+ - pg_stat_subscription (subscriber) - if PID is null, then the subscription is not active
+ - pg_stat_subscription_stats - look here for error_count to see if there were issues applying or syncing (if yes, check the logs for why)
+ - pg_replication_slots - use this to check if the slot is active and you can also calculate the lag from here
+3. [Metrics](/guides/telemetry/metrics) - Using the prometheus endpoint for your project
+ - replication_slots_max_lag_bytes - this is the more important one
+ - pg_stat_replication_replay_lag - lag to replay WAL files from the source DB on the target DB (throttled by disk or high activity)
+ - pg_stat_replication_send_lag - lag in sending WAL files from the source DB (a high lag means that the publisher is not being asked to send new WAL files OR a network issues)
+
+## Primary
+
+### Replication status and lag
+
+The `pg_stat_replication` table shows the status of any replicas connected to the primary database.
+
+```sql
+select pid, application_name, state, sent_lsn, write_lsn, flush_lsn, replay_lsn, sync_state
+from pg_stat_replication;
+```
+
+### Replication slot status
+
+A replication slot can be in one of three states:
+
+- `active` - The slot is active and is receiving data
+- `inactive` - The slot is not active and is not receiving data
+- `lost` - The slot is lost and is not receiving data
+
+The state can be checked using the `pg_replication_slots` table:
+
+```sql
+select slot_name, active, state from pg_replication_slots;
+```
+
+### WAL size
+
+The WAL size can be checked using the `pg_ls_waldir()` function:
+
+```sql
+select * from pg_ls_waldir();
+```
+
+### Check LSN
+
+```sql
+select pg_current_wal_lsn();
+```
+
+## Subscriber
+
+### Subscription status
+
+The `pg_subscription` table shows the status of any subscriptions on a replica and the `pg_subscription_rel` table shows the status of each table within a subscription.
+
+The `srsubstate` column in `pg_subscription_rel` can be one of the following:
+
+- `i` - Initializing - The subscription is being initialized
+- `d` - Data Synchronizing - The subscription is synchronizing data for the first time (i.e. doing the initial copy)
+- `s` - Synchronized - The subscription is synchronized
+- `r` - Replicating - The subscription is replicating data
+
+```sql
+SELECT
+ sub.subname AS subscription_name,
+ relid::regclass AS table_name,
+ srel.srsubstate AS replication_state,
+ CASE srel.srsubstate
+ WHEN 'i' THEN 'Initializing'
+ WHEN 'd' THEN 'Data Synchronizing'
+ WHEN 's' THEN 'Synchronized'
+ WHEN 'r' THEN 'Replicating'
+ ELSE 'Unknown'
+ END AS state_description,
+ srel.srsyncedlsn AS last_synced_lsn
+FROM
+ pg_subscription sub
+JOIN
+ pg_subscription_rel srel ON sub.oid = srel.srsubid
+ORDER BY
+ table_name;
+```
+
+### Check LSN
+
+```sql
+select pg_last_wal_replay_lsn();
+```
diff --git a/apps/docs/content/guides/database/replication/setting-up-replication.mdx b/apps/docs/content/guides/database/replication/setting-up-replication.mdx
new file mode 100644
index 00000000000..170b54b64d4
--- /dev/null
+++ b/apps/docs/content/guides/database/replication/setting-up-replication.mdx
@@ -0,0 +1,86 @@
+---
+id: 'setting-up-replication'
+title: 'Setting up replication and CDC with Supabase'
+description: 'Performing Extract Transform Load (ETL) with Supabase'
+sidebar_label: 'Setting up replication and CDC'
+---
+
+## Prerequisites
+
+To set up replication, the following is recommended:
+
+- Instance size of XL or greater
+- [IPv4 add-on](/guides/platform/ipv4-address) enabled
+
+To create a replication slot, you will need to use the `postgres` user and follow the instructions in our [guide](/guides/database/postgres/setup-replication-external).
+
+<Admonition type="note">
+ If you are running Postgres 17 or higher, you can create a new user and grant them replication
+ permissions with the `postgres` user. For versions below 17, you will need to use the `postgres`
+ user.
+</Admonition>
+
+If you are replicating to an external system and using any of the tools below, check their documentation first and we have added additional information where the setup with Supabase can vary.
+
+<Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="estuary"
+ queryGroup="tool"
+>
+
+<TabPanel id="airbyte" label="Airbyte">
+
+Airbyte has the following [documentation](https://docs.airbyte.com/integrations/sources/postgres/) for setting up Postgres as a source, either in their cloud offering or by self-hosting.
+
+You can follow those steps with the following modifications:
+
+1. Use the `postgres` user
+2. Select `logical replication` as the replication method (`xmin` is possible, but not recommended)
+
+## Troubleshooting
+
+Airbyte has a known [issue](https://discuss.airbyte.io/t/postgres-source-replication-slot-safe-wal-size-only-reset-when-a-change-occurs/3263/7) where it does not clear WAL files on each successful sync. The recommended workaround is to have a `heartbeat` table that you write changes to once an hour.>
+
+</TabPanel>
+
+<TabPanel id="estuary" label="Estuary">
+Estuary has the following [documentation](https://docs.estuary.dev/reference/Connectors/capture-connectors/PostgreSQL/Supabase/) for setting up Postgres as a source.
+
+</TabPanel>
+
+<TabPanel id="fivetran" label="Fivetran">
+
+Fivetran has the following [documentation](https://fivetran.com/docs/connectors/databases/postgresql/setup-guide) for setting up Postgres as a source.
+
+You can follow those steps with the following modifications:
+
+1. In Step 2, choose `logical replication` as the sync mechanism
+2. In Step 3, do not create a user and use the existing `postgres` user for replication
+3. In Step 5, no need to modify any WAL settings as we have done that for you
+
+</TabPanel>
+
+<TabPanel id="materialize" label="Materialize">
+
+Materialize has the following [documentation](https://materialize.com/docs/sql/create-source/postgres/) on setting up Postgres as a source.
+
+You can follow those steps with the following modifications:
+
+1. Follow the steps in our [guide](/guides/database/postgres/setup-replication-external) to create a publication slot
+
+</TabPanel>
+
+<TabPanel id="stitch" label="Stitch">
+
+Stitch has the following [documentation](https://www.stitchdata.com/docs/integrations/databases/postgresql/v2#extract-data) on configuring Postgres as a source.
+
+You can follow those steps with the following modifications:
+
+1. Use the `postgres` user for replication
+2. Skip step 3
+
+</TabPanel>
+
+</Tabs>
diff --git a/supa-mdx-lint/Rule003Spelling.toml b/supa-mdx-lint/Rule003Spelling.toml
index e15c9961fa9..9ca43af1105 100644
--- a/supa-mdx-lint/Rule003Spelling.toml
+++ b/supa-mdx-lint/Rule003Spelling.toml
@@ -340,6 +340,7 @@ allow_list = [
"vecs",
"vs",
"watchOS",
+ "[Xx]min",
]
prefixes = ["bi", "over", "pre", "un"]