# Add a Queue Consumer to a Cloudflare Worker

Yes. An agent adds a Queues producer binding and a queue handler to your Worker, writes batched D1 inserts, tests them in Workers Vitest, and opens a pull request.

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

## What the agent does

The agent reads the Worker's bindings and entry point before it adds a queue. In a Worker shaped like `d1-template` in cloudflare/templates, `wrangler.json` names `src/index.ts` as `main`, sets `compatibility_date` to 2025-10-08, turns `observability` on, uploads source maps, and binds one D1 database as `DB` with the name `d1-template-database`. `src/index.ts` exports a single `fetch` handler, typed with `satisfies ExportedHandler<Env>`, that runs `SELECT * FROM comments LIMIT 3` and renders the rows through `renderHtml.ts`. `migrations/0001_create_comments_table.sql` creates `comments(id, author, content)` and seeds three rows, and `package.json` has `cf-typegen` (`wrangler types`), `check` (`tsc && wrangler deploy --dry-run`), `seedLocalD1` (`wrangler d1 migrations apply DB --local`) and `predeploy` for the remote migration, with `wrangler 4.136.1` and `typescript 5.9.3` as the only dev dependencies and no tests.

The same repository shows the two halves of a queue. `ai-brand-visibility-template/wrangler.jsonc` declares `queues.producers` with a `queue` name and a `binding`, and `queues.consumers` for the same queue with `max_batch_size` and `max_concurrency`; `workers-builds-notifications-template` declares a consumer with `max_batch_size`, `max_batch_timeout` and `max_retries`, and its `src/index.ts` exports `async queue(batch: MessageBatch<CloudflareEvent>, env: Env)` beside `fetch`. The agent follows those shapes rather than inventing its own.

It adds a `POST /comments` branch to `fetch` that parses JSON, checks that `author` and `content` are non-empty strings, calls `env.COMMENTS_QUEUE.send({ author, content })` and answers 202, so a write never waits on D1. It adds a `queue` handler that prepares `INSERT INTO comments (author, content) VALUES (?, ?)` once, binds it per message and runs them in a single `env.DB.batch`, acks the batch on success and calls `retry()` on each message when the batch throws. `wrangler.json` gets the producer binding and a consumer block with a small batch size, a short batch timeout and a retry limit, and the agent runs `wrangler types` so `worker-configuration.d.ts` gains `COMMENTS_QUEUE: Queue`. The queue itself is created with `wrangler queues create`, a one-time step the pull request lists because the config references it by name.

The template has no test runner, so the agent adds `vitest` with `@cloudflare/vitest-pool-workers` and a `vitest.config.ts` pointing at `wrangler.json`, the way the templates with a `test/` directory in the same repository do, and writes cases that post a comment and read the 202, reject a body with no `content` with 400, call the exported `queue` handler with a two-message batch and then `SELECT` the rows from `env.DB`, and check that a failing batch retries every message. It runs `npm run check` for the type check and the dry-run deploy, then the tests, and keeps the output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a Cloudflare Queue to this Worker so comment writes happen in the background, and open a pull request. Read wrangler.json, src/index.ts, src/renderHtml.ts, migrations, package.json and worker-configuration.d.ts first. Add a POST /comments route to the fetch handler that validates a JSON body with non-empty author and content strings, sends it to a queue bound as COMMENTS_QUEUE and answers 202; answer 400 for a bad body. Add a queue handler that inserts a batch of messages into the comments table with one prepared statement and env.DB.batch, acks the batch on success and retries each message on failure. Add the producer binding and a consumer block with max_batch_size, max_batch_timeout and max_retries to wrangler.json, run wrangler types to update worker-configuration.d.ts, and list the wrangler queues create command the reader runs once. Add vitest with @cloudflare/vitest-pool-workers and tests that cover the 202, the 400, a two-message batch landing in D1, and retry on a failing batch. Run npm run check and the tests, and paste the output in the pull request. Do not change the migration or the HTML page.",
  "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 that edits `src/index.ts` for the new route and the `queue` handler, `wrangler.json` for the producer and consumer blocks, `worker-configuration.d.ts` as `wrangler types` regenerates it, and `package.json` for the test dependencies and a `test` script, plus a `vitest.config.ts` and a `test/` directory. The description pastes the `tsc` and `wrangler deploy --dry-run` output from `npm run check`, the Vitest summary, and the one `wrangler queues create` command to run before deploying.

The repository's own checks lint each template and run its tests on the pull request, so the new cases run there as well as in the sandbox.

A reviewer checks that the consumer's batch size and timeout suit the write rate, that a message is retried and not dropped when D1 is unavailable, and that the 202 is only sent after `send` resolves. Then they create the queue, deploy, and watch the consumer's invocations in the dashboard for the first batches.

## Run it on every Worker that writes on the request path

A team with several Workers that write to D1 or call a slow API inside `fetch` sends one `POST /o/{org}/sessions` per repository with this prompt and the repository in `resources`. Each run reads its own bindings and routes, so a Worker whose write is a KV `put` or an outbound webhook gets a consumer for that call instead, and each opens its own pull request.

Give the key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with `session_url` to read the pull request from, and `GET …/sessions/{id}/changes` lists the changed files with their diffs.

## Why run it on Rush?

A queue handler is easy to write and hard to prove: does the batch land, does a failure retry, does the producer binding match the consumer's name. In a Rush sandbox the agent runs the Worker inside workerd through the Vitest pool, drives a real batch into a local D1, and keeps the test output and the dry-run deploy in the run's record, so the pull request shows the consumer working before the queue exists in the account.

The code is short, but wiring `wrangler.json`, regenerating the `Env` type, adding a test runner the template does not have and checking retry behaviour is an afternoon on a laptop. The agent does it in one pass, and the same request works unchanged on the next Worker that writes on the request path.

## Frequently asked questions

### Does it create the queue?

No. Creating a queue is an account action, so the pull request lists `wrangler queues create` with the name the config uses, to run once before deploying. The tests do not need it: the Vitest pool provides the binding locally.

### Why batch the inserts?

Because the consumer receives up to `max_batch_size` messages at once and `env.DB.batch` runs the bound statements in one round trip. The handler prepares the statement once and binds it per message, which is also what makes a failing batch easy to retry as a whole.

### What happens when D1 is down?

The handler catches the thrown error and calls `retry()` on every message in the batch, so Queues redelivers them up to `max_retries` times. The pull request suggests a dead-letter queue as a follow-up if messages should be kept after that.

### Will the HTML page change?

No. `GET /` still renders the first three comments through `renderHtml.ts`. Only the new `POST /comments` route and the `queue` export are added to `src/index.ts`.

## More Cloudflare Workers jobs

- [Add R2 File Uploads to a Cloudflare Worker from a Linear Issue](https://getrush.ai/run/add-r2-file-uploads/cloudflare-workers/)
- [Add Rate Limiting to a Cloudflare Worker](https://getrush.ai/run/add-rate-limiting/cloudflare-workers/)
- [Add Request ID Logging to a Cloudflare Worker](https://getrush.ai/run/add-request-id-logging/cloudflare-workers/)

## More jobs like this: Hand off a long task

- [Add Rate Limiting to an Actix Web API](https://getrush.ai/run/add-rate-limiting/actix/)
- [Add Rate Limiting to an aiohttp App](https://getrush.ai/run/add-rate-limiting/aiohttp/)
- [Add Rate Limiting to an Axum API](https://getrush.ai/run/add-rate-limiting/axum/)

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