Skip to content

Start again on another port when a detected port is taken before the server binds it - #178

Open
zenios wants to merge 3 commits into
zonkyio:masterfrom
zenios:retry-detected-port-taken
Open

zenios wants to merge 3 commits into
zonkyio:masterfrom
zenios:retry-detected-port-taken

Conversation

@zenios

@zenios zenios commented Oct 31, 2026 •

Copy link
Copy Markdown

The problem

With no port set, Builder.start() picks a free port with new ServerSocket(0), closes it, runs initdb and only then starts the server. Anything can take the port in that window, which lasts as long as initdb. When tests run in parallel, another test's socket sometimes does. The server then logs:

LOG:  could not bind IPv4 address "127.0.0.1": Address already in use
FATAL:  could not create any TCP/IP sockets

and start() fails with Gave up waiting for server to start after ..., once the whole startup wait has passed. Nothing is wrong with the test, and it passes when run again.

When the port is taken by another embedded PostgreSQL, for example another test JVM's, it is worse: this instance's
postmaster still cannot bind it and exits, but the other server answers the readiness check (SELECT 1 on the port).
start() then succeeds and returns an instance whose connections reach the other cluster. Each test runs against the
other's database, and closing this instance does not stop the server it was using; a test that fails its setup and
closes its instance leaves the other test's connections terminated as well.

The change

  • Builder.start() tries up to 3 times, with a new port and a new temporary directory each time, if the failed port really is taken.
  • It does not retry when the caller set the port or the data directory, or when the port is still free, as that failure has another cause and would only wait again.
  • The readiness check also requires the server to serve this instance's data directory (SHOW data_directory). Another
    instance's server fails the attempt at once instead of being adopted, and the port being taken starts it again on
    another.
  • A failed start now closes the instance: it releases the lock and removes the data directory. Without this, each failed attempt also left its lock open and its directory behind, and a shutdown hook that tries to stop a server that never started.

Tests

  • testDetectedPortTakenBeforeTheServerBindsItStartsOnAnother holds the first detected port and expects a working server on another. A package-private nextPort() makes the clash deterministic.
  • testDetectedPortServedByAnotherInstanceStartsOnAnotherAndLeavesItRunning hands the first attempt a running
    instance's port and expects a working server on another, with its own data directory, and the other instance still
    serving. Without the data directory check it fails: the new instance reports the other's port.
  • testAPortAskedForAndTakenFailsWithoutAnotherAttempt keeps today's behaviour when the caller chose the port.

Known limits

  • A failed attempt still waits out pgStartupWait before retrying, as today. The server has already exited by then, so failing fast could be a separate change.
  • Closing a failed instance logs Could not stop postmaster at ERROR, as pg_ctl stop finds nothing running.

…server binds it

A detected port is free only until the server binds it, after initdb, and something else can take it in between. Builder.start() now tries up to 3 times, with a new port and temporary directory, when the failed port really is taken. A port or data directory set by the caller, or a failure with the port still free, fails as before. A failed start now closes the instance, releasing its lock and removing its data directory.
… the detected one

When another instance took the detected port first, this instance's postmaster cannot bind it and exits, but the
other instance's server answers the readiness check: start() returned an instance whose connections reached another
cluster, and closing it would not stop that server. The readiness check now also requires the server to serve this
instance's data directory; one that does not fails the attempt at once, and the port being taken starts it again on
another, as when anything else holds the port.
@tomix26

tomix26 commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator

Hi, thanks for the PR! The problem is real and I'd like to merge a fix for it. I think the retry can be simpler and faster, though. Here are my suggestions.

1. Retry only the server start

Right now each retry creates a new EmbeddedPostgres, so initdb runs again. It also creates a new temp directory, a new lock and a new shutdown hook. That's not needed: initdb does not use the port. The port is only used by pg_ctl start.

So I'd move the retry loop into startPostmaster():

  • If the user did not set a port, choose a free port there, just before pg_ctl start. This also makes the time window for the port clash much shorter.
  • If the start fails, stop pg_ctl, choose a new port and start again on the same data directory.
  • Register the shutdown hook only once, after the loop.

2. Stop waiting when pg_ctl has already failed

When the port is taken, the server stops within milliseconds. pg_ctl -w start then exits with an error code. But waitForServerStartup() doesn't check this. It only tries to connect to the database, so it keeps trying until pgStartupWait is over (10 seconds by default).

You can pass the pg_ctl process to waitForServerStartup() and check it in the loop, something like:

if (!pgCtl.isAlive() && pgCtl.exitValue() != 0) {
    throw new IOException("pg_ctl failed with exit code " + pgCtl.exitValue(), lastCause);
}

Then a failed attempt takes milliseconds, not 10 seconds.

3. Remove isTaken()

With 1 and 2, a retry is cheap. So we don't need to find out why the start failed. If the user did not set the port, we can simply retry on any failure. isTaken() is not reliable anyway:

  • it runs after the failure, so the port may already be free again;
  • it binds a different address than Postgres does, so on Windows it can say a taken port is free.

4. Small things

  • The data_directory check can be done in the same query as SELECT 1, so we don't open a second connection. For example:
    SELECT 1, current_setting('data_directory')
  • The cleanup in the constructor should catch RuntimeException too, not only IOException.
  • Please move START_ATTEMPTS up to the other constants, and the dataDirectory() helper to the end of the test class.

Tests

The three test cases look good, please keep them. With point 2 they should not need the short pgStartupWait anymore. It would be nice to also check that a failed attempt is fast, not 10 seconds.

Thanks again, and let me know if anything is unclear!

…ting once pg_ctl failed

Per review: the retry moves from Builder.start() into startPostmaster(). When no port is set, a free port is chosen
just before pg_ctl start; a failed start is stopped and started again on another port, on the same data directory, up
to 3 times, so initdb, the temporary directory and the lock are not redone, and the shutdown hook is registered once,
after the loop. A port set by the caller fails as before, without another attempt.

waitForServerStartup() takes the pg_ctl process and fails as soon as pg_ctl failed, so a failed attempt takes
milliseconds, not pgStartupWait. It connects only once pg_ctl -w start has exited: before that a connection can reach
whatever else listens on the port and wait seconds for an answer. With retries this cheap, any failure is retried and
isTaken() is gone.

The data_directory check is part of the readiness query, the constructor cleans up on a RuntimeException too, and the
tests no longer shorten pgStartupWait and check that a failed attempt is fast.
@zenios

zenios commented Nov 23, 2026

Copy link
Copy Markdown
Author

Thanks for the review! All done in 26fb365:

  1. The retry is now in startPostmaster(). Without a set port, a free port is chosen just before pg_ctl start; a failed start is stopped and started again on a new port, on the same data directory (no new initdb, temp directory or lock). The shutdown hook is registered once, after the loop. A port set by the user fails as before, without a retry.
  2. waitForServerStartup() takes the pg_ctl process and fails as soon as it has exited with an error, using your check. One addition: it only tries to connect once pg_ctl -w start has exited. Before that, the first connection can reach whatever holds the port, and pgjdbc then waits about 5 s for an answer that never comes; it also avoids starting again before the failed postmaster is gone. A failed attempt now takes about 200 ms.
  3. isTaken() is removed: without a set port, any failure is retried.
  4. The data_directory check is in the SELECT 1 query (SELECT 1, current_setting('data_directory')), the constructor cleanup also catches RuntimeException, and START_ATTEMPTS and the dataDirectory() helper are moved.

The three tests no longer shorten pgStartupWait, and the taken-port test checks that the failed attempt is fast (well under the default wait).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants