Core Concepts

Messaging and Work Queues

Follow a background job through a worker crash, then choose between work sharing, live delivery, and replay.

Free~16 min

A work queue holds jobs until a background worker can take them. The API can confirm that it accepted a job before the result is ready. Decide what has to be saved before the API answers and what a worker must finish before it acknowledges the job.

Save the job before answering

In the reporting app, the API adds, or enqueues, job 47 with the accepted export parameters, such as the sales report, the West region, and the dates November 9 to 15. It saves the job as pending in a store that survives a process restart, then returns 202 Accepted with the job ID. The browser can use that ID to check for the result later. The API checks that the signed-in account owns the job before serving its status or result. HTTP semantics for 202 Accepted

A worker is a process that runs jobs in the background. Worker A asks for a job. The queue grants it a claim, which gives A permission to work on job 47 for a limited time. The queue records the worker, the attempt number, and the deadline together. In this example, the queue grants one current claim if A and B ask for job 47 at the same time. A claims attempt 1 at 12:00:00 with a deadline of 12:00:30.

A builds the CSV from the accepted inputs and saves it as result 47 in the Results DB, the database the app reads when it serves completed exports. A waits for the write to commit, meaning the database confirms the save and the result survives a worker restart. A then acknowledges attempt 1. That tells the queue to mark job 47 as done.

The queue and Results DB are separate systems here. The API needs confirmation that the queue has accepted the job. Later, the queue needs confirmation that the worker has finished. A message broker, a service that accepts and delivers messages, can expose both signals. In RabbitMQ, the publisher needs both successful routing and a confirm for a persistent message sent to a durable queue. A broker can also confirm an unroutable publish. Use mandatory publishing or an equivalent routing check, and treat a returned message as failed acceptance. A consumer acknowledgment reports later processing on the worker side. RabbitMQ acknowledgments and publisher confirms

An acceptance response can get lost on the way back to the browser. To let the browser retry safely, give each export request a client-generated request key and enforce one job per account and request key in the same durable write that saves job 47. The API uses the key to find the same job on a retry. If the browser reuses the key with different filters, the API rejects the request. The worker faces a different retry when the queue delivers the accepted job again.

The same job can run again

Suppose worker A saves result 47 and crashes before its acknowledgment reaches the queue. The Results DB has the CSV. The queue still sees an unfinished attempt. At 12:00:30, attempt 1 expires and job 47 becomes eligible again. Worker B takes attempt 2 through 12:01:00.

B uses the export parameters saved with job 47. If the CSV must reflect the data as it was when the API accepted the job, save a reference to a snapshot, a frozen view of that data, with those parameters. Then both workers have the same inputs even if the sales report changes in the meantime.

The worker inserts the result only if the Results DB has no row for that job ID. The database enforces that rule with a unique key, so two attempts racing to insert can leave only one row. B finds that result 47 already exists, leaves it in place, and acknowledges attempt 2. The queue marks job 47 as done. This is an idempotent write. Repeating it has the same effect as doing it once. PostgreSQL conditional insert

Acknowledge before saving and a crash can leave a finished job with no result. Save first and the queue can retry a job whose result already exists. In this at-least-once design, the queue retries unacknowledged jobs while they remain eligible, so a worker can receive the same job more than once. The Results DB gives us one saved outcome across those attempts.

The worker may also call a service to send an export-ready notification. Give that operation a key derived from the job ID, such as export-ready:47, and have the notification service use it to recognize a repeated call. The browser request key protects submission to the API. The job-based key protects this specific operation at the service that performs it.

An expired claim can overlap with a slow worker

The same deadline also fires if A pauses for 40 seconds and comes back. In this design, the queue rejects A's late acknowledgment by checking the attempt number against the current claim. A and B can still overlap while doing the work. In the CSV example, both use the same job ID at the Results DB and the first result wins. If only the current worker may change a shared record, the store that accepts the change must check ownership as part of the write. A separate check at the queue leaves time for the claim to expire before the write reaches the store.

Workers can renew claims when they need more time. A short deadline speeds up recovery from a crash but increases the chance of retrying slow work. A long deadline keeps crashed jobs waiting. Amazon SQS uses a visibility timeout to hide a received message temporarily. A standard queue can still redeliver, and a successful delete response with an old receipt handle may leave the message in the queue. If a job fails on every attempt, set a retry limit and keep the failed job for inspection. Otherwise a bad job can spend worker time indefinitely. Amazon SQS visibility timeout · Amazon SQS DeleteMessage

Which order does the user need?

Suppose job 47 takes 20 seconds and job 48 takes two. Two workers can claim them in arrival order and still publish result 48 first. Exports in our example are independent, so the jobs can run concurrently. If jobs update the same report in sequence, we can route jobs for that report together and let the later update wait for the earlier one to finish. Work for other reports can still proceed. Now a slow or repeatedly failing job delays later updates to that report. The requirement to preserve the order of changes is what earns that cost.

Choose who should get each message

For exports, any available worker can build job 47. Now suppose the reporting app has a live dashboard on two screens. When an export is ready, both screens want the update. We can send event 101, a message that says something happened, through publish/subscribe, or Pub/Sub. Each connected screen subscribes to the channel and gets a copy. With live-only delivery such as Redis Pub/Sub, an offline screen can miss event 101. On reconnect, the app can read the current export status from the Results DB. Redis Pub/Sub delivery semantics

An analytics service may need to read every export-ready event after an outage. A retained log keeps messages after readers have read them, so they can resume or replay while those messages remain available. Kafka divides a log into partitions, each with an ordered sequence of records. The offset identifies a record's position within a partition. It belongs to the log. Event 101 is the message stored in the record at offset 42. The next record, at offset 43, holds event 102.

Each consumer group, a pool of processes reading the log together, can save its own position for each partition. Group A resumes at 42, so it reads event 101 and then event 102. Group B resumes at 43 and reads event 102. Both can revisit the entries while the log retains them. Kafka introduction · Kafka consumer positions

A log also works for sharing work. In Kafka, each partition is assigned to at most one member of a consumer group at a time. Within the group the consumers split the partitions. Kafka gives us record order within one partition. Application code decides whether to finish work in that order.

Suppose group A reads both events and saves position 44 before recording the effect of event 101. After a crash, it resumes at 44 and skips the unfinished work. If A saves its position after recording the effects for both events, it may reread them after a crash. The result-store rule we used for job 47 handles those duplicates, this time with the event ID as the key. The group can resume as long as the log still holds the records it needs. Kafka consumer groups and manual offset control

Waiting work can live in a database

In the ChatGPT walkthrough, the gateway saves a turn in PostgreSQL with status pending. The same row records what the user submitted and tells a worker there is something to claim. Workers periodically look for pending turns.

A separate broker presents another problem. Imagine the export worker saves result 47, then crashes before publishing event 101 for the analytics service. The CSV is ready, but the log has no record of the event. A transactional outbox is a database table of messages waiting to be published. The worker saves the result and an outbox row for event 101 in the same transaction, so the database commits both changes together. A separate process reads the outbox and publishes the event. If it crashes after publishing and tries again, the consumer uses event 101 to recognize the duplicate. AWS transactional outbox pattern

See also

  • Idempotency explains how to make a retry safe at the API or result store.
  • Redis compares live Pub/Sub with Redis Streams, which keep entries for later reads.
  • Kafka goes deeper on retained partitions, groups, and offsets.
  • Transactional Outbox walks through recovering a publication after a database commit.
  • Backpressure and Load Shedding explains what to do when jobs arrive faster than workers can finish them.

Used in

  • ChatGPT saves pending work as a PostgreSQL turn the worker can claim.
  • Batched Inference Service resumes from a saved Kafka position after a Batcher crash and uses the request ID to deduplicate results.
  • Group Chat with Threads delivers live notifications over Redis Pub/Sub and uses PostgreSQL to catch up after reconnect.

Done reading? Mark it so it sticks in your dashboard.

Discussion