N
Neon6mo ago
xenophobic-harlequin

Connection issue with neon DB and FastAPI application deployed on Vercel

FastAPI application that is connected to Neon DB (serverless Postgres) works locally, but fails to establish a database connection on deployment in Vercel. lifespan or startup event handlers for initializing the database pool seem to not execute or fail in the deployed environment. No proper error statement is shown. What is the source of this issue? . Is it Vercel or NeonDB? What are the alternatives to keep DB connection alive throughout session. I want the DB pool connection to be closed only when FastAPI app stops running. Here is the code snippet
pool = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global pool
pool = await asyncpg.create_pool(os.getenv('DATABASE_URL'))
yield
if pool:
await pool.close()
app = FastAPI(lifespan=lifespan)
pool = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global pool
pool = await asyncpg.create_pool(os.getenv('DATABASE_URL'))
yield
if pool:
await pool.close()
app = FastAPI(lifespan=lifespan)
I have tried following alternative as well. (It didn't work.)
pool = None
async def startup_event():
global pool
logging.info("Startup event: Initializing database pool")
pool = await asyncpg.create_pool(os.getenv('DATABASE_URL'))
logging.info(f"Startup event: Database pool initialized: {pool}")

async def shutdown_event():
global pool
logging.info("Shutdown event: Initiated")
if pool:
logging.info("Shutdown event: Closing database pool")
await pool.close()
logging.info("Shutdown event: Database pool closed")

app = FastAPI()
app.add_event_handler("startup", startup_event)
app.add_event_handler("shutdown", shutdown_event)
pool = None
async def startup_event():
global pool
logging.info("Startup event: Initializing database pool")
pool = await asyncpg.create_pool(os.getenv('DATABASE_URL'))
logging.info(f"Startup event: Database pool initialized: {pool}")

async def shutdown_event():
global pool
logging.info("Shutdown event: Initiated")
if pool:
logging.info("Shutdown event: Closing database pool")
await pool.close()
logging.info("Shutdown event: Database pool closed")

app = FastAPI()
app.add_event_handler("startup", startup_event)
app.add_event_handler("shutdown", shutdown_event)
Currently I am opening and closing pool connection for each and every function (FastAPI endpoint) which seems inefficient. Please suggest a solution for this issue.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?