Stop Testing Banking Data Layers Against H2
Testcontainers, Flyway and PostgreSQL migration tests
Testcontainers, Flyway and PostgreSQL migration tests
Many Java banking services still run their repository and integration tests against H2, an in-memory database that starts in milliseconds and needs no infrastructure. It feels like a reasonable trade: fast feedback in exchange for a database that is "close enough" to PostgreSQL, especially with H2's PostgreSQL compatibility mode switched on. The trouble is that "close enough" is precisely where data-layer bugs live. H2 emulates PostgreSQL's syntax in many places, but not its behaviour. Locking, isolation, collation, time zones, constraint semantics and the features a banking schema actually relies on all behave differently, or don't exist at all.
The result is a familiar pattern: a service passes hundreds of green tests and then fails on its first deployment because a migration used PostgreSQL syntax that H2 never saw. Or the schema under test wasn't even the real schema. Or a query that "worked" in tests returns accounts in a different order, deadlocks under load, or locks a table with forty million rows for several minutes during a release.
This article covers two changes that remove that gap. The first is running data-layer tests against real PostgreSQL with Testcontainers, applying the same Flyway migrations that production uses. The second goes beyond functional correctness: testing the migrations themselves for the one failure H2 can never show, a schema change that locks a busy table in production.
The differences that matter aren't obscure edge cases. They are features banking backends depend on every day:
Locking and isolation. Serialisation failures under SERIALIZABLE, SELECT … FOR UPDATE SKIP LOCKED work queues, advisory locks and real deadlock behaviour. These are exactly the mechanisms that prevent double-spend on a ledger, and H2's concurrency model is different enough that tests passing there prove little.
Upserts and constraints. INSERT … ON CONFLICT … DO UPDATE for idempotency keys, deferrable constraints, exclusion constraints and partial unique indexes such as "one active mandate per account".
Security features. Row-level security policies and security_invoker views don't exist in H2, so tests can't verify that a branch-scoped role really sees only its own branch.
Types and text. jsonb and its indexes, numeric precision and rounding at the edges, timestamptz semantics, and ICU collations that decide how Romanian, German or Polish names sort and compare.
The migrations themselves. CREATE INDEX CONCURRENTLY, DO blocks, PL/pgSQL functions and triggers either fail on H2 or need a second, H2-specific migration path.
That last point is the most damaging. Teams that hit H2 incompatibilities in their Flyway scripts usually respond in one of two ways. They maintain a separate set of test migrations, or they let Hibernate generate the test schema with ddl-auto=create. Either way, the schema under test is no longer the schema in production. Every test then verifies code against a database that doesn't exist anywhere else.
Testcontainers starts a disposable PostgreSQL in Docker for the duration of a test run, and Spring Boot's @ServiceConnection wires it in without any property plumbing. With Testcontainers 2.x, as used with Spring Boot 4, the PostgreSQL container class lives in org.testcontainers.postgresql:
1 @TestConfiguration(proxyBeanMethods = false)
2 class PostgresTestConfig {
3
4 @Bean
5 @ServiceConnection
6 PostgreSQLContainer postgres() {
7 return new PostgreSQLContainer("postgres:17.6") // pin production's version
8 .withEnv("POSTGRES_INITDB_ARGS",
9 "--locale-provider=icu --icu-locale=ro-RO"); // and its collation
10 }
11 }
12
13 @SpringBootTest
14 @Import(PostgresTestConfig.class)
15 class PaymentRepositoryIT {
16 // Flyway runs the production migrations on startup; tests run against that schema.
17 }
Three details make the difference between "uses PostgreSQL" and "tests what production does":
Pin the image to production's major version, and ideally the same minor version. Planner behaviour, locking optimisations and available syntax change between releases. Testing on 17 when production runs 15 can hide a migration that only works on the newer version.
Match collation and relevant configuration. If production uses an ICU locale, the test database should too, otherwise ordering and case-insensitive comparisons of customer names will differ silently. Apply the same default_transaction_isolation, extensions and any settings your queries rely on.
Use Flyway, never ddl-auto. Spring Boot runs Flyway automatically when it's on the classpath, so the test schema is built by exactly the same scripts, in the same order, as production. A migration that doesn't run on PostgreSQL fails in the first test run, on the developer's machine, not in the release pipeline.
The usual objection is speed, and it's mostly a configuration problem. Start one container per test JVM rather than per test class, either through a shared configuration like the one above or a static singleton. Run Flyway once. Isolate tests with transactions that roll back, or with targeted truncation, rather than new databases. With that setup, a typical banking service's data-layer suite adds seconds, not minutes. Tests that don't touch SQL at all shouldn't need a database: mock the repository and keep them as plain unit tests.
Even a perfect functional test suite misses one class of production incident entirely. A migration can be functionally correct and still take a lock that stops payments. In PostgreSQL, the operations to watch on large, busy tables include:
Table rewrites. Since PostgreSQL 11, adding a column with a constant default is a catalog-only change. A volatile default such as now() or gen_random_uuid() still rewrites every row, as do most ALTER COLUMN … TYPE changes. A rewrite holds an ACCESS EXCLUSIVE lock for its whole duration, which blocks reads as well as writes.
Index builds without CONCURRENTLY. A plain CREATE INDEX blocks writes to the table until the index is built.
Validating constraints. Adding a foreign key or check constraint validates every existing row under a strong lock, unless it's added NOT VALID and validated separately.
Lock queues. Even a "quick" ALTER TABLE needs ACCESS EXCLUSIVE briefly. If a long-running report holds a lock on the table, the migration waits, and every new query on that table queues behind the migration. A one-millisecond DDL can stall a payment table for as long as the slowest open transaction.
None of this shows up in a test that runs migrations against an empty schema. It shows up at 02:00 during a release window, when the table has forty million rows and the overnight batch is still running.
The PostgreSQL container makes these failures testable before they reach production. Three checks cover most of the risk.
When PostgreSQL rewrites a table, it writes the data to a new file on disk, so the table's file identifier changes. That gives a precise, cheap test: migrate to the version before the change, seed realistic volume, record the identifier, apply the new migration and compare.
1 @Test
2 void v42DoesNotRewriteThePaymentTable() {
3 migrateTo("41");
4 jdbc.execute("""
5 INSERT INTO payment (id, account_id, amount, currency, status, created_at)
6 SELECT gen_random_uuid(), (random() * 50000)::int, round((random() * 5000)::numeric, 2),
7 'EUR', 'SETTLED', now() - (g || ' minutes')::interval
8 FROM generate_series(1, 2000000) AS g
9 """);
10 Long before = jdbc.queryForObject("SELECT pg_relation_filenode('payment')", Long.class);
11
12 migrateTo("42");
13
14 Long after = jdbc.queryForObject("SELECT pg_relation_filenode('payment')", Long.class);
15 assertThat(after)
16 .as("V42 rewrites the payment table under ACCESS EXCLUSIVE")
17 .isEqualTo(before);
18 }
19
20 private void migrateTo(String version) {
21 Flyway.configure().dataSource(dataSource).target(version).load().migrate();
22 }
The seeded volume serves two purposes. It makes any rewrite measurably slow, so duration can be logged and trended. It also exercises the migration against data shaped like production, which catches backfills that time out or constraints that existing rows violate.
The defence against the lock-queue problem is a lock_timeout on every migration, so a DDL that can't get its lock within a few seconds fails and can be retried, instead of freezing the table. Flyway SQL callbacks make this a single file applied before each migration:
1 -- src/main/resources/db/migration/beforeEachMigrate.sql
2 SET lock_timeout = '3s';
A test can then show that the guard works, by holding a lock in a second connection the way a long-running report would:
1 @Test
2 void migrationsGiveUpQuicklyWhenATableIsBusy() throws Exception {
3 migrateTo("41");
4 try (Connection report = dataSource.getConnection()) {
5 report.setAutoCommit(false);
6 report.createStatement().execute("SELECT count(*) FROM payment"); // holds a lock until rollback
7
8 assertThatThrownBy(() -> migrateTo("42"))
9 .rootCause().hasMessageContaining("lock timeout");
10
11 report.rollback();
12 }
13 }
Some risks are easiest to catch statically: CREATE INDEX without CONCURRENTLY on a table on your "hot tables" list, a foreign key added without NOT VALID, a column type change on a large table. Open-source PostgreSQL migration linters such as Squawk run in CI on every new Flyway script and flag these patterns with an explanation and a safer alternative. One practical detail: CREATE INDEX CONCURRENTLY can't run inside a transaction block, so put it in its own migration and configure Flyway to run that script outside a transaction. Then the safe pattern is also the one that runs cleanly.
Together, these turn "we'll be careful with migrations" into an enforced rule. A rewrite on a hot table fails the build. A migration without a lock timeout fails the build. A risky DDL pattern is flagged in the pull request, before review.
Moving an existing service off H2 is incremental work:
Add the PostgreSQL container alongside H2 and run the existing repository tests against both. The tests that fail only on PostgreSQL are the first findings, and often the most valuable.
Delete test-only migrations and ddl-auto so Flyway builds the test schema from production scripts. Fix any script that only ever ran on H2.
Add the migration safety checks: the beforeEachMigrate callback, the rewrite test for the busiest tables, and the linter in CI.
Remove H2 from the build once the PostgreSQL suite is stable and fast enough, so nobody reintroduces it by accident.
H2 made sense when spinning up a real database for every build was slow and awkward. That's no longer true. A pinned PostgreSQL container, built by the same Flyway scripts as production, gives tests that fail for the same reasons production would. Migration tests with realistic volume, rewrite detection and lock timeouts catch the release-night failures that no in-memory database can reproduce.
From a testing perspective, the principle is simple: test the data layer on the database you run, with the schema you deploy, at a volume that resembles reality. For a banking service, where the data layer holds balances, mandates and payment state, anything less means testing a system nobody is going to run.