Testcontainers for PostgreSQL Replication Slots in Integration Tests
PostgreSQL replication slots are easy to misunderstand: the slot lives on the publisher, while the subscriber maintains a connection and refresh state. A mocked publisher can prove that application code issues a command, but it cannot expose a blocked WAL sender, an exhausted slot limit, or a schema mismatch across two databases.
Testcontainers gives each integration test an ephemeral PostgreSQL server managed through Docker. Starting a publisher and subscriber as separate containers makes topology, networking and cleanup repeatable, which is valuable when logical replication supports a deployment pipeline or an asynchronous data workflow.
The hard part is not starting PostgreSQL; it is reproducing the lifecycle around it. Tests must configure logical WAL, create publications and subscriptions, wait for the initial copy, then prove that subsequent changes reach the subscriber without leaving inactive slots behind.
A practical fixture therefore needs more than a JDBC URL. It needs container networking, deterministic readiness checks, version-aware SQL and assertions based on observable database state rather than hopeful sleeps. That combination supports a repeatable path from setup to teardown.
Why Replication Slots Need Real Containers
| Approach | Replication fidelity | Isolation | Startup cost | Best fit |
|---|---|---|---|---|
| Replication client mock | Low | High | Very low | Command and contract tests |
| Host-installed PostgreSQL | Medium | Low | Low | Existing developer setup |
| Publisher container only | Medium | High | Medium | Slot and publication behaviour |
| Publisher and subscriber containers | High | High | Higher | End-to-end logical replication |
A publisher-only container is useful when the test needs to verify publication metadata, slot creation or WAL retention. It cannot exercise the subscriber worker, initial table synchronisation or change delivery. Those behaviours live at the boundary between two PostgreSQL instances and deserve a two-node fixture.
Paired containers also reveal environmental mistakes that a single database hides. Network aliases, password authentication, PostgreSQL configuration and server versions all affect replication. The cost is extra startup time and memory, so choose the paired topology only when the test genuinely depends on cross-server behaviour.
Modelling the Publisher and Subscriber
Put both containers on a private Testcontainers network and give them stable aliases. The subscriber’s server-side worker must connect to the publisher by its container alias and internal PostgreSQL port; a mapped host port is intended for the test process, not for connections originating inside another container.
private static PostgreSQLContainer<?> database(Network network, String alias) {
return new PostgreSQLContainer<>("postgres:16-alpine")
.withNetwork(network)
.withNetworkAliases(alias)
.withCommand("postgres",
"-c", "wal_level=logical",
"-c", "max_replication_slots=10",
"-c", "max_wal_senders=10");
}
Network network = Network.newNetwork();
PostgreSQLContainer<?> publisher = database(network, "publisher");
PostgreSQLContainer<?> subscriber = database(network, "subscriber");
Keep the major PostgreSQL versions aligned unless the test explicitly targets cross-version replication. Create the subscriber schema before starting its subscription because logical replication copies rows into an existing table; it does not create application tables or run your migration system. Role privileges should permit the subscription connection to read the published relation.
The test process connects through each container’s randomly mapped JDBC port. The replication worker uses a different route: publisher:5432 on the shared network. Confusing these two addresses is a common cause of tests that pass locally but fail on CI workers with different networking rules.
Building a Disposable PostgreSQL Fixture
Construct the containers in a JUnit 5 fixture, Spock specification or equivalent lifecycle object, then expose each mapped JDBC URL through your application’s configuration. Testcontainers chooses random host ports, so parallel CI jobs avoid the fixed-port clashes common in hand-built Docker Compose setups. Use the org.testcontainers:postgresql module with the JUnit Jupiter module, and add Awaitility for asynchronous polling.
@DynamicPropertySource
static void datasource(DynamicPropertyRegistry registry) {
registry.add("publisher.url", publisher::getJdbcUrl);
registry.add("subscriber.url", subscriber::getJdbcUrl);
}
Container readiness means more than an open socket. After startup, query SHOW wal_level and confirm it returns logical; also check max_replication_slots and max_wal_senders. In Groovy Spock, the same pattern works through static container fields and @Shared, but cleanup should still stop both databases and close the dedicated network after the suite.
A Linux CI worker needs access to a Docker daemon, whether it is a rootless service, a mounted host socket or Docker-in-Docker. Do not make a developer’s Docker Desktop configuration part of the contract. The fixture should depend only on the Docker API and ordinary container networking.
Creating Replication Objects
Create the table and publication in the publisher. A publication defines which changes enter logical replication, while the subscription on the subscriber instructs PostgreSQL to consume that publication. Apply these statements to separate databases:
-- Publisher
CREATE TABLE events (id bigint PRIMARY KEY, payload text NOT NULL);
CREATE PUBLICATION event_pub FOR TABLE events;
-- Subscriber
CREATE TABLE events (id bigint PRIMARY KEY, payload text NOT NULL);
CREATE SUBSCRIPTION event_sub
CONNECTION 'host=publisher port=5432 dbname=test user=test password=test'
PUBLICATION event_pub
WITH (copy_data = true, create_slot = true, slot_name = 'event_sub');
With create_slot = true, PostgreSQL creates event_sub on the publisher. This is why checking only the subscriber database for a slot gives a false negative: pg_replication_slots is a publisher-side catalog. Slot names must be unique within that publisher, which matters when several tests share one server.
The connection string is stored in PostgreSQL metadata, so do not place a production credential in a fixture. Use a dedicated test role with the privileges required by your PostgreSQL version, including replication access where required, and restrict it to published test data. For a WAL-only scenario, set copy_data = false and arrange any prerequisite subscriber rows separately.
Dropping the subscription normally removes its remote slot. If setup fails midway, explicit slot cleanup or a fresh container prevents abandoned logical slots from retaining WAL and filling the publisher’s data directory.
Waiting for Asynchronous Replication
Logical replication is asynchronous. CREATE SUBSCRIPTION can return while the initial table copy is still running, and a row inserted immediately afterwards may be copied, streamed or observed in a different order depending on timing. First wait until pg_subscription_rel.srsubstate is r, meaning the table is ready, then insert the test row.
Use Awaitility to poll the subscriber rather than inserting a fixed sleep. The deadline should allow for a loaded CI runner while still failing promptly when the worker cannot connect:
await().atMost(Duration.ofSeconds(20)).untilAsserted(() ->
assertThat(subscriber.queryForObject(
"select count(*) from events where id = 42", Integer.class))
.isEqualTo(1));
Also assert publisher-side state. Query pg_replication_slots for the expected plugin, slot_type, active flag and a non-null confirmed_flush_lsn. On the subscriber, pg_stat_subscription shows the received and latest end LSN. Comparing progress across both nodes is stronger than checking that a row happened to arrive, because a previous initial copy could otherwise satisfy a weak assertion.
Running Reliably Across Australian Teams
Australian development teams are often spread across Sydney, Melbourne, Brisbane and Perth. Perth runs at UTC+8, Brisbane at UTC+10, and Sydney and Melbourne change between UTC+10 and UTC+11 under daylight-saving rules. Store timestamps in UTC, include the zone in logs and avoid assertions that accidentally depend on a local evening crossing midnight.
The local cloud market gives CI teams choices such as AWS regions in Sydney and Melbourne, Microsoft Azure Australia East and Australia Southeast, and Google Cloud locations in Sydney and Melbourne. Health, financial and government workloads may also carry Australian data-residency expectations, so keep test data synthetic and confirm whether container logs, build artefacts or temporary databases leave the country.
Docker Desktop’s commercial licensing has prompted many Australian organisations to standardise on Docker Engine in Linux CI. A portable fixture works with either the Engine API or Desktop, but it should never require a GUI, a fixed daemon socket or privileged networking. Running the pair as rootless containers is a useful portability check before a release reaches an enterprise runner.
Australian teams often use “no worries” or “she’ll be right” to keep stand-ups relaxed. Automation should be stricter: a timed-out replication wait is a defect signal, not something to paper over with another retry. Use an en_AU locale for display formatting, keep database dates unambiguous with ISO 8601, and configure the CI matrix around UTC rather than each engineer’s workstation clock.
Operational Trade-offs and Reliable Cleanup
Two PostgreSQL containers cost more than one because Testcontainers must download or reuse images, start operating-system processes and initialise separate data directories. Start the pair only for tests that validate replication. A test focused on publication SQL can use one publisher, while unit tests of the change-data-capture adapter should remain a mock.
Long-lived shared containers can reduce runtime, but they also retain slots, publications and WAL. Reuse is safer for read-only scenarios than for mutation-heavy replication tests. If a publisher is shared across parallel tests, allocate a unique publication and slot per test and remove both during teardown; otherwise one test can invalidate another’s LSN expectations.
The most common failures are wal_level set too low, exhausted slot or sender limits, an incorrect internal hostname, authentication rejection, incompatible schemas and assertions that run before replication catches up. Pin image versions, expose explicit health checks, make timeouts diagnostic and verify cleanup after failures as well as after successful tests.
The durable pattern is to treat logical replication as a stateful, asynchronous system: use a disposable publisher and subscriber on a private network, assert on PostgreSQL’s catalogs and LSN progress, and guarantee that every test leaves no slot or retained WAL behind.