← All notes

Run a Starlette or FastAPI background task after the response is sent

Answer: Starlette's BackgroundTask class is for in-process background tasks. Attach it to a response; it runs after that response has been sent. In FastAPI you can define background tasks to be run after returning a response.

Starlette BackgroundTask

The signature is BackgroundTask(func, args, *kwargs). The signup example builds a task with send_welcome_email and returns JSONResponse(message, background=task). The example returns JSONResponse(message, background=task) from signup.

FastAPI

Use this for operations that need to happen after a request, without making the client wait. Email notifications are the usual example, because connecting to an email server and sending an email tends to be slow. Processing data, such as a file that must go through a slow process, is another case: return the response right away and do that work in the background.

| Starlette | FastAPI | |---|---| | BackgroundTask | In-process task attached to a response | | background=task | Passed to a response such as JSONResponse | | after returning a response | When FastAPI runs the task | | email notifications | Example that should not block the response |

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Starlette, Background Tasks; FastAPI, Background Tasks. BSD-3-Clause; MIT. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Starlette, Background Tasks; FastAPI, Background Tasks. BSD-3-Clause; MIT.

Cite this

Permanent ID: iil:note:zy3kga2v

iinventedlight. 2026. "Run a Starlette or FastAPI background task after the response is sent." iinventedlight Library, iil:note:zy3kga2v, version of 2026-11-19. https://iinventedlight.com/library/notes/starlette-background-tasks/. License: CC-BY-4.0.

@misc{iil_note_zy3kga2v,
  author = {{iinventedlight}},
  title = {{Run a Starlette or FastAPI background task after the response is sent}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-19},
  url = {https://iinventedlight.com/library/notes/starlette-background-tasks/},
  note = {Permanent ID iil:note:zy3kga2v. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/starlette-background-tasks.md.