# Add Background Jobs to a Litestar App

Yes. An agent adds a Redis-backed job queue to your Litestar app with the SAQ plugin, a handler that enqueues, a worker command, tests, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-background-jobs/litestar/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how small the application is before deciding where a queue fits. In an app laid out like litestar-org/litestar-hello-world, `app.py` is the whole application: two handlers, `GET /async`, which sleeps a tenth of a second, and `GET /sync` with `sync_to_thread=False`, both returning `{"hello": "world"}`, assembled with `Litestar(route_handlers=[...])`. `pyproject.toml` depends on `litestar[standard]>=2.4.1`, with `pdm.lock` resolving Litestar 2.4.1, and keeps `ruff`, `mypy`, `pyright` and `pre-commit` in a `lint` group and `pytest`, `pytest-asyncio` with `asyncio_mode = "auto"` and `pytest-cov` in a `test` group; `[project.scripts]` maps `app` to Litestar's CLI, and the `Makefile` wraps `pdm install -G:all`, `pre-commit run` and `pytest tests`. `tests/test_app.py` uses `TestClient(app=app)` to assert both routes. `.github/workflows/ci.yaml` runs pre-commit, then `test.yaml` across Python 3.8 to 3.11, with macOS and Windows jobs on push. There is no Redis, no worker and no task that outlives a request.

Litestar's own `BackgroundTask`, passed as `background=` on a response, runs a callable after the response is sent and inside the same process, which is right for a log line and wrong for work that must survive a restart or run on a second machine. The agent adds `litestar-saq`, the SAQ plugin for Litestar, with `saq[redis]`, and because the plugin requires `litestar>=2.0.1` but was written against current 2.x, it moves the lock to Litestar's latest 2.x release and runs the existing tests to show nothing changed. `app.py` gains `SAQPlugin(config=SAQConfig(use_server_lifespan=True, queue_configs=[QueueConfig(name="default", dsn=settings.redis_url, tasks=[send_welcome])]))` in `plugins=[...]`, where `send_welcome` in a new `tasks.py` is an `async def send_welcome(ctx, *, email: str)` that logs and returns a JSON-serialisable dict, and `redis_url` is read from `REDIS_URL` with a `redis://localhost:6379/0` default in a small `settings.py`.

The handler is `POST /signups`, which validates a body with an `email` field, gets the queues through the dependency the plugin registers under its `task_queues` key, calls `queues.get("default")` and `await queue.enqueue("send_welcome", email=...)`, and returns `202` with the job key, so the request finishes before the mail would. A second handler, `GET /jobs/{key}`, reads the job's status back from the queue, which is what a client polls. `use_server_lifespan` means `litestar run` starts and stops the queue connection with the server, and the worker is a separate process started with `litestar workers run`, the command group the plugin adds to the CLI, so `pyproject.toml` gets a `worker` script and the README a section with both commands. The plugin's `web_enabled` flag mounts SAQ's monitoring UI under `/saq` on the worker; the agent leaves it off and shows the line.

Tests run against a real Redis in the sandbox. The agent installs `redis-server`, starts it, and adds `tests/test_jobs.py`: one test posts a signup through `TestClient` and asserts `202` with a key; another starts a `saq.Worker` for the queue in the test, enqueues `send_welcome` with `queue.apply`, which waits for the result, and asserts the dict the task returns; a third asserts that `GET /jobs/{key}` reports the status. `pytest tests` runs the old and new tests together, `pre-commit run --all-files` applies `ruff`, `mypy` and `pyright` to the new modules, and `test.yaml` gains a Redis service container so CI has the same backend.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add background jobs to this Litestar app with the SAQ plugin. Read app.py, pyproject.toml, pdm.lock, the Makefile, tests/test_app.py, .pre-commit-config.yaml and the workflows under .github/workflows first. Add litestar-saq and saq with its redis extra, moving the Litestar pin to the current 2.x release and rerunning the existing tests to show they pass. Add a settings module reading REDIS_URL with a localhost default, a tasks module with an async send_welcome task that logs and returns a dict, and register SAQPlugin with use_server_lifespan and one queue naming that task. Add POST /signups that validates an email, gets the queue from the plugin's task_queues dependency, enqueues send_welcome and returns 202 with the job key, and GET /jobs/{key} that reads the job status. Add a worker script and README section using litestar workers run; leave the web UI off and show the line. Install and start redis-server in the sandbox, add tests covering the enqueue response, a worker applying the task, and the status read, add a Redis service to the test workflow, run pytest and pre-commit, and open a pull request quoting the results.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request adds `settings.py`, `tasks.py` and `tests/test_jobs.py`, and changes `app.py`, `pyproject.toml`, `pdm.lock`, `README.md` and `.github/workflows/test.yaml`. Its description quotes the test run before the Litestar bump and after it, the full `pytest tests` output with the three new tests, the `pre-commit` result, and a transcript of `litestar workers run` picking up a job that `curl -X POST /signups` enqueued in the sandbox.

A reviewer checks the `tasks` list on the queue, since a function not listed there cannot run, the `REDIS_URL` default against their deployment, and the Litestar bump's changelog. They decide whether the worker runs as a second process of the same image or a separate deployment, which the README section describes both ways.

The two hello-world routes and their tests are untouched, and an app started without a Redis fails at startup with the connection error rather than at the first signup, because the lifespan opens the queue with the server.

## Run it on every Linear issue labelled background-job

In the console, add an automation to the Project with this prompt and a `linear` trigger on `linear.issue.labeled`, filtered to the `background-job` label. When someone labels an issue such as "the export endpoint times out", the trigger puts the issue after the prompt and the run reads which handler's work should move to a task before writing one. Only label changes by a person in your Rush org fire it, and the automation starts at most `max_runs_per_hour` runs in an hour.

An automation's runs are read-only, so the run that pushes the branch is started from your own server: a handler receiving the automation's comment sends this body to `POST /o/{org}/sessions` with the issue URL in `resources` and a `request_id` that is a UUID v5 of the issue id, so a redelivered event returns the run already started.

## Why run it on Rush?

The choice between a response's `background=` task and a real queue is the whole design, and the queue brings a worker process, a lifespan, a dependency key, a task allow-list and a Redis that tests need. The agent reads the application as it is, picks the plugin a Litestar maintainer publishes for SAQ, bumps the framework only as far as the plugin requires and proves the old tests still pass, then runs the new tests against a Redis it started in its sandbox, with every command and its output kept in the run's record.

The pull request also carries the operational half: the worker command, the service container in CI and the behaviour of a start without Redis, so the first deployment is not where those are discovered.

## Frequently asked questions

### Why not Litestar's BackgroundTask?

`BackgroundTask` runs after the response is sent, in the server process, with no retry and no record; a restart loses it. It is right for a log line or a cache warm. A welcome email or an export needs a queue that persists the job and a worker that can run elsewhere, which is what SAQ on Redis gives.

### Why does the Litestar version change?

`litestar-saq` declares `litestar>=2.0.1`, but its current release is developed against current Litestar 2.x, and the lock pinned 2.4.1. The agent moves to the latest 2.x, which keeps the `TestClient` and handler APIs the app uses, and runs the existing tests before and after so the bump is shown to be safe.

### How does a handler reach the queue?

The plugin registers a dependency under `task_queues`, the key `SAQConfig` sets by default, that resolves to the queues it owns. A handler declares that parameter, calls `.get("default")` for the queue, and `enqueue("send_welcome", email=...)` returns a job whose key the handler sends back.

### What runs the jobs?

A worker process started with `litestar workers run`, the command group the plugin adds to the Litestar CLI, which reads the same `SAQConfig` and runs the tasks listed on each queue. It can run beside the server or on another machine with the same Redis, and the README gives both commands.

### Can jobs run on a schedule?

Yes. `QueueConfig` takes `scheduled_tasks`, a list of SAQ cron jobs, so a task can run every night without a request. The pull request does not add one but shows the entry, since the worker that would run it is now in place.

## More Litestar jobs

- [Add Response Compression to a Litestar App](https://getrush.ai/run/add-compression/litestar/)
- [Add CORS to a Litestar API](https://getrush.ai/run/add-cors/litestar/)
- [Add Coverage to CI for a Litestar App](https://getrush.ai/run/add-coverage-to-ci/litestar/)

## The same job on other stacks

- [Add Background Jobs with Oban to a Phoenix App](https://getrush.ai/run/add-background-jobs/phoenix/)
- [Add Oban Background Jobs to a Phoenix LiveView App](https://getrush.ai/run/add-background-jobs/phoenix-liveview/)
- [Add Background Jobs to a Vapor App from a Linear Issue](https://getrush.ai/run/add-background-jobs/vapor/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
