When integration tests flake, check the database they share with the worker

In September 2026 I was adding integration tests to the payment flow of a transaction platform, using a real PostgreSQL database and httptest to simulate the partner. The tests failed intermittently because the compose worker shared the database and claimed outbox rows before they could. Moving them to their own database removed that competition.

A stuck-row scan looks for rows untouched for 30 minutes. To test it without waiting half an hour, I moved the row’s timestamp back, a stopgap that bypasses the normal write path. End-to-end retries also hit replay protection within the same second; re-signing with a different timestamp let them reach the idempotency layer. The simplified examples below reproduce all three cases on OrbStack on a Mac, with PostgreSQL 16.15 and Go 1.27.4.

Google’s Testing Blog wrote about similar problems in 2016: about 1.5% of runs across its test corpus were flaky, and almost 16% of its tests showed some level of flakiness.

The test shares a database with the worker

The example worker polls for a pending outbox row, pausing for 100 ms between attempts. It uses a common queue pattern:

-- worker.sql
UPDATE outbox SET status = 'sent', updated_at = now()
WHERE id = (SELECT id FROM outbox WHERE status = 'pending'
            ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1);

The test writes a pending row, waits 0.3 seconds and claims it with the same SQL, expecting to get its own row back:

-- test.sql
INSERT INTO outbox (order_id) VALUES ('o1');
\o /dev/null
SELECT pg_sleep(0.3);
\o
UPDATE outbox SET status = 'sent', updated_at = now()
WHERE id = (SELECT id FROM outbox WHERE status = 'pending'
            ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1)
RETURNING 'test claimed ' || order_id AS result;
SELECT order_id, status FROM outbox;

The same test runs once against app, which the worker polls, and once against app_test, which only the test uses:

== test against the shared database (app)
 result 
--------
(0 rows)

 order_id | status 
----------+--------
 o1       | sent
(1 row)

== test against its own database (app_test)
     result      
-----------------
 test claimed o1
(1 row)

 order_id | status 
----------+--------
 o1       | sent
(1 row)

Against the shared database, the test claims nothing and the failed assertion looks as if the code never wrote the row. The example worker only changes the status; the real worker also calls the partner’s callback. The balances the test sees therefore include work from both processes, making the cause harder to trace.

SKIP LOCKED makes a consumer pass over rows someone else has locked, so no row is held for the test. The PostgreSQL documentation says it gives an inconsistent view of the data, unsuitable for general work but useful for multiple consumers on a queue-like table. The worker and the test compete for the same pending rows, so the result depends on which claims the row first.

In the project the integration tests now use their own rgs_test database, set through PG_TEST_DSN, which the compose worker doesn’t connect to. Martin Fowler’s article on non-deterministic tests stresses a known starting state and isolation between tests. A separate database excludes the worker, but the tests still need isolation from one another.

A scan with a 30-minute threshold

The worker also scans for rows stuck in in_flight for more than 30 minutes. Two possible ways to test it are to wait or to write a timestamp calculated as “30 minutes ago” on the test host. The latter wasn’t reliable in the project: the host and database container don’t necessarily agree on the time, and the scan uses the database’s now().

Inside a transaction, now() returns the transaction’s start time and stays fixed however long the transaction sleeps:

-- clock.sql
TRUNCATE outbox;
INSERT INTO outbox (order_id, status) VALUES ('o2', 'in_flight');

-- (a) waiting inside one transaction: now() does not move.
BEGIN;
\o /dev/null
SELECT pg_sleep(2);
\o
SELECT now() - updated_at < interval '1 second' AS now_age_under_1s,
       clock_timestamp() - updated_at >= interval '2 seconds' AS clock_age_2s
FROM outbox;
COMMIT;

-- (b) moving the data back instead of waiting.
UPDATE outbox SET updated_at = updated_at - interval '31 minutes';
SELECT order_id AS stuck FROM outbox
WHERE status = 'in_flight' AND updated_at < now() - interval '30 minutes';
 now_age_under_1s | clock_age_2s 
------------------+--------------
 t                | t
(1 row)

 stuck 
-------
 o2
(1 row)

After a two-second sleep, the age measured with now() was still under a second, while clock_timestamp() returned the time of the call. A test that runs inside one transaction and rolls back at the end needs an old enough timestamp in the data; waiting cannot move now().

The project used approach (b), moving the timestamp back with an UPDATE. The example subtracts 31 minutes to cross the threshold while the scan still uses the database’s now(). This is a stopgap: it bypasses the normal write path, so a fault in that path could go undetected.

testing/synctest became generally available in Go 1.25. Within a bubble, the time package uses a fake clock that can advance only when every goroutine is durably blocked, and network I/O doesn’t count. A SQL scan using the database’s now() is outside its control, so the test has to supply the time through the data or a parameter.

A same-second retry hits replay protection first

One step of the end-to-end suite resends the same credit and expects the idempotency layer to return the original response. Some runs got DUPLICATE_REQUEST instead.

The partner API uses HMAC signatures and timestamps with one-second resolution. Its nonce key is nonce:<api_key>:<path>:<signature>. Requests using the same credentials, method, path and body within the same second produce the same signature, so the second request counts as a replay:

key := "nonce:" + apiKey + ":" + path + ":" + sig
v.mu.Lock()
defer v.mu.Unlock()
if v.seen[key] {
	return "DUPLICATE_REQUEST"
}
v.seen[key] = true
return "OK (passed to idempotency layer)"
first request            ts=1793980800 path=/wallet/credit -> OK (passed to idempotency layer)
retry, same second       ts=1793980800 path=/wallet/credit -> DUPLICATE_REQUEST
retry, next second       ts=1793980801 path=/wallet/credit -> OK (passed to idempotency layer)
same second, other path  ts=1793980800 path=/wallet/refund -> OK (passed to idempotency layer)

The last line passes because a different path changes both the key and the signature. To reach the idempotency layer, the end-to-end retry needs a fresh signature: wait a second before re-signing, or use another timestamp within the validity window, while keeping the business idempotency key unchanged. Reusing the signature fails the replay check before reaching that layer. The example only implements replay checking; it has no idempotency layer or timestamp validity check. The fields to sign are covered in “What an HMAC Request Signature Should Cover: Method, Path, Query and the Raw Body”.

Notes

  • A test and worker using FOR UPDATE SKIP LOCKED on the same outbox compete for rows. The project separated them with a test database set by PG_TEST_DSN.
  • now() is the transaction start time and doesn’t move however long the transaction waits; the stuck-scan example moves the row back 31 minutes, a stopgap that bypasses the normal write path.
  • testing/synctest fakes the clock on the Go side only and can’t reach the database’s now().
  • A resend with the same credentials and signature is stopped by the nonce check; the end-to-end suite needs a different timestamp inside the window and the same business idempotency key to reach the idempotency layer.

Further reading

Ideas and technical judgement by Sheng; drafted with Claude · Examples run in OrbStack containers on a Mac (PostgreSQL 16.15, Go 1.27.4).