title: Post-startup event in FastAPI?
body: <p>I have a FastAPI app that serves an ML model. It is deployed on Kubernetes. For best practices Kubernetes recommends implementing a liveliness endpoint in your API that it can probe to see when the application has completed startup, as well as a readiness endpoint to probe to see when the application is ready to start receiving requests.</p>
  <p>Currently, I have implemented both the liveliness and readiness endpoints as a single endpoint, which returns a status code of <code>200</code> once the ML model has been loaded and the endpoints are available for requests.</p>
  <p>This is ok, but ideally, I would like a liveliness endpoint to return <code>200</code> once FastAPI's startup has completed, and a readiness endpoint to return <code>200</code> once the models have been loaded (takes much longer than the application startup).</p>
  <p>FastAPI allows for <a href="https://fastapi.tiangolo.com/advanced/events/" rel="nofollow noreferrer">startup event triggers</a> where I could initiate the loading of the model, but no endpoints become available until the application startup is complete, which will not be complete until the startup events are also complete.</p>
  <p>Is there anyway to implement and &quot;post-startup&quot; event in FastAPI where I could initiate the loading of the model?</p>
  <p>Here is some simple example code for what I would like to achieve:</p>
  <pre><code>from fastapi import FastAPI, Response
  from request import PredictionRequest
  import model
  
  app = FastAPI()
  
  @app.on_event(&quot;post-startup&quot;) # not possible
  def load_model():
      model.load()
  
  @app.get(&quot;/live&quot;)
  def is_live():
      return Response(status_code=200)
  
  @app.get(&quot;/ready&quot;)
  def is_ready():
      if model.is_loaded():
          return Response(status_code=200)
      else:
          return Response(status_code=409)
  
  @app.post('/predict')
  def predict(request: PredictionRequest):
      return model.predict(request)
  </code></pre>