Fix RuntimeError: RuntimeError: Event loop is closed in FastAPI
This error occurs when an async startup event or lifespan handler tries to use the event loop after it has been closed, typically because the async resource initialization fails and cleanup runs against a closed loop. Fix it by using FastAPI's lifespan context manager pattern to properly initialize and clean up async resources like database pools and HTTP clients.
Reading the Stack Trace
Here's what each line means:
- File "/app/src/main.py", line 12, in startup_event: The startup event handler attempts to create an async database pool, which may fail if the database is unreachable.
- File "/app/venv/lib/python3.11/site-packages/asyncpg/pool.py", line 401, in _async__init__: asyncpg tries to initialize the connection pool, and failure during startup leaves the app in a broken state.
- File "/app/src/main.py", line 22, in shutdown_event: The shutdown handler tries to close the pool on a closed event loop because the startup failed and the loop was already torn down.
Common Causes
1. Using deprecated on_event instead of lifespan
The on_event('startup') and on_event('shutdown') decorators are deprecated and do not handle initialization failures gracefully.
from fastapi import FastAPI
import asyncpg
app = FastAPI()
@app.on_event("startup")
async def startup_event():
app.state.db_pool = await asyncpg.create_pool(DATABASE_URL)
@app.on_event("shutdown")
async def shutdown_event():
await app.state.db_pool.close() # Fails if startup_event failed
2. Missing error handling in startup
The startup handler does not catch connection errors, so a temporary database outage prevents the app from starting and leaves resources in an undefined state.
@app.on_event("startup")
async def startup():
app.state.redis = await aioredis.from_url(REDIS_URL)
app.state.db = await asyncpg.create_pool(DATABASE_URL)
# If Redis connects but DB fails, Redis connection leaks
3. Shutdown handler accessing uninitialized resources
The shutdown handler assumes all resources were created in startup, but if startup failed partway through, some resources do not exist.
@app.on_event("shutdown")
async def shutdown():
await app.state.redis.close() # AttributeError if redis was never set
await app.state.db_pool.close()
The Fix
Use the lifespan context manager pattern instead of deprecated on_event decorators. The code before yield runs on startup, and the code after yield runs on shutdown. This pattern guarantees cleanup runs in the same event loop context and only executes if startup succeeded.
from fastapi import FastAPI
import asyncpg
app = FastAPI()
@app.on_event("startup")
async def startup_event():
app.state.db_pool = await asyncpg.create_pool(DATABASE_URL)
@app.on_event("shutdown")
async def shutdown_event():
await app.state.db_pool.close()
from contextlib import asynccontextmanager
from fastapi import FastAPI
import asyncpg
import logging
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
logger.info("Connecting to database...")
app.state.db_pool = await asyncpg.create_pool(DATABASE_URL)
logger.info("Database pool created.")
yield
# Shutdown
logger.info("Closing database pool...")
await app.state.db_pool.close()
logger.info("Database pool closed.")
app = FastAPI(lifespan=lifespan)
Testing the Fix
import pytest
import pytest_asyncio
from httpx import AsyncClient, ASGITransport
from unittest.mock import patch, AsyncMock
from app.main import app
@pytest.mark.asyncio
async def test_app_starts_and_serves_requests():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
response = await ac.get("/health")
assert response.status_code == 200
@pytest.mark.asyncio
async def test_db_pool_is_available_after_startup():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
response = await ac.get("/health")
assert response.status_code == 200
@pytest.mark.asyncio
async def test_app_handles_multiple_requests():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
for _ in range(10):
response = await ac.get("/health")
assert response.status_code == 200
Run your tests:
pytest tests/test_startup.py -v --asyncio-mode=auto
Pushing Through CI/CD
git checkout -b fix/fastapi-startup-lifespan,git add src/main.py tests/test_startup.py,git commit -m "fix: migrate from on_event to lifespan context manager for proper startup/shutdown",git push origin fix/fastapi-startup-lifespan
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_DB: testdb
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: 'pip'
- run: pip install -r requirements.txt
- run: pytest --tb=short -q --asyncio-mode=auto
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/testdb
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
pip install bugstack
Step 2: Initialize
import bugstack
bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm the app starts and shuts down cleanly.
- Open a pull request with the lifespan migration.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify the app starts correctly in staging with real database connections.
Frequently Asked Questions
BugStack tests the full application lifecycle including startup, request handling, and shutdown, verifying that database pools are created and cleaned up without event loop errors.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review the lifespan changes before merging.
No. If you provide a lifespan parameter to FastAPI, all on_event handlers are ignored. Migrate all startup and shutdown logic into the lifespan context manager.
Add try/except inside the lifespan startup code. Log the error and either exit the process or set a health check flag so the load balancer removes the unhealthy instance.