3

I have a FastAPI app with the following code

    @app.on_event("startup")
    async def startup_event():
    """Initialize application services"""
        print("Starting the service")

when I run FastAPI directly from the terminal, I get the following output

INFO:     Started server process [259936]
INFO:     Waiting for application startup.
Starting the service
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:3000 (Press CTRL+C to quit)

You can see that the print statement got executed.

However, when the same app is automatically run inside a Kubernetes cluster, I get the following output

 INFO:     Waiting for application startup.
 INFO:     Application startup complete.
 INFO:     Uvicorn running on http://0.0.0.0:3000 (Press CTRL+C to quit)

The print statement did not get executed, in fact, any additional code inside the function never gets executed.

However, if I exit the process like this:

@app.on_event("startup")
async def startup_event():
    """Initialize application services"""
    print("Starting the service")
    exit(99)

The process exists then I can see the print statement.

SystemExit: 99
ERROR:    Application startup failed. Exiting.
Starting the service

What is the problem here?

Edit: Actually no code whatsoever gets executed, I have put print statements literally everywhere and nothing gets printed, but somehow the webserver runs...

4
  • perhaps you looking at an old image. You sure it got pulled?
    – The Fool
    Apr 27, 2022 at 13:15
  • @TheFool Yes, I changed the port to see if it changes in the logs and it does. Apr 27, 2022 at 13:18
  • Looks like a difference of how asyncio is being handled in the kubernetes python client versus in your environment Apr 27, 2022 at 14:35
  • It turns out the problem was the internal buffer not flushing the output. Forcing it to flush: print("", flush=True) solved the issue. Apr 27, 2022 at 15:23

1 Answer 1

2

So, actually, there is no problem with my code, FastAPI, asyncio, or Kubernetes.

Everything was actually working correctly, it's just that the output was buffered.

After adding flush=True to the print statement, everything showed.

I am answering this in case some poor soul stumbles upon this thread in the future.

I spent days debugging this!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.