<p>I have a FastAPI app with the following code</p>
<pre class="lang-py prettyprint-override"><code>    @app.on_event(&quot;startup&quot;)
    async def startup_event():
    &quot;&quot;&quot;Initialize application services&quot;&quot;&quot;
        print(&quot;Starting the service&quot;)
</code></pre>
<p>when I run FastAPI directly from the terminal, I get the following output</p>
<pre><code>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)
</code></pre>
<p>You can see that the print statement got executed.</p>
<p>However, when the same app is automatically run inside a Kubernetes cluster, I get the following output</p>
<pre><code> INFO:     Waiting for application startup.
 INFO:     Application startup complete.
 INFO:     Uvicorn running on http://0.0.0.0:3000 (Press CTRL+C to quit)
</code></pre>
<p>The print statement did not get executed, in fact, any additional code inside the function never gets executed.</p>
<p>However, if I exit the process like this:</p>
<pre class="lang-py prettyprint-override"><code>@app.on_event(&quot;startup&quot;)
async def startup_event():
    &quot;&quot;&quot;Initialize application services&quot;&quot;&quot;
    print(&quot;Starting the service&quot;)
    exit(99)
</code></pre>
<p>The process exists then I can see the print statement.</p>
<pre><code>SystemExit: 99
ERROR:    Application startup failed. Exiting.
Starting the service
</code></pre>
<p>What is the problem here?</p>
<p>Edit: Actually no code whatsoever gets executed, I have put print statements literally everywhere and nothing gets printed, but somehow the webserver runs...</p>

Adham Salama
<p>So, actually, there is no problem with my code, FastAPI, asyncio, or Kubernetes.</p>
<p>Everything was actually working correctly, it's just that the output was buffered.</p>
<p>After adding flush=True to the print statement, everything showed.</p>
<p>I am answering this in case some poor soul stumbles upon this thread in the future.</p>
<p>I spent days debugging this!!!</p>
