Stream PostgreSQL Row Changes Without Dual Writes
In this article
- Background: Why Dual Writes Are a Problem
- How Logical Replication Works
- Setting Up Logical Replication
- Choosing the Right Tool for Your Use Case
- Common Pitfalls and How to Avoid Them
- Comparison: Logical Replication vs. Other Methods
- Costs and Operational Considerations
- Safety and Reliability
- Frequently Asked Questions
Yes, you can stream PostgreSQL row changes to other systems without adding application dual-write logic. The standard approach uses PostgreSQL's logical replication feature, which decodes changes from the write-ahead log (WAL) and sends them to a subscriber, such as another database, a message queue, or a data warehouse. This article explains how logical replication works, how to set it up, and what to watch out for.
Background: Why Dual Writes Are a Problem
Dual writes happen when your application updates the database and then separately sends the same change to another system (e.g., a search index, cache, or analytics store). This pattern is fragile because the two operations are not atomic: if the second write fails, the systems become inconsistent. Retry logic adds complexity, and ordering issues can arise under concurrency. Logical replication solves this by making the database itself the source of truth for change events, so your application only writes once.
How Logical Replication Works
Logical replication is built into PostgreSQL (since version 10). It works by reading the WAL and decoding changes into a logical format (by default, the pgoutput plugin). The publisher sends these changes to a subscriber, which applies them. Unlike physical replication, which copies raw blocks, logical replication sends row-level changes, so the subscriber can be a different PostgreSQL version, a different database, or even a non-PostgreSQL system if you use a decoder like wal2json or decoderbufs.
Key components:
- Publication: Defines which tables (or schemas) to publish. You can choose row filters and column lists.
- Subscription: Connects to the publisher and receives changes. It can be on the same server or a remote one.
- Replication slot: Tracks the WAL position. It ensures the publisher retains WAL segments until the subscriber acknowledges them.
When a row is inserted, updated, or deleted, the change is written to the WAL. The logical decoding plugin converts it into a structured message (e.g., JSON) and sends it to the subscriber. The subscriber applies the change, and optionally, you can have a trigger or a custom program that processes the change further.
Setting Up Logical Replication
To use logical replication, you need to configure both the publisher and the subscriber. Here are the essential steps:
- Set
wal_level = logicalinpostgresql.confand restart PostgreSQL. - Create a publication on the source database:
CREATE PUBLICATION mypub FOR TABLE mytable; - Create a subscription on the target database:
CREATE SUBSCRIPTION mysub CONNECTION 'host=... dbname=...' PUBLICATION mypub; - Ensure the target table schema matches (or use a custom apply function).
Once set up, changes flow automatically. You can monitor the status via pg_stat_subscription and pg_replication_slots.
Choosing the Right Tool for Your Use Case
Logical replication is excellent for replicating whole tables to another PostgreSQL instance. But for streaming to Kafka, Elasticsearch, or a data lake, you often need a separate tool that consumes the changes and forwards them. Popular options include:
- Debezium: An open-source CDC platform that uses logical decoding and emits change events in JSON or Avro. It integrates with Kafka, but can also stream to other systems.
- pgoutput: The built-in plugin, used by PostgreSQL subscriptions. If you want to write your own consumer, you can use the
pgoutputprotocol directly. - wal2json: A plugin that outputs changes as JSON, useful for lightweight integrations.
- Custom scripts: You can write a program that connects to the replication protocol (using libraries like
pgjdbcorpsycopg2) and processes changes.
Your choice depends on your target system, the volume of changes, and whether you need exactly-once semantics or can tolerate at-least-once.
Common Pitfalls and How to Avoid Them
Logical replication is powerful, but it has several gotchas:
- Schema changes: DDL like
ALTER TABLEis not replicated automatically. You must apply schema changes manually to the subscriber and ensure the publication still matches. - Primary keys: Logical replication requires a primary key or a replica identity (unique index) to identify rows for updates/deletes. Without it, updates will fail.
- Sequence values: Sequences are not synchronized. If you insert rows on both sides, you may get conflicts. Use
setvalor avoid writing to the subscriber. - Replication slot lag: If the subscriber is down for a long time, the WAL grows and can fill the disk. Monitor slot lag and set
max_slot_wal_keep_sizeappropriately. - Data types: Some types (e.g.,
jsonb, arrays) are supported, but custom types may not be. Test before relying on them.
For example, if you add a column to the source table, the subscriber will not know about it until you add it there too, and the publication may need to be refreshed (ALTER PUBLICATION ... ADD TABLE or REFRESH PUBLICATION).
Comparison: Logical Replication vs. Other Methods
Before choosing logical replication, consider alternatives:
- Trigger-based auditing: You can write triggers that insert change records into an audit table. This is simple but adds overhead to every write and can be hard to scale.
- Application dual write: As discussed, this is fragile and not recommended.
- Physical replication: Copies the entire database, but you cannot selectively stream tables or transform data.
- Polling: Your application periodically queries for changes (e.g., using
updated_attimestamps). This is simple but introduces latency and misses deletes unless you use soft deletes.
Logical replication is the only method that gives you real-time, row-level changes without modifying your application code, and it works across different PostgreSQL versions.
Costs and Operational Considerations
Running logical replication has some costs:
- WAL overhead: Logical decoding requires retaining WAL segments until the subscriber consumes them. This can increase disk usage.
- CPU usage: Decoding WAL consumes CPU on the publisher, especially with high write rates.
- Network bandwidth: Changes are sent over the network, so ensure sufficient bandwidth.
- Maintenance: You must monitor replication lag, handle schema changes, and manage slots.
For most workloads, these costs are acceptable. If you have extremely high write throughput, you may need to tune the decoder or use batching.
Safety and Reliability
Logical replication is safe in that it does not affect the source database's normal operation. However, you must be careful about:
- Data consistency: The subscriber may lag, so it does not always reflect the latest state. For real-time analytics, this is usually fine.
- Exactly-once vs. at-least-once: The replication protocol is at-least-once. If your consumer crashes after receiving a change but before processing it, you may get duplicates. Design your consumer to be idempotent.
- Security: Replication connections require a role with
REPLICATIONprivileges. Use SSL and strong passwords.
If you need to stream changes to a system that cannot be a PostgreSQL subscriber (like Kafka), you must use a tool like Debezium, which handles the decoding and delivery. In that case, you are responsible for ensuring the tool is configured correctly and for monitoring its health.
Frequently Asked Questions
Can I stream changes without a primary key?
No, logical replication requires a primary key or a unique index (replica identity) to identify rows for updates and deletes. If a table lacks one, you can set REPLICA IDENTITY FULL, but that sends the entire row for every change, which is inefficient.
Does logical replication work with PostgreSQL on cloud services?
Most managed PostgreSQL services (like AWS RDS, Google Cloud SQL, Azure Database) support logical replication, but you may need to enable it via parameter groups. Check your provider's documentation for specifics.
What happens if the subscriber is down?
The publisher retains WAL data in the replication slot. When the subscriber comes back, it resumes from where it left off. If the slot is dropped or the WAL is removed, you may need to reinitialize the subscription.
Can I filter which rows are replicated?
Yes, publications support row filters (e.g., WHERE clauses) and column lists. This is useful if you only want to stream certain data.
Is logical replication the same as CDC?
Change Data Capture (CDC) is a broader concept. Logical replication is a form of CDC, but CDC tools like Debezium add features like schema history and integration with message queues. Logical replication is the underlying mechanism.
Can I use logical replication to migrate between PostgreSQL versions?
Yes, logical replication works across different major versions, making it a good tool for zero-downtime upgrades. However, you must ensure the schema is compatible.