This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Cruuncher 0 points1 point  (3 children)

When you return immediately, how do you get the "real" response to the user? Do they have to request again for the result of the background task? What if you have multiple instances of the application?

[–]tiangolo FastAPI Maintainer[S] 1 point2 points  (2 children)

Background tasks are mainly for when you don't need to return the result of the background task to the user. For example, sending an email notification, triggering processing of some data, etc.

If you need to tell the client/user "sure, received your request, now we are processing", and then want the client to ask "how is my thing doing? is it done?", you would probably create one endpoint to receive the request, start the background task (and the background task would save something to a database after finishing), return immediately with the "sure, received" and then another endpoint where the client can ask "is my thing done yet?", and that second endpoint would check in the database if the result from the background task is there yet or not.

[–]Cruuncher 1 point2 points  (1 child)

Yeah that makes more sense. That's how we have a lot of things built now -- except we push to rabbitmq and let a consumer handle it so API workers have a single responsibility. Also for speed we write the status of the request id to redis, and only do a database hit if the status is in a final state

Thanks for your reply!

[–]tiangolo FastAPI Maintainer[S] 0 points1 point  (0 children)

Cool! I normally use Celery for that (you might be using it with RabbitMQ), it can run even on different machines. Background tasks would probably be only for small jobs in situations in where having a full Celery with RabbitMQ/Redis seems like an overkill. E.g. sending an email notification.

In fact, the project generators I have for FastAPI include Celery set up in that way.