@@ -132,16 +132,33 @@ func GetPostgresContainer(ctx context.Context) (*postgres.PostgresContainer,
132132 },
133133 ).WithStartupTimeout (pgInitTimeout )
134134
135+ p := testParallelism ()
136+ m := db .DefaultMaxConnections
137+
138+ // pgMaxConns is the Postgres max_connections budget for the
139+ // test container. It is sized as P*M + M + 3*P where:
140+ //
141+ // P*M — steady-state: up to P parallel tests each holding a
142+ // pool of at most M connections (db.SetMaxOpenConns).
143+ //
144+ // +M — teardown latency: one extra store-equivalent for a
145+ // store that has called Close() but whose connections
146+ // have not yet fully disappeared from Postgres.
147+ //
148+ // +3*P — per-slot bootstrap overlap: each slot needs roughly
149+ // 3 transient connections while a new test starts —
150+ // one admin connection for CREATE DATABASE, ~1 for
151+ // PingContext, and ~1 for migration setup — so 3*P
152+ // covers all slots transitioning simultaneously.
153+ pgMaxConns := p * m + m + 3 * p
154+
135155 pgContainer , pgContainerErr = postgres .Run (ctx ,
136156 cfg .Image ,
137157 postgres .WithDatabase (cfg .Database ),
138158 postgres .WithUsername (cfg .Username ),
139159 postgres .WithPassword (cfg .Password ),
140160 testcontainers .WithCmd (
141- "-c" , fmt .Sprintf (
142- "max_connections=%d" ,
143- testParallelism ()* db .DefaultMaxConnections ,
144- ),
161+ "-c" , fmt .Sprintf ("max_connections=%d" , pgMaxConns ),
145162 ),
146163 testcontainers .WithWaitStrategyAndDeadline (
147164 pgInitTimeout , waitForSQL ,
0 commit comments