Hi,
I am working on migrating our code to serverless. We are using python 3.12 and FastAPI. The database is Neon. At runtime, we have a lifepsan init setup for creating a db connection pool (shown below). However the lifespan is not running when using vercel dev or in previews. Therefore we are getting db connection errors because the pool was never initialized. When I run this as a standalone application using uvicorn I can see the lifespan and connection pool being initialized.
Any points on what is going wrong?
I have double checked the DB URL and it is correct. This problem only happens using vercel dev/deployments. I’ve currently switched to acquiring a connection on every db call which works on deployments but introduces a lot of latency. We would like to be able to use lifespan to create a pool.
Thank you!
index.py snippet
@asynccontextmanager
async def lifespan(app: fastapi.FastAPI):
# Code to run on startup
logger.info("--- LIFESPAN: Entering lifespan manager ---")
logger.info("Application startup: Initializing database pool...")
await init_db_pool()
yield # Application runs here
# Code to run on shutdown
logger.info("Application shutdown: Closing database pool...")
await close_db_pool()
# Create the main FastAPI application instance
# Vercel's Python runtime will look for an object named 'app' (or 'api') by default
app = fastapi.FastAPI(
title="Serverless API",
description="API endpoints for Marly services and Inngest workflows.",
# You can add version, docs_url, redoc_url etc. here
# version="0.1.0",
lifespan=lifespan
)
vercel.json
{
"version": 2,
"builds": [
{
"src": "api/index.py",
"use": "@vercel/python"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/api/index.py"
}
]
}