# Add Background Jobs with Oban to a Phoenix App

Yes. An agent adds Oban to your Phoenix app, turns polling GenServers and fire-and-forget casts into retried, scheduled jobs with tests, and opens a PR.

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

## What the agent does

The agent clones the repository into its own cloud sandbox and reads how the app defers work today before it adds a queue. In an app like fly-apps/live_beats, `mix.exs` asks for Elixir `~> 1.12`, `phoenix ~> 1.7.1`, `ecto_sql ~> 3.11`, `postgrex`, `flame ~> 0.1.12` and `bumblebee` from GitHub, and nothing named Oban. `lib/live_beats/application.ex` starts a `Task.Supervisor` called `LiveBeats.TaskSupervisor`, a `FLAME.Pool` called `LiveBeats.WhisperRunner` with `min: 0`, `max: 5` and `max_concurrency: 10`, and `{LiveBeats.SongsCleaner, interval: {3600 * 6, :second}}`, the last one filtered out with `!parent &&` so FLAME runners do not start it.

Two pieces of work are the candidates. `lib/live_beats/songs_cleaner.ex` is a GenServer whose `init/1` reads `FLY_REGION` and `PRIMARY_REGION` and returns `:ignore` outside the primary region, then calls `Process.send_after` every `@poll_interval` of 30 minutes to run `MediaLibrary.expire_songs_older_than(count, interval)`. In `lib/live_beats/media_library.ex`, `import_songs/3` commits the songs in an `Ecto.Multi`, stores each MP3 through `consume_file`, then calls `async_transcribe/2`, which is a `FLAME.cast` to the WhisperRunner that runs `LiveBeats.Audio.speech_to_text`, broadcasts each segment and finally writes the transcript with `Repo.update_all`. A commented `Task.Supervisor.start_child` above it shows the earlier shape. If that cast raises, nothing retries it and the song keeps an empty transcript.

The agent adds `oban` to `deps` in `mix.exs`, runs `mix deps.get`, writes a migration under `priv/repo/migrations` that calls `Oban.Migration.up` and `down`, and configures `config :live_beats, Oban` in `config/config.exs` with `repo: LiveBeats.Repo`, two queues named for the work (`transcription` with a limit no higher than the FLAME pool's `max_concurrency`, and `maintenance`) and the `Oban.Plugins.Cron` plugin with a `*/30 * * * *` entry for `LiveBeats.Workers.ExpireSongs`, the same cadence `SongsCleaner` had. `config/test.exs` gets `testing: :manual`. `LiveBeats.Workers.ExpireSongs` keeps the `{3600 * 6, :second}` threshold as job args; `LiveBeats.Workers.TranscribeSong` takes `%{"song_id" => id}`, sets `max_attempts: 3` and `unique: [keys: [:song_id]]`, and moves the body of `async_transcribe/2` into `perform/1`, calling the FLAME pool with `FLAME.call` so a crash in the runner fails the job and Oban retries it with backoff. `import_songs/3` inserts the job inside the existing multi with `Oban.insert/3`, so a job exists only when the songs commit.

In `application.ex` the agent adds `{Oban, Application.fetch_env!(:live_beats, Oban)}` after `LiveBeats.Repo`, guarded with `!parent &&` like the endpoint so FLAME runners never pull jobs, and removes `SongsCleaner` from the children. The region check is no longer needed: Oban's plugins run on the node that holds leadership, so the cron fires once per cluster. Tests use `Oban.Testing` in `test/live_beats/workers/`: `perform_job/2` for each worker against the SQL sandbox that `test/support/data_case.ex` sets up, and an `assert_enqueued worker: TranscribeSong` added to the `import_songs` case in `test/live_beats/media_library_test.exs`. The agent runs `mix format` with the `.formatter.exs` that loads `Phoenix.LiveView.HTMLFormatter`, `mix compile --warnings-as-errors` and `mix test`, whose alias in `mix.exs` runs `ecto.create --quiet` and `ecto.migrate --quiet` first against the `live_beats_test` database `config/test.exs` names.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add Oban background jobs to this Phoenix app and open a pull request. Read mix.exs, lib/live_beats/application.ex, lib/live_beats/songs_cleaner.ex, lib/live_beats/media_library.ex, config/config.exs, config/test.exs, config/runtime.exs and test/live_beats/media_library_test.exs first. Add oban as a dependency, a migration that runs Oban.Migration, and config with a transcription queue and a maintenance queue. Replace the SongsCleaner GenServer with a cron job on the same 30-minute cadence that expires songs older than the same six-hour threshold. Replace the FLAME.cast in async_transcribe with a TranscribeSong worker that is unique per song, retries up to three times, and is inserted inside the import_songs multi. Start Oban in the supervision tree only when the node is not a FLAME runner. Add Oban.Testing tests for both workers and an assert_enqueued check in the import test. Run mix format, mix compile --warnings-as-errors and mix test against Postgres, and put the output in the pull request description.",
  "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

What comes back is a pull request on its own branch. It changes `mix.exs` and `mix.lock`, adds one migration under `priv/repo/migrations`, edits `config/config.exs` and `config/test.exs`, adds `lib/live_beats/workers/expire_songs.ex` and `lib/live_beats/workers/transcribe_song.ex`, edits `lib/live_beats/application.ex` and `lib/live_beats/media_library.ex`, deletes `lib/live_beats/songs_cleaner.ex`, and adds the two worker test files plus the new assertion in the media library test. The description says which queue limits it chose and why they sit under the FLAME pool's `max: 5` and `max_concurrency: 10`.

The run's record keeps the `mix test` output, including the `ecto.migrate` step that creates the `oban_jobs` table, so a reviewer can see the suite pass with the queue in place rather than take the description's word. It also shows whether `LiveBeats.Application.start/2` loaded `openai/whisper-tiny` through Bumblebee in the sandbox, which the app does at boot whenever the FLAME backend is not Fly.

Before merging, a reviewer checks that the cron entry matches the cadence the GenServer had, that `unique` on `song_id` does not block a legitimate re-transcription after a failed upload, that the `!parent &&` guard keeps Oban off FLAME runners, and that `config/runtime.exs` needs no new environment variable for production.

## Run it on every Phoenix service without a job queue

A script on your server lists repositories through `GET /o/{org}/github`, reads each `mix.lock` for an `oban` entry, and sends one `POST /o/{org}/sessions` with this prompt for every Phoenix repository that has none, with that repository in `resources`. Each run reads its own supervision tree, so a service whose deferred work is a `Task.Supervisor` call or a `Process.send_after` loop gets workers shaped for that code, and each opens its own pull request.

A `request_id` in each body makes a retry safe, and the key's `webhook_url` receives `run.completed` or `run.failed` for every run the key starts, with `data.session_url` to read the pull request link from.

## Why run it on Rush?

Moving work into a queue is only safe once the suite runs green against a real database with the queue table in place, and in this app the suite also boots a Bumblebee model and a FLAME pool. The sandbox has Postgres, runs the full `mix test` alias with its `ecto.create` and `ecto.migrate` steps, and keeps the output, so the pull request carries proof instead of a promise to run it later.

The change touches the dependency list, a migration, config for two environments, the supervision tree and the module that imports songs. One run returns all of it with its log, and the same prompt runs against several Phoenix services at once, each in its own sandbox reading its own `application.ex`.

## Frequently asked questions

### Why Oban rather than a Task.Supervisor or the FLAME pool?

The FLAME pool gives the transcription a bigger machine but does not persist the request: a crash in the runner loses it. Oban stores each job in Postgres, retries it with backoff up to `max_attempts`, and shows it in the `oban_jobs` table. The worker still hands the model work to `LiveBeats.WhisperRunner`; what changes is who remembers that it needs doing.

### What happens to the primary-region check in SongsCleaner?

It goes away. Oban elects one leader per cluster and runs plugins such as the cron there, so the expiry job is inserted once every 30 minutes regardless of how many Fly regions run the app. The six-hour threshold the supervisor passed as `{3600 * 6, :second}` becomes the job's args.

### Does this change my database?

One migration adds the `oban_jobs` table and its indexes through `Oban.Migration.up`. Nothing in the `songs` or `users` tables changes. The migration runs with the rest under `mix ecto.migrate`, which the `test` alias and `fly.toml`'s release command already call.

### Will the tests need a running queue?

No. `config/test.exs` sets `testing: :manual`, so inserted jobs sit in the sandboxed database and the tests call `perform_job/2` directly or assert with `assert_enqueued`. No queue process polls during the suite, which keeps the SQL sandbox in `test/support/data_case.ex` working as before.

### I use SQLite or MySQL instead of Postgres. Does this still apply?

Oban ships engines for SQLite and MySQL as well as Postgres, and the agent reads your `mix.exs` adapter to pick one. The cron plugin and `Oban.Testing` work the same. Only the migration module differs, and the pull request names the one it used.

## More Phoenix jobs

- [Add a Feature to a Phoenix App from a Customer Spec](https://getrush.ai/run/add-feature-per-customer/phoenix/)
- [Add GitHub Actions CI to a Phoenix App](https://getrush.ai/run/add-github-actions-ci/phoenix/)
- [Add Health Checks to a Phoenix App](https://getrush.ai/run/add-health-checks/phoenix/)

## The same job on other stacks

- [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/)
- [Add Background Jobs to a Litestar App](https://getrush.ai/run/add-background-jobs/litestar/)

## 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/)
