After Response
2 min read · last updated atThere is some work that takes time, but is actually not that important. Yes, if a new user signs up, you want to send them a welcome notification, but do they actually need to sit there and wait for your mailer to be done? And sending a mail might not be the only thing you do. Imagine the follwing code in a handler function of your framework of choice:
If you want your app to feel snappy, you gotta respond to the user directly. Maybe some (or all) of these can run asynchronously in the background.
A resilient solution like a Job Queue would do this task well, but often comes with additional infrastructure overhead. You need to store the job data somewhere, manage worker processes that run an additional instance of your app in a command line context, setup monitoring, alerting and a whole suite of other observability stuff, so you get notified if there are suddenly a lot less jobs running than usual. Sounds a bit too complicated for simply sending an email and create a few database records if you ask me.
To solve such problems, many framework provide ways to run logic after the response has been sent to the user. After all a web server also has worker processes.
Below are some examples how different frameworks solve this issue. The FastAPI one is very close to our previous example.
FastAPI has first-class support for this concept, which they call “Background Tasks”. It even has it’s own page in the official documentation.
import SideNote from “@components/SideNote.astro”;
Laravel’s Application::terminating
method allows scheduling a callback before application shuts down.
In a traditional PHP context, this will happen after the response has been send.
Here is an example of sending an email to the currently authenticated user, which can be placed somewhere in a controller after signing them up for the application:
There are also shortcuts for this, e.g. you can schedule a job class to run after the response has been sent, instead of sending it to a queue:
or use terminatable middleware: