← All guidesCodex for Backend Engineering · Future with Shivank
Hands-on guide

21. Messaging with RabbitMQ

Build Part 6. Approve both slices: first the auction close worker with its transactional outbox, then RabbitMQ → notification worker → popup modals. Review the code while Codex works, and finish with a bidding war that ends in “Congratulations” for the winner and “Your auction has closed” for the seller.

Part 6 · build≈ 40–60 min hands-onRabbitMQ + 2 workersWeb http://localhost:5106

What you'll do

Before you start

⚙ Codex settings for this guide
Project / folderworkshop
ModelGPT-5.6 Sol
ReasoningMedium
ModeNormal chat (the main chat from guide 20)
ApprovalsApprove for me
📘 Concept: worker processes

Until Part 5 our backend was one program: the API server. From Part 6 it is three. A process is simply one running program with its own memory. The API process answers HTTP requests and holds the WebSocket connections. The close worker process does nothing but poll the database and close auctions. The notification worker process does nothing but read messages from RabbitMQ and push popups. They share the same codebase (all three live in server/src/) and the same database, but each one can be started, stopped, crashed and restarted on its own. That is why npm start now prints four prefixes in the log: one per process, plus the web app.

1

Approve Slice 1

Send a short approval, in the same style as our Part 4 approval in guide 18. Codex has the whole design in GRILL.md and the ADR, so it needs nothing more than a clear yes for Slice 1 only. While it works, which takes a while, read the two concept boxes below; they explain what RabbitMQ is doing under the hood.

✦Paste into CodexMain chat · same thread as guide 20
go for slice 1
📘 Concept: exchange, routing key, queue, ack

Inside RabbitMQ a message does not go straight into a queue. The producer sends it to an exchange, a kind of sorting office, together with a routing key, a short label such as auction.closed. The exchange looks at the key and copies the message into every queue that has asked for messages with that key (this is called a binding). A consumer reads from a queue, one message at a time. When it has finished the work it sends an ack; only then does RabbitMQ delete the message. If the consumer dies before acking, the message goes back on the queue and is delivered again. In our project Codex declares one exchange (auction.events in the reference copy) and one queue (auction.notifications) bound to it. You will see both in the dashboard in step 7.

📘 Concept: loose coupling (why not just call the other service?)

The obvious alternative is for the close worker to call the notification service directly over HTTP: “hey, auction 42 closed, go notify people”. That builds a chain: for a close to succeed, the notification service must be up, reachable and fast at that exact moment. Add two more services to the chain and the whole feature breaks whenever any one of them is restarting. A queue works like a post office: the close worker drops the letter and walks away, and the notification worker collects it whenever it is ready, even if that is ten seconds later after a restart. Neither service needs to know the other's address or whether it is alive. This is loose coupling, and it is the main reason real systems put a queue between workers.

✓ You should see

Similar to: “I'll first normalize Part 6's copied configuration and map the existing query/test seams, then implement and run the required backend, frontend, typecheck, and browser verification before stopping for your review.” A progress pill above the message box counts up, for example Step 2 / 5 · 21 files changed +563 −32. Along the way Codex explains it is using a dedicated auction_closes table plus a uniquely keyed outbox_events row created in the same transaction, and that the worker will lock due auction rows with SKIP LOCKED. Those three phrases are the design from guide 20, now becoming code.

⚠ Heads up

Two build slices in a row is the most expensive part of this guide. Each can run 10 minutes or more on Sol. Do not switch models mid-slice; let it finish.

2

Review Slice 1's code while it works

You do not have to sit and watch the progress pill. Open the review panel (the icon at the top right, or Review on the edited-files card) and set the dropdown at its top to Last Turn, so you see only the files changed in this run. The list grows as Codex works. Here is what I check, in this order:

  • 002_auction_closes_outbox.sql in server/migrations/: the two new tables, auction_closes and outbox_events.
  • server/src/auctionClose.ts: the heart of the slice. It claims due auctions with FOR UPDATE OF a SKIP LOCKED, inserts one row into auction_closes and one into outbox_events, then COMMIT. That is the transactional outbox from guide 20: close and event in one transaction, so you can never have one without the other.
  • server/src/close-worker.ts: the separate polling process. A loop with a one-second sleep that calls the function above.
  • server/src/app.ts: the API now returns the winning-bid fields on an auction, read from the close row.
  • tests/bidding-war.spec.ts: updated to point at the Part 6 URL and database, so the war from Part 4 still runs here.
📘 Concept: migration and SKIP LOCKED

A migration is a numbered SQL file that changes the database's structure: create a table, add a column. They run in order (001, 002, 003…) on every machine, so everyone's database ends up with the same shape. Codex adds 002_… because Part 4 already had 001. SKIP LOCKED is a PostgreSQL option on a locking SELECT: “give me the due auctions, but if another transaction is already holding one of those rows, skip it instead of waiting”. The result is that you can run two or three close workers at once and they will never fight over the same auction, nor block each other. One line of SQL, and the worker is safe to scale.

✓ You should see

Mostly green (new) lines. A migration similar to:
CREATE TABLE auction_closes (auction_id … PRIMARY KEY, closed_at …, winning_bid_id … UNIQUE REFERENCES bids(id))
CREATE TABLE outbox_events (id uuid PRIMARY KEY, event_type …, payload jsonb …, published_at timestamptz, UNIQUE (event_type, auction_id))

Read the constraints: auction_id … PRIMARY KEY means an auction can be closed only once. UNIQUE (event_type, auction_id) means there can be only one AuctionClosed event per auction. published_at being empty is how the publisher knows a row still needs sending. The database itself enforces “one close, one event”, which is idempotency at the first boundary.

💡 Tip

I like that the winning bid is stored on the close row (winning_bid_id) rather than recomputed from the bids table every time someone opens the page. A close is a historical fact; store it. And the polling worker? Is it a perfect architecture? Maybe not. Will it keep working reliably for years? Yes. Simple and boring beats clever here.

3

Queue “go ahead on slice 2”

Watch the progress messages. When Codex reports Slice 1's tests passing (it says something like “The full regression suite is green”), I am confident enough to type the next instruction while Codex is still working and press Enter. Codex does not interrupt itself; it holds the message and sends it the moment the current turn ends. This saves you from staring at the screen waiting for the exact second it finishes.

✦Paste into CodexMain chat · while Slice 1 is still running
go ahead on slice 2

Why this matters: it is a judgement call. Queuing means you trust the tests more than your own browser check for this slice. I do that here because Slice 1 is backend-only (tables and a worker) and its tests are exactly the ones that matter: concurrency and idempotency. For Slice 2, which has a visible UI, I do not queue; I look at it first.

✓ You should see

First Slice 1 finishes: “Slice 1 is complete and verified in Part 6.” It shows a Mermaid diagram (⏱️ Auction Close Worker polls due auctions every second → 🐘 PostgreSQL auctions, closes, outbox; ⚡ Fastify API reads the authoritative outcome; 🌐 Web App refreshes after the deadline) and an “Edited 23 files” card. Then your queued message is sent automatically and Codex starts Slice 2 (“Designing notification delivery migration and idempotent emission…”).

💡 Tip

Prefer to check Slice 1 in the browser first? Then don't queue. Wait for Codex's review steps, try them (step 6 shows how to run Part 6; at this stage you would only see the auction show as ended after the deadline, with no popup yet), then send this message. If your Codex version does not hold messages typed during a run, simply send it after the turn ends.

4

Review Slice 2's code

Same review panel, Last Turn again, which now shows only Slice 2's files. New pieces to look at:

  • 003_notification_deliveries.sql in server/migrations/: a table with one row per event and recipient, with UNIQUE (outbox_event_id, recipient_user_id). This is the idempotent consumer from guide 20 made real: if RabbitMQ redelivers the same event, the second insert for the same recipient fails the unique check, so no second popup.
  • server/src/close-worker.ts: the close worker now also publishes pending outbox rows to RabbitMQ on a confirm channel, meaning it waits for RabbitMQ's “got it” before setting published_at.
  • server/src/notification-worker.ts: the separate process that consumes from RabbitMQ, decides the recipients, and emits through Redis to Socket.IO.
  • server/src/notificationDelivery.ts: INSERT … ON CONFLICT DO NOTHING, then emit. “On conflict do nothing” is PostgreSQL for “if this row already exists, skip quietly instead of throwing an error”. Insert first, emit second: if the insert was skipped, there is nothing to emit.
  • tests/outcome-notification.spec.ts: the multi-window Edge check that opens seller, winner and an unrelated user and asserts who gets a modal.
  • web/src/…/OutcomeModal.tsx: the React component for the popup itself, with the dismiss button and the three text variants.
✓ You should see

Codex works through Step 1 / 6 → 6 / 6 (about 23 files changed, roughly +1,000 lines). It ends with “Slice 2 is complete and verified”, lists key files like outboxPublisher.ts, notification-worker.ts, realtime.ts and OutcomeModal.tsx, and gives review steps similar to: “To review, run npm start, open several windows at http://localhost:5106, select seller/winner/unrelated users, and let a short auction end. Seller and winner sessions receive the appropriate modal; unrelated and offline users do not.”

💡 Tip

Trace one message through the files in your head: close worker writes outbox row → publisher sends it to the exchange and marks published_at → queue → notification worker reads it → inserts delivery rows (unique) → emits to Socket.IO rooms via Redis → browser shows OutcomeModal. If you can tell that story, you understand Part 6.

5

Run the bidding war

It isn't verified until bidding wars. This time the war has a new ending: after the countdown, the close worker should close the auction, the message should travel through RabbitMQ, and two of the four windows should get a modal. Stop any npm start you have running for Part 6 (Ctrl+C in Terminal) so the test can start its own servers, then send:

✦Paste into CodexMain chat
BIDDING WARS, it ain't verified until bidding wars bayyyy
✓ You should see

“You're right. Slice 2 doesn't get the victory lap without the four-window war.” Four Edge windows tile the screen at localhost:5106/items/bidding-war-gpu-… (SELLER · AVERY, BIDDER 1 · MAYA, BIDDER 2 · THEO, BIDDER 3 · PRIYA). Bids climb, every window shows ENDED with a final outcome like “@priya won with $107”, and then, a few seconds later:

  • the seller's window shows a modal “Auction ended — Your auction has closed”: “Your auction for BIDDING WAR GPU … ended. Priya Shah won with $107.” with Dismiss and View auction buttons
  • the winner's window shows “Congratulations”: “You won BIDDING WAR GPU … with a bid of $107.”
  • the two losing bidders get no modal, exactly as decided in guide 20

The few seconds of delay are real: up to one second for the poll, then the publish, then the consume. That is the cost of loose coupling, and for a notification it is perfectly fine.

💡 Tip

No Edge installed? Tell Codex to run the headed bidding war in Google Chrome instead (see guide 18, step 8). If the windows show ENDED but no modal ever appears, do not guess; go to step 6 and read the worker logs.

6

Run Part 6 yourself in Chrome

The war proves it works for the test's users. Now try the close workflow by hand, with an auction you create. First start everything:

❯Run in TerminalTerminal app · leave it running
cd ~/codex-course/workshop/part-6-async-close-rabbitmq
npm install
npm start

Line by line: cd into the Part 6 folder; npm install fetches the new packages, including the RabbitMQ client library (amqplib) Codex added; npm start brings up the three containers, runs migrations 001–003 on auction_part_6, then starts the four processes. Leave this Terminal window open. Then:

  1. Open the web URL Codex gave you (in my run http://localhost:5106). In this window, click Sell in the top navigation and post an auction with a closing time about 2 minutes from now. The form insists on at least 1 minute, and 2 gives you time to set up the second window.
  2. Copy the new auction's address and open it in a second Chrome window (Cmd+N). This window gets a different random demo user. If it happens to be the same user as the seller, switch to another one with the footer switcher. Place a bid.
  3. Arrange the two windows so you can see both, and wait for the deadline. Watch the Terminal too: within a second of the deadline you should see a [close-worker] line, then a [notification-worker] line.
✓ You should see

Terminal shows the postgres, redis and rabbitmq containers as healthy, migrations applied, then interleaved logs from four processes (in my version prefixed [api], [close-worker], [notification-worker], [web]). A few seconds after the deadline, both pages show the auction as ended, with no reload. The seller window shows “Your auction has closed” and the bidder window shows “Congratulations”. Each modal stays on screen until you click Dismiss; clicking elsewhere does nothing, which is the dismiss-required behaviour you asked for.

💡 Tip

Nothing pops up? Work backwards along the chain. Does the Terminal show a [close-worker] log line at the deadline? If not, the poll is not running. Does it show a [notification-worker] line? If not, check that the rabbitmq container is running in Docker Desktop. If both lines are there but no modal, the problem is between Redis and the browser; check the browser's address matches the API's port. In every case, paste the exact error line into the Codex chat and let it debug with you.

Stop the servers with Ctrl+C when done. The containers keep running in Docker; that is fine.

7

Optional: look inside RabbitMQ

This step makes the exchange-and-queue concepts from step 1 concrete. RabbitMQ ships with a web dashboard called the management UI. With Part 6 still running (npm start from step 6), open the address below and log in with username auction and password auction. Those credentials come from the root docker-compose.yml; they are for your local container only.

↗Open in browserChrome · Part 6 must be running
http://localhost:15676
✓ You should see

The RabbitMQ dashboard with an Overview graph. The Exchanges tab lists the exchange Codex declared (in the reference copy it is auction.events) alongside RabbitMQ's built-in ones. The Queues and Streams tab lists the notification queue (auction.notifications in the reference) with 1 consumer, which is your Notification Worker, connected and waiting. Click the queue to see its bindings to the exchange. Now create and close another short auction as in step 6 and watch the message-rate graph: a small blip of one published and one delivered message, then the “Ready” count returns to 0 because the consumer acked it.

💡 Tip

If the page does not load, your Codex may have set RabbitMQ up with a different port or user. Ask it in the chat: “what is the RabbitMQ management URL and login for Part 6?” If you stop the notification worker (Ctrl+C the whole npm start) and close an auction with only the containers running, you would see the message sit in the queue as “Ready”; that is the post office holding the letter.

8

Commit Part 6

Both slices are built and verified. Commit with the short message “part 6”. First stop npm start with Ctrl+C in its Terminal window, then:

❯Run in TerminalTerminal app · workshop folder
cd ~/codex-course/workshop && git add -A && git commit -m "part 6"

As always: go to the workshop root, stage every change (git add -A), save the snapshot with a message. From guide 22 onwards we start using Git more seriously (worktrees, pull requests), so having each part as one clean commit will pay off.

✓ You should see

A commit summary listing part-6-async-close-rabbitmq/… files, including docs/adr/0001-…, server/migrations/002_… and 003_notification_deliveries.sql, server/src/close-worker.ts and server/src/notification-worker.ts. If you also see part-7-winner-checkout changes, you forgot step 8 of guide 20; run that command first and commit again.

Stuck or got a very different result?

A slice won't go green, or you want to skip ahead? Replace your Part 6 with the finished reference version. The reference folder is the end state of the whole part: both slices, with GRILL.md, CONTEXT.md and the ADR. After copying, run it with npm install && npm start inside the Part 6 folder and open http://localhost:5106 to confirm the modals appear.

❯Run in TerminalTerminal app · catch up: Part 6
cd ~/codex-course/workshop && rm -rf part-6-async-close-rabbitmq && cp -R ../reference/part-6-async-close-rabbitmq ./ && git add -A && git commit -m "Catch up: part 6 from reference"

What it does: deletes your Part 6 folder, copies the reference Part 6 in its place, stages and commits. Skip step 8 afterwards, because this already commits.

Other common problems: npm start fails on the RabbitMQ container → Docker Desktop is not running, or port 56726 is taken by an old container (check Docker Desktop's Containers tab). Modals appear twice → your consumer is not idempotent; ask Codex to check the unique constraint on notification_deliveries. Only the winner gets a modal, not the seller → re-read your round 1 answer 7 in GRILL.md and ask Codex to add the seller recipient.

Key takeaways