Skip to content

Commit 87652a9

Browse files
committed
Fix "server closed connection unexpectedly" db issue
The engine outlives individual requests, so pooled connections can be dropped server-side (idle timeouts, firewall reaps, failovers) while still sitting in the pool. pool_pre_ping validates a connection before use and transparently reconnects if it is dead; pool_recycle bounds connection age so they are refreshed before common idle-timeout windows. Without these, a stale connection surfaces as "server closed the connection unexpectedly". Assisted-by: Claude Opus 4.8 <noreply@anthropic.com> Signed-off-by: Lukas Puehringer <lukas.puehringer@eclipse-foundation.org>
1 parent c5b263b commit 87652a9

1 file changed

Lines changed: 5 additions & 1 deletion

File tree

pia/main.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,11 @@
3838
@asynccontextmanager
3939
async def lifespan(app: FastAPI):
4040
"""Initialize database engine and session factory on app startup."""
41-
engine = create_engine(settings.database_url)
41+
engine = create_engine(
42+
settings.database_url,
43+
pool_pre_ping=True,
44+
pool_recycle=1800,
45+
)
4246
app.state.session_factory = sessionmaker(bind=engine)
4347
logger.info("Database engine and session factory initialized")
4448
yield

0 commit comments

Comments
 (0)