Asynchronous Flow

AsyncFlow is an “async version” of the Flow class.

The quote mark represents the explicit async when using AsyncFlow.

While synchronous from outside, Flow also runs asynchronously under the hood: it manages the eventloop(s) for scheduling the jobs. If the user wants more control over the eventloop, then AsyncFlow can be used.

Create AsyncFlow

To create an AsyncFlow, simply

  1. from jina import AsyncFlow
  2. f = AsyncFlow()

There is also a sugary syntax Flow(asyncio=True) for initiating an AsyncFlow object.

  1. from jina import Flow
  2. f = Flow(asyncio=True)

Input & output

Unlike Flow, AsyncFlow accepts input and output functions as async generators. This is useful when your data sources involve other asynchronous libraries (e.g. motor for MongoDB):

  1. import asyncio
  2. from jina import AsyncFlow, Document
  3. async def async_inputs():
  4. for _ in range(10):
  5. yield Document()
  6. await asyncio.sleep(0.1)
  7. with AsyncFlow().add() as f:
  8. async for resp in f.post('/', async_inputs):
  9. print(resp)

Using AsyncFlow for overlapping heavy-lifting job

AsyncFlow is particularly useful when Jina and another heavy-lifting job are running concurrently:

  1. import time
  2. import asyncio
  3. from jina import AsyncFlow, Executor, requests
  4. class HeavyWork(Executor):
  5. @requests
  6. def foo(self, **kwargs):
  7. time.sleep(5)
  8. async def run_async_flow_5s():
  9. with AsyncFlow().add(uses=HeavyWork) as f:
  10. async for resp in f.post('/'):
  11. print(resp)
  12. async def heavylifting(): # total roundtrip takes ~5s
  13. print('heavylifting other io-bound jobs, e.g. download, upload, file io')
  14. await asyncio.sleep(5)
  15. print('heavylifting done after 5s')
  16. async def concurrent_main(): # about 5s; but some dispatch cost, can't be just 5s, usually at <7s
  17. await asyncio.gather(run_async_flow_5s(), heavylifting())
  18. if __name__ == '__main__':
  19. asyncio.run(concurrent_main())

AsyncFlow is very useful when using Jina inside a Jupyter Notebook, where it can run out-of-the-box.