Skip to content
mentoor

Topic 1 of 5 · 4 min read

Running agent jobs on queues and workers

Goal: Design a queue setup for agent jobs with a concurrency limit and a dead-letter path for jobs that fail repeatedly.

Run every agent job from a queue, not from the web request that started it: the request enqueues a job and returns, and a pool of workers runs the job at a rate you control. A single agent run can take minutes and make dozens of model and tool calls. An HTTP handler that waits for all of it will time out, and a deploy will kill it halfway.

Check yourself · 1 of 3

Why should an agent run that takes several minutes be started from a queue rather than inside the web request?

Choose one answer

Why it matters

Three things break when agent jobs run inline. A traffic spike starts 500 runs at once and you hit the model provider's rate limit. A deploy restarts the process and every running job vanishes. A job that always fails, for example because of a malformed input, is retried forever and burns tokens. A queue fixes all three: jobs wait on disk (in Redis, Postgres or a cloud queue), workers pull them, and you set how many run at once.

The parts

  1. Producer. Your API validates the request, writes a job with an id and a payload, and returns 202 Accepted with that id.
  2. Queue. Durable storage for waiting jobs. BullMQ on Redis, SQS, and Postgres-based queues are common choices.
  3. Worker pool. Processes that pull jobs. Concurrency is the number of jobs one worker runs at the same time.
  4. Back-pressure. When the queue grows faster than workers drain it, you want a visible signal (queue depth, oldest job age) and a decision: add workers, slow the producers, or reject new work.
  5. Dead-letter queue (DLQ). After a set number of failed attempts, the job moves to a separate queue for a human to inspect instead of retrying forever.

Before and after

// Before: the run lives and dies with the request
app.post("/research", async (req, res) => {
  const report = await runAgent(req.body.topic); // minutes long
  res.json(report);
});
// After: enqueue, return, and let a capped worker do the work
import { Queue, Worker } from "bullmq";

const queue = new Queue("agent-jobs", { connection });

app.post("/research", async (req, res) => {
  const job = await queue.add("research", req.body, {
    attempts: 3,
    backoff: { type: "exponential", delay: 5000 },
  });
  res.status(202).json({ jobId: job.id });
});

new Worker("agent-jobs", runAgentJob, { connection, concurrency: 5 });

Pick the concurrency from the model provider's rate limit and your cost budget, not from CPU: agent jobs spend most of their time waiting on the network.

What goes wrong

  • No attempt limit. A poison job (input that always crashes the agent) loops, and each loop pays for model calls. Cap attempts and route the failure to a DLQ.
  • Visibility timeout shorter than the job. On SQS a message becomes visible to other workers again if it is not deleted in time. A long agent job then runs twice at once. Extend the timeout while the job runs.
  • Retries that restart from step one. A queue retry reruns the whole job. Without saved state (see the state topic) every retry repeats the early tool calls and their cost.
  • Nobody reads the DLQ. A dead-letter queue with no alert is a silent drop. Alert on its depth.

Examples

Handler returns a job id

The API returns 202 and { "jobId": "j_81" }. The client polls GET /jobs/j_81 or receives a webhook. The request never holds a connection open for the length of the run.

Dead-letter rule on SQS

Set maxReceiveCount to 3 on the source queue and point its redrive policy at agent-jobs-dlq. After the third failed receive the message moves there, and an alarm on the DLQ's ApproximateNumberOfMessagesVisible pages the on-call engineer.

Key points

  • A queue lets the request return at once while workers run the long agent job at a rate you set.
  • Set worker concurrency from the model provider's rate limit and your cost budget, because agent jobs mostly wait on the network.
  • Cap attempts and send a job that keeps failing to a dead-letter queue instead of retrying forever.
  • Watch queue depth and the age of the oldest job; they are the back-pressure signals.
  • A queue retry reruns the whole job, so retries need saved state to avoid repeating early work.

Common mistakes

  • Running the agent inside the HTTP handler and relying on a long timeout.
  • Setting concurrency to a large number because the workers have spare CPU, then hitting the provider's rate limit.
  • Leaving attempts unlimited, so a poison job retries forever.
  • Creating a dead-letter queue and never alerting on it.

Check yourself · 2 of 3

A worker pool is set to concurrency 50, and the model provider allows about 10 concurrent requests per key. What is the likely result?

Choose one answer

Check yourself · 3 of 3

A job with a malformed PDF crashes the agent every time. The queue has attempts unlimited. What should you change first?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic