Background Tasks
Fenrir supports running background tasks after sending the response, allowing you to perform work like sending emails, processing data, or triggering webhooks without blocking the client.
Simple Background Task
Use BackgroundTasks to run functions after the response is sent:
1 2 3 4 5 6 7 8 9 10 11 | |
The task function receives positional arguments in the order they are passed.
Multiple Background Tasks
Use BackgroundTasks to queue multiple tasks:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
BackgroundTasks is automatically injected when declared as a parameter — no Depends() needed.
Background Tasks in MethodView
Background tasks work seamlessly with class-based views:
1 2 3 4 5 6 7 | |
Using Sanic-style Task Scheduler
Schedule recurring tasks using server lifecycle listeners:
1 2 3 4 5 6 7 8 | |
Background Tasks with Dependency Injection
Background tasks can be used inside dependency-injected functions:
1 2 3 4 5 6 7 8 9 10 | |
Error Handling
If a background task raises an exception, it is logged but does not affect the client response. The exception is silently caught and logged by the framework.
Best Practices
- Keep tasks idempotent: Background tasks may retry on failure, so design them to be safely re-runnable.
- Avoid shared state: Tasks run after the response, so avoid modifying request-scoped state.
- Use async functions: For I/O-bound work, use
asyncfunctions to avoid blocking the event loop. - Limit task complexity: For long-running or CPU-intensive work, consider using a dedicated task queue (Celery, RQ) instead.