# Background Responses in FastAPI

## The pattern

1. Call `client.responses.create(..., background=True)`. It returns immediately
   with a response object whose `status` is `queued`.
2. Return HTTP 202 to your client with the response id. Do not hold the request.
3. Poll `client.responses.retrieve(response_id)` until `status` is `completed`,
   or register a webhook to be notified. Your polling loop lives in a background
   worker (Celery, arq, or a FastAPI BackgroundTask that only polls), not in the
   request handler.
4. On `completed`, read `response.output` (or `output_text`) and store the result
   against the job id.

## Traps

- BackgroundTask in FastAPI still runs inside the worker process; it is fine for
  polling but not for CPU-heavy post-processing. Keep the poll interval sane
  (a few seconds) to avoid hammering the retrieve endpoint.
- `background=True` changes the return contract: there is no `output_text` until
  completion. Code that reads `response.output_text` immediately after a
  background create gets nothing; gate on `status`.
- Failed background responses carry the error in the response object; surface it
  to the job record instead of retrying blindly.

## Check before you ship

- Kill the API process mid-job and confirm the job can be recovered by id
  (retrieve by the stored response id).
- Confirm your 202 response includes the id and a poll endpoint; clients should
  never guess the id format.