fix: run MongoDB connect in background so HTTP port binds immediately

Blocking startup_event on connect_to_mongo() prevented the server from
opening its port when Atlas was slow or unreachable, causing Render to
wait indefinitely. Connection now runs as a background task.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
vee1e 2026-06-02 12:59:48 +05:30
parent 21c618ae78
commit 29a6379370
No known key found for this signature in database
GPG key ID: EB498AFC60A7A01A

View file

@ -52,8 +52,17 @@ async def startup_event():
"""Connect to MongoDB on startup and log cold start time"""
global startup_time
startup_time = time.time()
await connect_to_mongo()
log_metric('cold_startup_time', time.strftime('%Y-%m-%d %H:%M:%S'))
# Run in background so the HTTP server binds its port immediately.
# If MongoDB is unreachable (e.g. Atlas IP allowlist), the server stays
# up and retries rather than blocking Render's health check.
asyncio.create_task(_connect_with_log())
async def _connect_with_log():
try:
await connect_to_mongo()
log_metric('cold_startup_time', time.strftime('%Y-%m-%d %H:%M:%S'))
except Exception as e:
logger.error(f"MongoDB connection failed at startup: {e}")
@app.on_event("shutdown")
async def shutdown_event():