500 Time error - Python FastAPI on Vercel Pro

I’m using Python FastAPI on Vercel, and I’m encountering a 500 timeout error on the first request. Has anyone experienced a similar issue? If you know how to resolve it, I would appreciate your help.

ERROR:uvicorn.error:Unhandled error: 127.0.0.1 - - [10/Jan/2025 01:15:48] "GET /health/db HTTP/1.1" 500 - # This is test code for checking a health state of Database
@router.get("/health/db")
def check_db_connection(session: SessionDep):
    try:
        session.execute(text("SELECT 1"))
        return {"status": "Database connection is healthy"}
    except SQLAlchemyError as e:
        raise HTTPException(
            status_code=500,
            detail=f"Database connection error: {str(e)}"
        )

Hi @sehooh5, welcome to the Vercel Community!

Sorry that it’s not working as expected.

Does the code work correctly locally? Have you tried printing and reading the exception e before raising the HTTPException to see what the error is about?

Thank you for your response! @anshumanb

However, the 500 error doesn’t occur after the first request, so I can’t reproduce it again at the moment. It seems to happen again after some time, so I’ll wait and check later. Also, the error information shown in the Vercel logs is quite limited. Is there a way to get more detailed information?

Hi @sehooh5,

I suspect that you are trying to connect to a database assuming it is a persistent connection but in the serverless environment you’ll need a new connection for every cold start. For more details, see Connection Pooling with Serverless Functions.

About the logs: can you try printing a long block of static text to see if it comes through or not. Because, I can console log a big chunk (see image)