20. Fullstack Backend Engineering with Codex#
A fast, conceptual revision guide for 04-codex. Covers both how to direct an AI coding agent with engineering discipline (grilling, vertical slices, AGENTS.md, context hygiene, cross-model reviews, /goal, worktrees) and the real backend architecture built across Parts 1–8 of the Auction House app (PostgreSQL row locking, Redis + Socket.IO real-time fan-out, RabbitMQ transactional outbox, Stripe-style webhooks, and OpenTelemetry + Jaeger tracing).
Codex as a Coding Agent, Thinking Levels & Cost Control#
Revision Notes#
Reference files: codex-project-notes/1. Introduction.html, 2. Codex Overview.html, 3. Thinking Levels.html
Concept#
Strip away the desktop UI and every coding agent is the same four primitives: a loop + an LLM + filesystem access + command-line access. Unlike a chatbot that only generates text, a coding agent reads files, edits code, runs tests, inspects errors, and iterates until it believes the job is done. The core engineering skill is not "vibe coding" — it is directing the agent, controlling cost and risk, and verifying every claim.
Key Mental Models#
- Model vs. Effort vs. Speed:
- Model is which brain you use (e.g., strongest tier like Sol for planning, architecture, and reviews; smaller tiers like Terra/Luna for simple, bounded tasks).
- Effort (reasoning level) controls how many hidden reasoning tokens the model spends thinking before acting. Higher effort helps on hard design/debugging problems but wastes tokens and causes overthinking on simple tasks.
- Speed only affects latency, not answer quality.
- Tests as guardrails for cheaper models: A high-leverage workflow is letting a strong model plan and write the automated tests, then delegating implementation to a cheaper model. Passing tests act as back pressure that catches mistakes before you review.
- Sub-agents (
Ultra): Splits large independent tasks across parallel sub-agents managed by a lead agent — powerful for massive jobs, but very token-hungry and unnecessary for small vertical slices. - Approvals & API safety:
- Use Approve for me for routine local dev commands, and never grant Full access on a machine you care about.
- With API-key billing, always set both a hard monthly budget (caps spend) and an email alert (early warning before a task gets halted mid-run).
- Custom instructions vs.
AGENTS.md: Custom instructions live in your Codex user settings and apply silently to every chat across all projects;AGENTS.mdlives inside a repository and scopes rules to that codebase.
Tech Stack, Vertical Slices & Agent Guardrails (`AGENTS.md` & Skills)#
Revision Notes#
Reference files: codex-project-notes/4. Specifying a Tech Stack.html – 7. Create Auctions & Bids Site.html, codex-project-code/AGENTS.md, codex-project-code/docker-compose.yml, codex-project-code/part-1-foundation/
Concept#
Never let an AI agent silently pick your tech stack — you are the one who must maintain and debug the result. Instead, lock down a clear stack, build in vertical slices rather than horizontal layers, and encode non-negotiable conventions in AGENTS.md and reusable skills (SKILL.md).
Key Mental Models#
- Fixed fullstack architecture:
- Application layer: TypeScript across the stack, React + Vite (frontend), Fastify (API), Zod (boundary input validation), Socket.IO (real-time), Playwright (E2E browser verification).
- Infrastructure in Docker Compose: PostgreSQL (primary database), Redis (pub/sub backplane), RabbitMQ (async messaging), Jaeger (distributed tracing). Each part (
part-1throughpart-8) runs on its own ports and isolated Postgres database so parts can run side by side as "before/after" snapshots.
- Vertical slices over horizontal layers:
- A vertical slice cuts through every layer at once (DB migration + API endpoint + React UI + automated tests) to deliver one complete, browser-reviewable behavior.
- Part 1 (
part-1-foundation) proves the thinnest possible slice:React → Fastify → Postgresvia/api/health. Always verify the health chain first before debugging higher layers.
- Curating
AGENTS.mdlike a garden:- Codex reads
AGENTS.mdautomatically at the start of every chat — it is the primary lever for making a non-deterministic agent behave predictably. - Keep constraints, canonical commands, verification checklists, and architecture rules; delete descriptions of current file state that quickly go stale.
- To share one source of truth with Claude Code, put
@AGENTS.mdinsideCLAUDE.md.
- Codex reads
- Custom skills (
SKILL.md): Reusable slash-command workflows stored in~/.agents/skills(such as/grill-me/grill-with-docsand Playwright browser skills) so you do not retype complex prompt templates. - Browser use puts you in the reviewer's chair: Running headed Playwright (visible Chrome/Edge windows) lets you watch real user flows instead of trusting an agent's text summary.
Code Reference#
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_USER: auction
POSTGRES_PASSWORD: auction
POSTGRES_DB: postgres
# Map to non-default host port 55432 to avoid colliding with a local Postgres instance.
ports:
- "55432:5432"
# Healthcheck lets dependent setup scripts wait until Postgres accepts SQL connections.
healthcheck:
test: ["CMD-SHELL", "pg_isready -U auction -d postgres"]
interval: 2s
timeout: 5s
retries: 10
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
# Disable RDB snapshots and AOF persistence: Redis is used only for ephemeral pub/sub & cache.
command: ["redis-server", "--save", "", "--appendonly", "no"]
# Bind to loopback (127.0.0.1) so local dev services are not exposed on the LAN.
ports:
- "127.0.0.1:56379:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 2s
timeout: 5s
retries: 10
rabbitmq:
image: rabbitmq:4-management-alpine
environment:
RABBITMQ_DEFAULT_USER: auction
RABBITMQ_DEFAULT_PASS: auction
# 56726 = AMQP broker port; 15676 = web management UI for inspecting queues and DLQs.
ports:
- "127.0.0.1:56726:5672"
- "127.0.0.1:15676:15672"
# RabbitMQ boots slower than Redis/Postgres, so allow up to 20 retries (40s).
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 2s
timeout: 5s
retries: 20
volumes:
- rabbitmq_data:/var/lib/rabbitmq
jaeger:
image: jaegertracing/all-in-one:1.76.0
environment:
# Whitelist every multi-bidder dev origin (including subdomains) so browser OTLP spans pass CORS.
COLLECTOR_OTLP_HTTP_CORS_ALLOWED_ORIGINS: "http://localhost:5106,http://127.0.0.1:5106,http://bidder-two.localhost:5106,http://bidder-three.localhost:5106,http://localhost:5107,http://127.0.0.1:5107,http://bidder-two.localhost:5107,http://bidder-three.localhost:5107,http://localhost:5108,http://127.0.0.1:5108,http://bidder-two.localhost:5108,http://bidder-three.localhost:5108"
COLLECTOR_OTLP_HTTP_CORS_ALLOWED_HEADERS: "Content-Type"
# Enable OTLP receiver so Node/browser OpenTelemetry SDKs can push traces directly to Jaeger.
command:
- "--collector.otlp.enabled=true"
# 16686 = Jaeger UI; 4318 = OTLP/HTTP trace ingestion endpoint.
ports:
- "127.0.0.1:16686:16686"
- "127.0.0.1:4318:4318"
# Port 14269 is Jaeger's internal admin/health endpoint.
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:14269/"]
interval: 2s
timeout: 5s
# ... (see full file: docker-compose.yml)
$ docker compose up -d
[+] Running 5/5
✔ Network codex-project-code_default Created 0.1s
✔ Container codex-project-code-postgres-1 Healthy 3.4s
✔ Container codex-project-code-redis-1 Healthy 2.6s
✔ Container codex-project-code-rabbitmq-1 Healthy 9.8s
✔ Container codex-project-code-jaeger-1 Healthy 2.9s
$ docker compose ps --format "table {{.Service}}\t{{.Status}}\t{{.Ports}}"
SERVICE STATUS PORTS
jaeger Up 14 seconds (healthy) 127.0.0.1:4318->4318/tcp, 127.0.0.1:16686->16686/tcp
postgres Up 14 seconds (healthy) 0.0.0.0:55432->5432/tcp
rabbitmq Up 14 seconds (healthy) 127.0.0.1:56726->5672/tcp, 127.0.0.1:15676->15672/tcp
redis Up 14 seconds (healthy) 127.0.0.1:56379->6379/tcp
Plan Mode, Grilling, ADRs & Context Hygiene#
Revision Notes#
Reference files: codex-project-notes/8. Plan Mode & Grilling.html – 10. Bidding & Constraints.html, codex-project-code/part-2-create-auction-and-bid/ (GRILL.md, AGENTS.md)
Concept#
When you jump straight into coding, an agent silently makes dozens of architectural assumptions that only surface later as bugs. Grilling flips the workflow: the agent interviews you in structured rounds (with options and recommendations) before writing code, locking decisions into durable docs (GRILL.md, CONTEXT.md, ADRs) where changing your mind is free.
How It Works#
Key Mental Models#
- Plan mode vs. Grilling:
- Built-in Plan mode is read-only and produces a plan mostly from the model's assumptions.
- Grilling (
grill-with-docs) forces explicit human decisions on edge cases, records them next to the code, and decomposes work into 2–4 browser-reviewable vertical slices. - Read every question: accept recommendations when sensible, override them when your domain knowledge disagrees, and say no to premature complexity.
- Core backend fundamentals established in Part 2:
- Money as integer cents (
_cents): Never use floating-point dollars due to binary rounding errors. - Timestamps in UTC (
TIMESTAMPTZ): Store all deadlines and events in UTC; format for local time only in the UI. - Plain parameterized SQL over ORMs: Writing explicit SQL migrations and
$1, $2parameterized queries keeps database behavior transparent (critical for concurrency) and prevents SQL injection. - Enforce every business rule in the API, not only the browser: UI checks are for UX; the API must validate inputs with Zod and enforce rules (e.g., sellers cannot bid on their own auction, minimum increment, closed auction) returning
409 Conflictwhen violated.
- Money as integer cents (
- Review hierarchy: Inspect the database schema/migrations first (tables, types,
_cents), then diffs and test names, then verify in a real browser. Commit after every slice so each diff stays small and reviewable. - Context window hygiene:
- Every turn resends the entire chat history as tokens. Long chats get slower, pricier, and cause the agent to drift.
- Compact at natural pauses, use side chats as temporary scratch paper for questions that should not pollute main context, and start a new chat per task (relying on
AGENTS.md,GRILL.md, and ADRs for long-term memory).
Code Reference#
import { randomUUID } from 'node:crypto';
import Fastify from 'fastify';
import pg from 'pg';
import { z } from 'zod';
// Fall back to the local Docker Compose Postgres instance for Part 2's isolated database.
const connectionString = process.env.DATABASE_URL ?? 'postgres://auction:auction@localhost:55432/auction_part_2';
// Validate query/path params at the HTTP boundary before touching SQL.
const listQuerySchema = z.object({ q: z.string().trim().max(100).optional() });
const slugParamsSchema = z.object({ slug: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/) });
const categorySchema = z.enum(['GPUs', 'CPUs', 'Memory', 'Chassis', 'Networking', 'Cooling']);
// Enforce domain invariants with Zod: integer cents avoid floating-point money bugs,
// and the refine check ensures an auction cannot be created already expired or closing immediately.
const createAuctionSchema = z.object({
userId: z.number().int().positive(),
title: z.string().trim().min(3).max(120),
category: categorySchema,
description: z.string().trim().min(10).max(4000),
condition: z.string().trim().min(2).max(100),
location: z.string().trim().min(2).max(100),
startingPriceCents: z.number().int().positive().max(1_000_000_000),
endsAt: z.string().datetime({ offset: true }),
}).refine((auction) => Date.parse(auction.endsAt) > Date.now() + 60_000, {
message: 'Closing time must be in the future',
path: ['endsAt'],
});
const createBidSchema = z.object({
userId: z.number().int().positive(),
amountCents: z.number().int().positive().max(1_000_000_000),
});
// Map display categories to frontend artwork asset keys.
const artByCategory = {
GPUs: 'gpu',
CPUs: 'cpu',
Memory: 'memory',
Chassis: 'chassis',
Networking: 'switch',
Cooling: 'cooling',
} as const;
// Produce URL-safe slugs: NFKD decomposes accents so diacritics can be stripped cleanly,
// and fallback to 'auction' if the title had only punctuation.
function slugify(title: string): string {
return title.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase()
.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 80) || 'auction';
// -> 'NVIDIA RTX 4090 Founders Edition' -> 'nvidia-rtx-4090-founders-edition'
}
// Mirrors the joined SQL projection returned by auction listing and detail queries.
type AuctionRow = {
slug: string;
title: string;
kicker: string;
category: string;
art: string;
current_price_cents: number;
bid_count: number;
current_bidder: string | null;
ends_at: Date;
seller_id: number;
seller_display_name: string;
seller_handle: string;
location: string;
condition: string;
description: string;
// ... (see full file: app.ts)
$ curl -s -X POST http://localhost:4002/api/auctions \
-H "Content-Type: application/json" \
-d '{"userId":1,"title":"NVIDIA RTX 4090 Founders Edition","category":"GPUs","description":"Lightly used in climate-controlled rack, original box included.","condition":"Mint","location":"Austin, TX","startingPriceCents":140000,"endsAt":"2026-12-03T18:00:00Z"}' | jq
{
"slug": "nvidia-rtx-4090-founders-edition",
"title": "NVIDIA RTX 4090 Founders Edition",
"category": "GPUs",
"art": "gpu",
"currentPriceCents": 140000,
"bidCount": 0,
"currentBidder": null,
"endsAt": "2026-12-03T18:00:00.000Z"
}
$ curl -s -X POST http://localhost:4002/api/auctions/nvidia-rtx-4090-founders-edition/bids \
-H "Content-Type: application/json" \
-d '{"userId":2,"amountCents":145000}' | jq
{
"slug": "nvidia-rtx-4090-founders-edition",
"currentPriceCents": 145000,
"bidCount": 1,
"currentBidder": "bidder-two"
}
Concurrency, Race Conditions & PostgreSQL Row Locking#
Revision Notes#
Reference files: codex-project-notes/11. Understanding the Concurrency Problem.html – 15. Closing the Auction.html, codex-project-code/part-3-business-rules-concurrency/
Concept#
Sequential tests hide one of the most dangerous backend bugs: the check-then-act race condition. When multiple bidders submit the same amount at the exact same millisecond, separate "read current price → check → insert bid" statements allow all of them to pass the check before any write commits, creating duplicate winning bids. The fix is not "checking more carefully" — it is serializing bids per auction inside a PostgreSQL transaction with a row lock.
How Row Locking Fixes the Race#
Key Mental Models#
- Red before green (reproduction → protection):
- First write a headed 4-window Playwright "bidding war" test that deliberately fires simultaneous bids and reproduces duplicate
$107bids. - Then flip the test into a protection test that fails if any duplicate bid slips through. Passing tests after the fix are proof; an agent's "done" is not.
- First write a headed 4-window Playwright "bidding war" test that deliberately fires simultaneous bids and reproduces duplicate
- Transaction (
BEGIN … COMMIT) + Row Lock (SELECT … FOR UPDATE):- Wraps reading, validating, and inserting into one atomic unit.
- Locking only the single auction row serializes competing bids on that auction without slowing down bids on any other auction.
- Isolation levels trade-off:
- PostgreSQL's default
READ COMMITTEDdoes not stop check-then-act races on its own. SERIALIZABLEdetects conflicts automatically but aborts transactions and requires application-level retry loops. KeepingREAD COMMITTED+ explicitSELECT … FOR UPDATEis simpler, predictable, and needs no retry machinery.
- PostgreSQL's default
- Authoritative closing & Injected App Clock:
- Never call
Date.now()directly inside business rules — you cannot deterministically test1msbefore vs. after closing. - Inject a clock dependency into the API (real system clock in production, fake controllable clock in tests) and read the clock after acquiring the row lock so the close decision and stored timestamp belong to the exact same serialized moment.
- Never call
- Typed
409 Conflict& graceful stale-bid recovery:- Returning machine-readable error codes (
BID_TOO_LOW,AUCTION_CLOSED) lets the frontend refresh the auction cleanly on conflict instead of polling constantly or showing vague errors.
- Returning machine-readable error codes (
Code Reference#
import { randomUUID } from 'node:crypto';
import Fastify from 'fastify';
import pg from 'pg';
import { z } from 'zod';
// Real-time event contract published over Redis/SSE when bids, closes, or payments mutate an auction.
import type { AuctionChangedEvent } from './realtime.js';
// Payment client + HMAC signature verification + Zod payload schema for mock Stripe webhooks.
import {
createMockStripeClient,
type StripeClient,
StripeSessionNotFoundError,
stripeWebhookEventSchema,
verifyStripeSignature,
} from './payments.js';
// Distributed tracing helpers: propagate W3C traceparent across HTTP, RabbitMQ jobs, and Stripe callbacks.
import {
activeTraceparent,
contextFromHeaders,
contextFromTraceparent,
withBusinessSpan,
} from './tracing.js';
const connectionString = process.env.DATABASE_URL ?? 'postgres://auction:auction@localhost:55432/auction_part_8';
const listQuerySchema = z.object({ q: z.string().trim().max(100).optional() });
const slugParamsSchema = z.object({ slug: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/) });
const categorySchema = z.enum(['GPUs', 'CPUs', 'Memory', 'Chassis', 'Networking', 'Cooling']);
// Part 8 drops the >60s refine constraint so cross-stack tests can create fast-closing auctions.
const createAuctionSchema = z.object({
userId: z.number().int().positive(),
title: z.string().trim().min(3).max(120),
category: categorySchema,
description: z.string().trim().min(10).max(4000),
condition: z.string().trim().min(2).max(100),
location: z.string().trim().min(2).max(100),
startingPriceCents: z.number().int().positive().max(1_000_000_000),
endsAt: z.string().datetime({ offset: true }),
});
const createBidSchema = z.object({
userId: z.number().int().positive(),
amountCents: z.number().int().positive().max(1_000_000_000),
});
// Checkout endpoints accept userId either in JSON body (POST) or coerced from query string (GET).
const checkoutBodySchema = z.object({ userId: z.number().int().positive() });
const checkoutQuerySchema = z.object({ userId: z.coerce.number().int().positive() });
// -> parses query string { userId: '2' } -> { userId: 2 }
const artByCategory = {
GPUs: 'gpu',
CPUs: 'cpu',
Memory: 'memory',
Chassis: 'chassis',
Networking: 'switch',
Cooling: 'cooling',
} as const;
function slugify(title: string): string {
return title.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase()
.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 80) || 'auction';
}
type AuctionRow = {
slug: string;
title: string;
// ... (see full file: app.ts)
$ curl -s -X POST http://localhost:4008/api/auctions/rtx-4090-fe/checkout \
-H "Content-Type: application/json" \
-H "traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" \
-d '{"userId":2}' | jq
{
"sessionId": "cs_test_9c8f1a2b",
"checkoutUrl": "http://localhost:4242/checkout/cs_test_9c8f1a2b",
"status": "open",
"amountCents": 145000
}
# After mock-stripe delivers signed POST /api/webhooks/stripe with the same traceparent:
# HTTP/1.1 200 OK
# {"received":true,"auctionSlug":"rtx-4090-fe","paymentStatus":"paid"}
Code Reviews, Cross-Model Blind Spots & Defect Investigation#
Revision Notes#
Reference files: codex-project-notes/16. Code Reviews with Codex & Claude.html, 19. Finding a Concurrency Defect.html, codex-project-code/part-5-hidden-defect-review/
Concept#
Code written by an AI agent must be reviewed with the same rigor as a teammate's code. A model reviewing its own output often shares the same blind spots, and concurrency defects are invisible to standard unit tests — making independent cross-model reviews, clean commit diffs, and targeted debugging prompts essential engineering habits.
Key Mental Models#
- Clean review mechanics:
- Commit before reviewing, then run
/review last commitin a fresh chat so the reviewer evaluates only the diff without memory of how the code was written. - Triage by severity:
P1= real bug/data-loss risk (fix before shipping);P2= worth improving, not blocking. Severity badges are opinions — the human decides what matters. - Use the strongest model for reviews; a weak reviewer that misses a real bug creates dangerous false confidence. Pairing two different models (e.g., Codex + Claude) catches defects neither finds alone.
- Commit before reviewing, then run
- The
FOR UPDATEvs.FOR SHAREconcurrency defect (part-5-hidden-defect-review):SELECT … FOR UPDATEis an exclusive lock ("I am modifying this row; everyone else wait").SELECT … FOR SHAREallows multiple concurrent transactions to read the same row simultaneously — changing a single word silently breaks duplicate-bid protection while every sequential test still passes.
- Prescriptive vs. vague debugging prompts:
- A vague prompt ("find the bug") lets an agent take shortcuts (such as diffing against
part-4or reading Git history). - A prescriptive prompt constrains the method and off-limits folders when testing an agent's true reasoning — and in real production debugging, you flip that strength in your favor ("reproduce the bug first, then inspect Git history to find the regression").
- A vague prompt ("find the bug") lets an agent take shortcuts (such as diffing against
- Model sizing & credential boundaries:
- Smaller models (like Luna) are fast and cost-effective for focused detective work in a small codebase; reserve top models for planning and multi-file builds.
- Give agents broad database/tool access only on local dev/Docker containers — never production or cloud-admin credentials.
Code Reference#
// Injectable clock/timer interface so unit tests can advance time deterministically without real sleeps.
export type AuctionCloseRefreshEnvironment = {
now(): number;
setTimeout(callback: () => void, delayMs: number): number;
clearTimeout(timer: number): void;
};
// Default runtime adapter bound to the browser's global clock and timers.
const browserEnvironment: AuctionCloseRefreshEnvironment = {
now: () => Date.now(),
setTimeout: (callback, delayMs) => window.setTimeout(callback, delayMs),
clearTimeout: (timer) => window.clearTimeout(timer),
};
// Ensures the UI learns the final close outcome even if an SSE/realtime close event is missed
// or the backend worker finishes closing the auction slightly after `endsAt`.
export function watchAuctionCloseOutcome(
endsAt: string,
closedAt: string | null,
refresh: () => Promise<void>,
environment: AuctionCloseRefreshEnvironment = browserEnvironment,
): () => void {
// Already closed on the server — no polling needed; return a no-op disposer.
if (closedAt) return () => undefined;
let stopped = false;
let timer: number | null = null;
const deadline = Date.parse(endsAt);
// -> epoch ms for '2026-12-02T14:00:05.000Z'
const schedule = (delayMs: number) => {
timer = environment.setTimeout(() => {
timer = null;
// Swallow transient network errors so a single failed fetch never kills the retry loop,
// then poll every 1s until the caller sees `closedAt` and invokes the cleanup callback.
void refresh().catch(() => undefined).finally(() => {
if (!stopped) schedule(1_000);
// -> retries 1s later (e.g. 14:00:06.018Z) until closedAt is set & cleanup runs
});
}, delayMs);
};
// Sleep until the exact auction deadline (or fire immediately if already past `endsAt`).
schedule(Math.max(0, deadline - environment.now()));
// -> at 14:00:00.000Z: Math.max(0, 5000) = 5000 ms (fires at 14:00:05.000Z)
// Return a React useEffect-compatible cleanup function that halts any future retry.
return () => {
stopped = true;
if (timer !== null) environment.clearTimeout(timer);
};
}
// Example usage in a React effect or test harness:
const stopWatching = watchAuctionCloseOutcome(
'2026-12-02T14:00:05.000Z',
null,
async () => {
const auction = await fetchAuction('rtx-4090-fe');
console.log('refreshed closedAt:', auction.closedAt);
if (auction.closedAt) stopWatching();
},
);
// Console timeline (assuming current time is 14:00:00.000Z):
// [14:00:05.002Z] refreshed closedAt: null // fires at deadline
// [14:00:06.018Z] refreshed closedAt: 2026-12-02T14:00:05.412Z // 1s retry sees worker result -> stops
Real-Time Fan-Out with Socket.IO & Redis Backplane#
Revision Notes#
Reference files: codex-project-notes/17. Socket.io & Redis.html, 18. Implementing the Real-Time Updates.html, codex-project-code/part-4-realtime-socketio-redis/
Concept#
HTTP is strictly request-response: the browser must ask, and the server cannot speak first. Polling every 1–2 seconds wastes server capacity and still feels laggy. Replacing polling with WebSockets (Socket.IO) lets the server push live updates to all viewers immediately, while a Redis pub/sub backplane ensures those events still reach every viewer when multiple API servers run behind a load balancer.
How Distributed Real-Time Fan-Out Works#
Competing bids serialize on one PostgreSQL row via SELECT ... FOR UPDATE; only after COMMIT does Redis Pub/Sub broadcast a thin Socket.IO signal across API replicas for coalesced HTTP refetching.
Key Mental Models#
- Socket.IO over raw WebSockets: Adds named events (
auction:changed), per-auction rooms (browsers only receive updates for the auction they are viewing), and automatic reconnection. - Why Redis pub/sub is needed: With one API process, in-memory Socket.IO works alone. With multiple API replicas, Browser A may be connected to Instance 1 while Browser B is on Instance 2; Redis pub/sub broadcasts each event across all instances.
- Post-commit emission + thin event pattern:
- Emit the socket event only after the PostgreSQL transaction commits — never broadcast uncommitted data that might roll back.
- Send a lightweight "something changed" signal over the socket and let the browser refetch authoritative state over HTTP, avoiding state drift and complex client-side merge logic.
- Agent steering lessons:
- Prompts bias the model: Casual jokes (e.g., "100,000 users") turn into over-engineered requirements; write only what you actually mean, and review Mermaid architecture diagrams before approving implementation.
- Screenshots as prompts: For visual/layout defects caught in headed Playwright runs, attaching a screenshot with 2 numbered points beats long text descriptions.
- Branching beats arguing: If a chat goes off-track, branch into a new chat from the last good message instead of fighting polluted context.
Code Reference#
import { describe, expect, it, vi } from 'vitest';
import { createRefreshCoalescer } from './liveAuction';
describe('live auction refresh coalescing', () => {
it('turns overlapping requests into one in-flight and one trailing refresh', async () => {
let releaseFirst: (() => void) | undefined;
// First call pauses on a deferred promise so we can trigger overlapping SSE events while it's in flight.
const refresh = vi.fn()
.mockImplementationOnce(() => new Promise<void>((resolve) => {
releaseFirst = resolve;
}))
.mockResolvedValue(undefined);
const coalescedRefresh = createRefreshCoalescer(refresh);
// Three rapid events arrive; only the first starts immediately while the other two coalesce into one pending run.
const first = coalescedRefresh();
const second = coalescedRefresh();
const third = coalescedRefresh();
// -> first is in-flight; second & third share a single queued trailing refresh
expect(refresh).toHaveBeenCalledTimes(1);
// Completing the first refresh drains the single trailing refresh so the UI still sees the latest state.
releaseFirst?.();
await Promise.all([first, second, third]);
// -> first resolves -> queued trailing refresh executes once -> total calls = 2
expect(refresh).toHaveBeenCalledTimes(2);
});
it('allows a later event to retry after a failed background refresh', async () => {
// Verify the coalescer resets its in-flight state in a `finally` block so a rejected fetch doesn't wedge it.
const refresh = vi.fn()
.mockRejectedValueOnce(new Error('temporary read failure'))
.mockResolvedValue(undefined);
const coalescedRefresh = createRefreshCoalescer(refresh);
await expect(coalescedRefresh()).rejects.toThrow('temporary read failure');
await expect(coalescedRefresh()).resolves.toBeUndefined();
expect(refresh).toHaveBeenCalledTimes(2);
});
});
$ npx vitest run src/liveAuction.test.ts
RUN v3.1.1 /workspace/codex-project-code/part-8-cross-stack-debugging/web
✓ src/liveAuction.test.ts (2 tests) 6ms
✓ live auction refresh coalescing (2)
✓ turns overlapping requests into one in-flight and one trailing refresh 3ms
✓ allows a later event to retry after a failed background refresh 2ms
Test Files 1 passed (1)
Tests 2 passed (2)
Duration 412ms
Asynchronous Workflows: Workers, RabbitMQ & Transactional Outbox#
Revision Notes#
Reference files: codex-project-notes/20. Closing Auction Plan.html, 21. Messaging with RabbitMQ.html, codex-project-code/part-6-async-close-rabbitmq/
Concept#
When an auction's deadline passes, closing the auction and notifying the winner/seller should not depend on a user clicking refresh or a brittle chain of synchronous HTTP calls. Part 6 splits the backend into three independent processes — the API, an Auction Close Worker, and a Notification Worker — decoupled by RabbitMQ and protected against crashes by the Transactional Outbox pattern.
How the Async Close Pipeline Works#
Writing the auction close and outbox event in one PostgreSQL transaction prevents lost events on crash, while UNIQUE database constraints make at-least-once RabbitMQ redeliveries harmless.
Key Mental Models#
- Loose coupling over HTTP chains: If the Close Worker called the Notification service directly over HTTP, any downtime in notifications would block closing auctions. With RabbitMQ (exchange → routing key → queue), the producer drops the event and moves on; the consumer processes it when ready.
- Polling with
FOR UPDATE SKIP LOCKED: Polling Postgres every second is simple, reliable ("boring" is a strength), andSKIP LOCKEDallows multiple Close Worker replicas to run safely in parallel without grabbing the same expired auction. - The Transactional Outbox problem & solution:
- You cannot wrap a PostgreSQL write and a RabbitMQ publish in one distributed transaction. If the worker crashes between them, the auction closes in Postgres but the notification event is lost forever.
- Fix: Write the auction close and an outbox event row in the same Postgres transaction, then publish from the outbox and mark it published only after RabbitMQ publisher confirms.
- At-least-once delivery & Idempotent Consumers:
- If a consumer crashes before sending
ack, RabbitMQ redelivers the message. - Enforce "only once" in the database (
PRIMARY KEY,UNIQUEconstraints,ON CONFLICT DO NOTHING) at every boundary: one close per auction, one outbox event, one notification delivery per(event, recipient), and one modal per notification.
- If a consumer crashes before sending
Issue-Driven Autonomy (`/goal`), Git Worktrees & PR Reviews#
Revision Notes#
Reference files: codex-project-notes/22. Codex Goals.html, 24. Reviewing the Pull Request.html
Concept#
Interactive turn-by-turn prompting is ideal for exploratory feature design, but for well-scoped backlog tickets you can hand Codex an outcome with /goal, connect it to GitHub issues via the gh CLI, isolate its work in a Git worktree, and review the resulting Pull Request (PR) like any teammate's contribution.
Key Mental Models#
/goalvs. normal turns: A normal turn executes once and stops./goalruns an autonomous plan → execute → verify → re-plan loop until the success criteria are satisfied (and you can steer it mid-run).- Git worktrees for parallel work: A worktree checks out a separate branch into its own directory linked to the same Git repo. This lets a background
/goal(e.g., evaluating a Drizzle ORM migration) run concurrently while you grill and build another part in your main folder without file collisions. - Ticket quality dictates output quality:
- A vague, exploratory issue produces a design decision/ADR (e.g., documenting why to keep plain
pginstead of migrating to Drizzle). - A concrete issue with explicit acceptance criteria produces ready-to-review code in a PR.
- A vague, exploratory issue produces a design decision/ADR (e.g., documenting why to keep plain
- Disciplined PR review checklist:
- Does the PR summary match the issue's acceptance criteria?
- Are the changed files strictly where expected?
- Read the critical diffs (schema, business logic, security boundaries) line by line.
- Verify test claims: Agents can over-claim without intending to lie (e.g., running unit tests while skipping slow headed E2E tests). Always list every required verification command explicitly in
AGENTS.mdand ask directly whether E2E tests ran.
Winner Checkout, Signed Webhooks & Replay Safety#
Revision Notes#
Reference files: codex-project-notes/23. Stripe Checkout.html, 24. Reviewing the Pull Request.html, codex-project-code/part-7-winner-checkout/, codex-project-code/stripe-service/
Concept#
Payment handling is security-critical: your backend should never handle raw credit card numbers, never trust prices sent from the browser, and never mark an order "paid" just because a browser redirected to a success URL. Part 7 models real Stripe Checkout using a local Mock Stripe service (stripe-service/) with hosted checkout pages, test cards, and signed webhooks.
End-to-End Winner Checkout Flow#
Key Mental Models#
- Server owns the amount: The browser never tells the API how much to charge; the API reads the authoritative winning bid from PostgreSQL.
- Only a signed webhook proves payment: Browser redirects can be forged or interrupted if a tab closes. The payment provider calls your server (
POST /webhooks/stripe) with a cryptographically signed event to confirm settlement. - Replay safety (idempotency) everywhere:
- Webhooks are delivered at least once — slow responses trigger retries. Your webhook handler must safely ignore duplicate
checkout.session.completeddeliveries without double-charging or duplicating records. - The same principle applies to database seeds (
ON CONFLICT DO NOTHING): whenever an operation can run more than once, make repeated executions harmless.
- Webhooks are delivered at least once — slow responses trigger retries. Your webhook handler must safely ignore duplicate
- Local mock parity: Using a realistic local mock (
stripe-service/) lets you run full headed Playwright checkout tests with zero external accounts, API keys, or real money.
Distributed Observability with OpenTelemetry & Jaeger#
Revision Notes#
Reference files: codex-project-notes/25. Observability.html, 26. Observability with Jaeger.html, codex-project-code/part-8-cross-stack-debugging/
Concept#
Once an application spans an API, PostgreSQL, Redis, RabbitMQ, two background workers, and a payment service, plain logs cannot tell you where a workflow broke or stalled. Distributed tracing with OpenTelemetry (OTel) and Jaeger stitches every timed step (span) across processes and minutes of wall-clock time into one visual trace timeline.
How the "Golden Trace" Stays Connected#
Persisting W3C traceparent across PostgreSQL outbox rows, RabbitMQ headers, and signed Stripe Checkout webhooks stitches asynchronous hops minutes apart into one Jaeger trace.
Key Mental Models#
- Three observability signals:
- Logs: Detailed text lines per service (hard to stitch across distributed hops).
- Metrics: Aggregated numbers over time (great for dashboards/alerts, bad for debugging one specific user's failure).
- Traces: Parent/child trees of timed spans following one workflow end to end across services.
- OTel → OTLP → Jaeger: OpenTelemetry inside each Node.js service creates spans and exports them via the standard OTLP wire protocol to Jaeger, which stores and visualizes them (
http://localhost:16686). - Trace context propagation across async boundaries: HTTP calls propagate trace headers automatically, but async handoffs break traces unless you explicitly persist the trace context in the database outbox row and copy it into RabbitMQ message headers.
- High signal beats noisy data:
- Turn off noisy low-value auto-instrumentation and define meaningful business spans (
auction.bid.accept,auction.close,winner.checkout.start). - PII hygiene: Record IDs and amounts in span tags — never names, emails, or card numbers.
- Reserve red error spans for real failures: Rejected low bids or declined test cards are normal business outcomes, not crashes. If normal rejections turn spans red, real failures (
ECONNREFUSED, timeouts, slow805msqueries) get drowned out.
- Turn off noisy low-value auto-instrumentation and define meaningful business spans (
- Cross-stack debugging with agents: Agents excel at reading Jaeger traces to pinpoint a broken service, port mismatch, or slow query — just restrict them to read-only access in production environments.
Code Reference#
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';
import { NodeSDK } from '@opentelemetry/sdk-node';
import {
ParentBasedSampler,
SamplingDecision,
type Sampler,
type SamplingResult,
} from '@opentelemetry/sdk-trace-base';
// Custom root sampler keeps Jaeger focused on business flows:
// only root spans explicitly prefixed with `mock-stripe.` are recorded; noisy healthchecks are dropped.
class StripeRootSampler implements Sampler {
shouldSample(
_parentContext: Parameters<Sampler['shouldSample']>[0],
_traceId: string,
spanName: string,
): SamplingResult {
return {
decision: spanName.startsWith('mock-stripe.')
? SamplingDecision.RECORD_AND_SAMPLED
: SamplingDecision.NOT_RECORD,
// -> 'mock-stripe.checkout.complete' -> RECORD_AND_SAMPLED; 'GET /health' -> NOT_RECORD
};
}
toString(): string {
return 'StripeRootSampler';
}
}
// Must be initialized before the HTTP server starts so Undici's `fetch` is patched in time.
const sdk = new NodeSDK({
serviceName: process.env.OTEL_SERVICE_NAME ?? 'mock-stripe',
// Skip cloud/host resource detectors to keep local startup fast and deterministic.
autoDetectResources: false,
// Respect incoming upstream sampling decisions (from the auction server), falling back to StripeRootSampler for roots.
sampler: new ParentBasedSampler({ root: new StripeRootSampler() }),
// Exports OTLP/HTTP spans to OTEL_EXPORTER_OTLP_ENDPOINT (Jaeger on localhost:4318).
traceExporter: new OTLPTraceExporter(),
instrumentations: [new UndiciInstrumentation({
// Prevent orphan HTTP client spans from background traffic outside a traced business operation.
requireParentforSpans: true,
// Give outbound webhook calls a domain-meaningful span name instead of generic "HTTP POST".
requestHook(span, request) {
if (request.path === '/api/webhooks/stripe') {
span.updateName('winner.purchase.webhook HTTP');
// -> renames generic HTTP POST span in Jaeger for /api/webhooks/stripe
}
},
})],
});
sdk.start();
// Flush buffered spans cleanly on container stop or Ctrl+C.
process.once('SIGTERM', () => void sdk.shutdown());
process.once('SIGINT', () => void sdk.shutdown());
$ OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 \
node --import ./dist/otel.js ./dist/index.js
mock-stripe listening on http://127.0.0.1:4242
# Resulting trace tree visible in Jaeger (http://127.0.0.1:16686):
# Trace 4bf92f3577b34da6a3ce929d0e0e4736 (total: 42.6ms)
# ├─ [auction-server] winner.checkout.create (14.2ms)
# └─ [mock-stripe] mock-stripe.checkout.complete (21.8ms)
# └─ [mock-stripe] winner.purchase.webhook HTTP (11.4ms) <- renamed by requestHook
# └─ [auction-server] winner.purchase.webhook ( 8.9ms)
import {
context,
propagation,
ROOT_CONTEXT,
SpanStatusCode,
trace,
type Attributes,
type Context,
type Span,
} from '@opentelemetry/api';
// Named tracer scopes all manual business spans emitted by the mock Stripe service.
const tracer = trace.getTracer('mock-stripe-business');
// Reconstruct an OpenTelemetry Context from a stored or received W3C `traceparent` header
// so asynchronous callbacks (e.g., webhook delivery) attach to the original checkout trace.
export function contextFromTraceparent(traceparent?: string): Context {
return traceparent ? propagation.extract(ROOT_CONTEXT, { traceparent }) : ROOT_CONTEXT;
// -> Context carrying traceId '4bf92f3577b34da6a3ce929d0e0e4736' from stored header
}
// Serialize the currently active span context into a W3C `traceparent` string
// for persisting in DB rows or forwarding over queues/webhooks.
export function activeTraceparent(): string | null {
const carrier: Record<string, string> = {};
propagation.inject(context.active(), carrier);
// -> carrier = { traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-a91c4e82f01b3d74-01' }
return carrier.traceparent ?? null;
}
// Run an async business operation inside a child span: guarantees context activation
// (so outbound Undici fetches inherit this span), error recording, and `span.end()` on every exit path.
export async function withStripeSpan<T>(
name: string,
attributes: Attributes,
parent: Context,
work: (span: Span) => Promise<T>,
): Promise<T> {
const span = tracer.startSpan(name, { attributes }, parent);
return context.with(trace.setSpan(parent, span), async () => {
try {
return await work(span);
} catch (error) {
// Attach stack trace + mark span ERROR so Jaeger highlights failed payment/webhook attempts.
span.recordException(error instanceof Error ? error : String(error));
span.setStatus({ code: SpanStatusCode.ERROR });
throw error;
} finally {
span.end();
}
});
}
// Example usage when completing a checkout session and dispatching a webhook:
const parentCtx = contextFromTraceparent(session.traceparent);
await withStripeSpan(
'mock-stripe.checkout.complete',
{ 'stripe.session_id': session.id, 'auction.slug': session.auctionSlug },
parentCtx,
async () => {
console.log('outbound traceparent:', activeTraceparent());
await deliverSignedWebhook(session);
},
);
// Output:
// outbound traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-a91c4e82f01b3d74-01
How All Building Blocks Connect#
Revision Notes#
This module pairs two reinforcing tracks that evolve together from Part 1 to Part 8:
- The Backend Architecture Progression:
- Part 1 (
part-1-foundation): Vertical health slice (React → Fastify → Postgres) + Docker Compose baseline. - Part 2 (
part-2-create-auction-and-bid): Auctions, users, bids, integer cents, UTC timestamps, Zod validation, plain SQL migrations. - Part 3 (
part-3-business-rules-concurrency):SELECT … FOR UPDATErow locking, injected app clock, authoritative closing, typed409 Conflictrecovery, headed Playwright bidding-war tests. - Part 4 (
part-4-realtime-socketio-redis): Post-commit WebSocket fan-out via Socket.IO rooms + Redis pub/sub backplane for horizontal scale. - Part 5 (
part-5-hidden-defect-review): SeededFOR SHAREconcurrency defect proving why sequential tests miss races and how targeted agent investigation catches them. - Part 6 (
part-6-async-close-rabbitmq): Polling close worker (SKIP LOCKED) + transactional outbox + RabbitMQ + idempotent notification worker. - Part 7 (
part-7-winner-checkout+stripe-service): Hosted Stripe-style checkout, server-owned pricing, replay-safe signed webhooks. - Part 8 (
part-8-cross-stack-debugging): OpenTelemetry + Jaeger end-to-end "golden trace" across HTTP, Postgres, RabbitMQ, workers, and Mock Stripe.
- Part 1 (
- The AI-Assisted Engineering Loop:
- Lock guardrails in
AGENTS.mdand custom skills. - Grill before building (
GRILL.md, ADRs, Mermaid diagrams) and slice work into 2–4 browser-reviewable vertical slices. - Enforce back pressure with automated tests, type checks, headed Playwright runs, fresh-chat commits, and cross-model reviews.
- Scale your workflow with context hygiene (compaction, side chats, one chat per task), cheaper models guarded by tests, and
/goal+ Git worktrees for issue-driven PRs.
- Lock guardrails in
Quick Self-Check Questions#
Self-Check Questions#
Why is SELECT … FOR UPDATE preferred over READ COMMITTED alone or SERIALIZABLE for handling simultaneous bids on an auction?
READ COMMITTED alone allows check-then-act races where multiple concurrent requests read the same old price and insert duplicate bids. SELECT … FOR UPDATE locks only that single auction row so competing bids serialize cleanly without blocking other auctions or requiring SERIALIZABLE retry loops.
Why does changing FOR UPDATE to FOR SHARE break bidding concurrency while leaving normal unit tests green?
FOR SHARE permits multiple concurrent transactions to read the same auction row simultaneously, reintroducing the check-then-act race. Sequential unit tests only send one request at a time, so only a concurrent test (like the 4-window bidding war) exposes it.
Why inject an app clock instead of calling Date.now() directly inside auction-closing logic?
Calling Date.now() couples business rules to real wall-clock time, making exact boundary tests (1ms before vs. after endsAt) impossible without waiting. An injected clock lets tests control time deterministically and ensures a single time source read after acquiring the row lock.
Why does Socket.IO need a Redis pub/sub backplane, and why should events emit only after the database commits?
With multiple API server instances behind a load balancer, a browser connected to Instance 2 would miss bids processed by Instance 1 unless Redis fans events out to all instances. Emitting after COMMIT prevents broadcasting bids that later roll back.
What failure mode does the Transactional Outbox solve between PostgreSQL and RabbitMQ?
Because Postgres and RabbitMQ cannot share a single atomic transaction, a crash after closing an auction in Postgres but before publishing to RabbitMQ would permanently lose the close event. Writing the state change and outbox row in the same Postgres transaction guarantees the event is persisted and eventually published.
Why must both RabbitMQ notification consumers and Stripe webhook handlers be idempotent (replay-safe)?
Both message queues and webhooks provide at-least-once delivery, meaning crashes or slow responses cause duplicate deliveries. Enforcing uniqueness in the database (UNIQUE, ON CONFLICT DO NOTHING) ensures processing the same event twice produces the same final state with no duplicate popups or payments.
How does a single Jaeger trace stay connected across a bid, an auction close minutes later, and a notification worker?
By persisting the OpenTelemetry trace context in the PostgreSQL outbox row when the bid/close is recorded, propagating it in RabbitMQ message headers, and extracting it in the notification worker so each process continues the same trace ID instead of starting disconnected traces.