title: Sharing python objects across multiple workers
body: <p>We have created a service using FastAPI. When our service starts it creates a few python objects that the endpoints then use to store or retrieve data from.</p>
  <p>FastAPI in production starts with multiple workers. Our problem is that <strong>each worker creates its own object rather than sharing a single one</strong>.</p>
  <p>The script below shows a (simplified) example of what we are doing, though in our case the usage of Meta() is considerably more complex.</p>
  <pre><code>from fastapi import FastAPI, status
  
  class Meta:
     def __init__(self):
        self.count = 0  
  
  app = FastAPI()
  
  meta = Meta()
  
  # increases the count variable in the meta object by 1
  @app.get(&quot;/increment&quot;)
  async def increment():
      meta.count += 1
      return status.HTTP_200_OK
  
  # returns a json containing the current count from the meta object
  @app.get(&quot;/report&quot;)
  async def report():
      return {'count':meta.count}
  
  # resets the count in the meta object to 0
  @app.get(&quot;/reset&quot;)
  async def reset():
      meta.count = 0
      return status.HTTP_200_OK
  
  
  </code></pre>
  <p>As mentioned above, the problem with multiple workers is that each one will have its own <code>meta</code> object. Please be aware that the issue is not visible when running the api with a single worker.</p>
  <p>More explicitly, when we hit the <code>/increment</code> endpoint for the first time we will see only one of the two workers responding to the call (this is correct, we don't want both workers doing the same thing). However, because there are two separate <code>meta</code> objects, only one of the two will be incremented. <br/> When hitting the <code>/report</code> endpoint, depending on which worker responds to the request, either 1 or 0 will be returned.</p>
  <p>The question then is, how do we get the workers to share and operate on the same object?</p>
  <p>As a side question, the problem above affects the <code>/reset</code> endpoint too. If this endpoint is called then only one of the workers will reset its object. Is there a way to force all workers to respond to a single call on an endpoint?</p>
  <p>Thanks!</p>
  <p>Edit: I forgot to mention that we have tried (with no success) to store the <code>meta</code> object in the <code>app.state</code> instead. Essentially:</p>
  <pre><code>app.state.meta = Meta()
  ...
  @app.get(&quot;/report&quot;)
  async def report():
      return {'count':app.state.meta.count}
  </code></pre>