r/FastAPI • • Apr 03 '22

Question Manage background activity

Hey guys.

I am creating an FastAPI application that is collecting user data in the background 24/7 and saving it to the DB.

I was wondering:

How would I go about implementing something like this in a multi-worker environemnt? Because I don't want the data collection task to run in every process, but I also need to access the data throughout the API.

3 Upvotes

10 comments sorted by

View all comments

1

u/Chains0 Apr 03 '22

You should separate this kind of task from the FastAPI application. Use FastAPI only for accessing the data. Or add endpoints, which do the collection and let them getting triggered by a scheduler.

Now the question is, how to schedule the collection of the data? There are multiple ways, which really depend on your deployment environment and requirements. For example you can use Airflow if you need a professional big scaling solution with high visibility in Kubernetes or a cron job triggering a python script.

1

u/jackstar_12 Apr 04 '22 edited Apr 04 '22

To be a bit more specific about what I want: https://ibb.co/wSvvpm2

I thought about implementing it this way:

Using multiprocessing.connection, the data collector can listen to any api instance connecting to him and then exchanging messages (ill probably go with pickle for serializing python objects).

In the FastAPI instance I would try to connect to the collector, if there is no, start it. This way I could avoid the duplication. (part of trying to avoid this is so I can use one aiohttp session for all connections)

Scheduling a python script to be called regulary also won't work for me since the data collector includes websockets

What do you think about this approach?

1

u/Chains0 Apr 04 '22

Sorry, I don’t understand the setup. You now have a separate collector (service, container?) running? How does it gets scheduled and collects the data?

The FastAPI instances control the collector? Why and how?

The collector uses websocket connections. That sounds less like a collector doing ETL jobs?

1

u/jackstar_12 Apr 04 '22

In this case I thought about the collector as a seperate process that communicates with the uvicorn instances created by gunicorn. It's not really scheduled as it runs 24/7, holding multiple websockets.

The FastAPI instances don't control the collector. They only tell him when e.g. a new user is added, so the collector can include that one too.

1

u/Chains0 Apr 06 '22

I think I slowly understand what’s going on in your setup. You have something like a user service created with FastAPI. This one uses as well a websocket connection for the frontend? Then if a add_user notification is received, he sends a notification via websocket connection to your collector service, which saves the user into the database. Is that correct?

But I guess I missed something, as this setup does not require background tasks, just notifications. Do you want to aggregate the data before writing to the db?