01

What Happens When You Rename a Stop

You type "Tsukiji Outer Market," click outside the box, and half a second later a pin lands on three friends' screens at once — follow that single edit across the system.

From Couch Planning to Live Street Coordination

Imagine you and three friends have your Tokyo trip open simultaneously — you rename "Lunch" to "Tsukiji Outer Market," click away, and half a second later the new title and map pin appear on everyone else's screen without anyone hitting refresh. RoadStar is built not just for couch planning weeks before takeoff, but also for live group coordination on the street once you land.

🗺️

Live Co-Planning

Shape multi-day timelines and stops together while WebSocket broadcasts keep every open laptop and phone in lockstep.

🧭

Map-First Routes & Optimiser

Visualize daily stops as connected map pins, inspect travel legs, and run the one-click route optimiser to untangle zig-zagging detours.

✨

Idea Board & AI Copilot

Toss "maybe" cafes into a KIV voting board and ask the AI Copilot to turn rough wishes into structured stops.

📍

On-the-Move Meetup & Location

Turn on opt-in expiring GPS sharing, broadcast "meet here at 15:00" walking ETAs, and coordinate in group trip chat.

One Edit, Two Legs: The Relay Race Baton Pass

Think of renaming a stop as a two-leg relay race: your browser passes the baton over strict HTTP REST to an official judge (Core) who stamps it into the permanent record book (PostgreSQL). Only after that ink dries does Core hand a megaphone to a stadium announcer (Realtime), who blasts the update over Redis Pub/Sub and WebSockets so every friend's phone updates automatically.

💻
Alice's Browser
🚪
NGINX Gateway
⚖️
Core Service
🗄️
PostgreSQL
📣
Go Realtime
📱
Bob's Phone
Click "Next Step" to trace Alice's rename from keystroke to Bob's screen
🧭
Why Should You Care? Instant Bug X-Ray Vision

Writes enter through the front door (an NGINX proxy forwarding REST writes to Core); live updates exit through the side window (WebSockets from Realtime). That split lets you triage bugs in five seconds: if an edit vanishes on reload, inspect Core and PostgreSQL; if it survives reload but teammates had to refresh to see it, inspect the Realtime WebSocket path.

Leg 1 in Code: Sending Your Edit Through the Front Door

When you blur the stop title box, React sends an HTTP PUT call through apiRequest in frontend/src/services/apiClient.ts to /backend. Passing credentials: "include" tells the browser to attach your HttpOnly cookie automatically on every API call.

CODE · frontend/src/services/apiClient.ts
export async function apiRequest<T>(path: string, opts: ApiOptions = {}): Promise<T> {
  const { body, auth = true, headers: extraHeaders, ...rest } = opts;
  const headers = new Headers(extraHeaders);
  headers.set("Content-Type", "application/json");

  const res = await fetch(`${API_BASE}${path}`, {
    ...rest, headers, credentials: "include", // cookie rides along automatically
    body: body === undefined ? undefined : JSON.stringify(body),
  });

  if (res.status === 401 && auth) {
    onAuthFailure?.();
    throw new ApiError(401, "Session expired");
  }
PLAIN ENGLISH

One shared helper handles every backend request, using a TypeScript generic <T> to type-check the response.

Unpack the caller's payload and options, and stamp "application/json" on the envelope so Core knows JSON is inside.

Send the request to /backend/... (API_BASE) and wait for the server's verdict.

credentials: "include" tells the browser to slip your invisible login cookie into the request automatically — no manual token wiring needed.

Convert your JavaScript object (like { title: "Tsukiji Outer Market" }) into a JSON string on the wire.

If the server replies 401, trigger the global sign-out hook and stop immediately with a clear "Session expired" error.

Leg 2 in Code: Announcing Only After Commit

Inside core/src/itinerary/concurrency.utils.js, Core checks the stop's version, waits for PostgreSQL to commit the row plus a new sequence number, and only then sends an internal POST to Realtime (documented in ADR 0005). A 2-second timeout and try/catch ensure a stalled announcer can never crash your save.

CODE · core/src/itinerary/concurrency.utils.js
  try {
    const response = await fetch(`${realtimeUrl}/internal/broadcast`, {
      method: 'POST',
      headers,
      body: JSON.stringify({
        room: tripId,
        action,
        timestamp: new Date().toISOString(),
        data: { data, version, seq },
      }),
      // Awaited before the REST response is sent, so a hung Realtime must not
      // hang the user's request.
      signal: AbortSignal.timeout(BROADCAST_TIMEOUT_MS),
    });
    if (response.status !== 202) {
      console.error(`Realtime broadcast rejected (${action}): ${response.status} ${await response.text()}`);
    }
  } catch (error) {
    console.error(`Realtime broadcast failed (${action}): ${error.message}`);
  }
PLAIN ENGLISH

Wrap the entire megaphone call in a safety net (try), then call Realtime's private /internal/broadcast endpoint.

Address the envelope to this trip's room (tripId) and attach the action name (ACTIVITY_UPDATED), timestamp, updated stop data, version, and seq counter.

Attach a 2-second cutoff timer (BROADCAST_TIMEOUT_MS) so a frozen Realtime service cannot leave Alice staring at a spinner forever.

Realtime normally answers 202; if it returns anything else, log the rejection for engineers without failing Alice's request.

If Realtime is completely unreachable or times out, catch the error, log it, and still return success to Alice because PostgreSQL already saved her work.

💡
Aha! Why Best-Effort Broadcasts Beat Rollbacks

PostgreSQL is the single source of truth. If Realtime hiccups after the database has committed Alice's stop rename, rolling back or failing her edit would throw away valid user work — instead, Core logs the missed broadcast and lets lagging clients catch up cleanly via change_seq sequence numbers.

Test Your Intuition: Three Real Scenarios

Put the two-leg relay model to work on the exact kind of bug reports and design tradeoffs you will encounter when steering an AI coding assistant.

Scenario 1 · Debugging a Live Sync Bug

Alice renames "Lunch" to "Tsukiji Outer Market" on her laptop. Sitting across the table, Bob watches his open trip tab and nothing changes — yet the instant Bob hits browser refresh, "Tsukiji Outer Market" appears on his timeline and map.

Which hop in the relay race broke, and where should you investigate first?

Scenario 2 · Steering an AI Architecture Suggestion

You ask an AI assistant to add a "rename day" feature. It suggests sending the edit over the open WebSocket into Go Realtime first, and having Go forward the write to Core.

Why did RoadStar explicitly reject routing itinerary edits through the WebSocket first (ADR 0001)?

Scenario 3 · Resilience Under Partial Failure

Right as Alice clicks away to save a stop title, the Go Realtime service freezes completely for 10 seconds and stops answering internal requests.

What happens to Alice's save request while Realtime is frozen?

Now that we have watched a single edit pass the baton from browser to database to megaphone, let's zoom out. In Module 2, we will step behind the curtain and meet the full cast of services that power RoadStar behind one front door.

02

Meet the Cast of Services

When you run docker compose up, ten containers wake up on one virtual network — why ten specialized crew members instead of one giant program?

Why Split Into a Film Production Crew?

On a movie set, you wouldn't ask the camera operator to negotiate actor contracts, hold a boom mic motionless for twelve hours, and scout city streets all at once. RoadStar's ADR 0001 splits the system into specialized microservices because short database writes, all-day open phone lines, metered map lookups, and streaming AI suggestions behave completely differently under load — while a single NGINX reverse proxy makes all ten containers look like one clean website on port 80.

🎬

Short Transactions

Core (x2) handles bursty RBAC checks, route maths, and strict database commits.

🎙️

12-Hour Open Lines

Realtime (x2) holds thousands of idle WebSocket rooms open inside a tiny 128 MB RAM budget.

🗺️

Metered Lookups

Maps (x2) shields paid Google APIs behind a 24-hour cache and deterministic offline mock fixtures.

✨

Streaming Diffs

AI Copilot trickles live SSE itinerary proposals without ever writing directly to the database.

Browser Layer

🌐
Frontend SPA

Edge Gateway (:80)

🚦
NGINX Gateway

Stateless Application Crew

🏛️
Core Service x2
⚡
Realtime Service x2
🧭
Maps Service x2
🤖
AI Copilot

State & External Providers

🗄️
PostgreSQL 14
📡
Redis 7
👆 Click any crew member above to inspect its folder, runtime port, tech stack, and strict ownership boundary.
💡
Why Ownership Boundaries Matter

Whether you are debugging a bug or steering an AI coding assistant, know which crew member is allowed to touch state: Realtime never queries PostgreSQL, Maps owns zero database tables, AI Copilot only proposes diffs, and Core is the sole judge of permissions and database writes.

Where Everything Lives in the Repo

RoadStar keeps all services together in one monorepo so a single feature branch can update SQL tables, backend APIs, and React screens side by side. Although an early project proposal considered Next.js and binary gRPC, the shipped codebase deliberately chose a Vite SPA plus REST, SSE, and WebSockets for simpler inspection and deployment.

📝

Early Proposal

Considered Next.js SSR + internal gRPC service contracts.

🚀

Built Reality

Shipped React 19 + Vite SPA over REST + SSE + WebSockets behind NGINX.

frontend/ React 19, Vite, TypeScript, Tailwind CSS, and Leaflet browser UI
core/ Node.js 22 + Express 5 service (:3000) — Auth, RBAC, Trips, Itinerary, KIV, Chat, Meetup, Optimiser
realtime/ Go 1.24 + coder/websocket service (:8080) — stateless trip rooms, presence, live GPS, typing events
maps-service/ TypeScript + Express 5 service (:3001) — Google Places/Routes client, SMU mock provider, 24h Redis cache
ai-service/ Python 3.12 + FastAPI service (:8001) — OpenAI Responses SSE streaming & itinerary diff proposals
db/ PostgreSQL 14 normalized 14-table schema (init.sql) and demo seed data
infrastructure/nginx/ nginx.conf port 80 gateway, round-robin pools, and WebSocket upgrade rules
manifests/ Cloud-ready Kubernetes deployment, service, and ingress YAML definitions
docs/adr/ Architecture Decision Records justifying service splits, locking, and sync protocols
tests/ Cross-service integration and end-to-end verification suites

The Traffic Director: NGINX & Core's Dual Doors

Inside infrastructure/nginx/nginx.conf, NGINX groups twin containers into named upstream pools (core-1/core-2, maps-1/maps-2, realtime-1/realtime-2), dealing traffic in round-robin order while upgrading /ws into a 1-hour persistent tunnel. If any container fails three times in 10 seconds, NGINX automatically routes around it for instant failover.

infrastructure/nginx/nginx.conf
    upstream core_backend {
        # Round-robin distribution across scaled Core Trips instances
        server core-trips-service-1:3000 max_fails=3 fail_timeout=10s;
        server core-trips-service-2:3000 max_fails=3 fail_timeout=10s;
        keepalive 32;
    }

    upstream maps_backend {
        # Round-robin distribution across scaled Maps instances
        server maps-service-1:3001 max_fails=3 fail_timeout=10s;
        server maps-service-2:3001 max_fails=3 fail_timeout=10s;
        keepalive 16;
    }

    upstream realtime_backend {
        # Round-robin distribution across scaled Realtime instances
        server realtime-1:8080 max_fails=3 fail_timeout=10s;
        server realtime-2:8080 max_fails=3 fail_timeout=10s;
        keepalive 32;
    }
PLAIN ENGLISH

Core pool: Alternate API requests evenly between core-trips-service-1 and core-trips-service-2 on internal port 3000.

Circuit breaker: If either twin errors 3 times in 10 seconds, pause traffic to it for 10s; keep 32 warm keepalive sockets ready.

Maps pool: Alternate place searches and route calculations across maps-service-1 and maps-service-2 on port 3001 (16 warm sockets).

Realtime pool: Spread new WebSocket room handshakes across realtime-1 and realtime-2 on port 8080 so neither Go container shoulders every open tab alone.

Inside Core's Front Door: Defensive Dual Mounting

Once NGINX forwards /backend/... to core_backend, core/src/index.js registers every Express middleware router under both /api/* and /*. That way, requests succeed identically whether a gateway strips /backend down to /api/trips or an internal test calls /trips directly.

core/src/index.js
app.use('/api/trips', tripsRoutes);
app.use('/trips', tripsRoutes);

app.use('/api/trips/:tripId/itinerary', itineraryRoutes);
app.use('/trips/:tripId/itinerary', itineraryRoutes);

app.use('/api/trips/:tripId/kiv', kivRoutes);
app.use('/trips/:tripId/kiv', kivRoutes);

app.use('/api/trips/:tripId/meetup', meetupRoutes);
app.use('/trips/:tripId/meetup', meetupRoutes);
app.use('/api/trips/:tripId/chat', chatRoutes);
app.use('/trips/:tripId/chat', chatRoutes);

app.use('/api/places', mapsRoutes);
app.use('/places', mapsRoutes);
PLAIN ENGLISH

Trips CRUD & roles: Accept both /api/trips and /trips for creating trips and managing collaborators.

Daily schedule: Wire stop ordering, times, and route recalculation at both /api/trips/:tripId/itinerary and /trips/:tripId/itinerary.

Keep-In-View backlog: Mount the shared idea parking lot + voting routes under both prefixes.

Meetup & group chat: Attach live meetup pins and persistent trip chat history to both URL styles.

Places helper routes: Expose Core's internal place-lookup wrapper at both /api/places and /places.

Behind the Scenes: Searching & Adding "Marina Bay"

Let's eavesdrop on the crew's walkie-talkies when Alice opens a trip, types "Marina" into the search box, and clicks Add to Day 1. Pay close attention to which services jump in — and which ones stay completely silent!

🧭
Exam Nuance — Docs vs. Code

Notice how core/src/index.js mounts routes at both /api/trips and /trips so requests succeed whether a proxy strips /backend or forwards /api directly — while NGINX blocks outside browsers from ever calling /realtime/internal, reserving that broadcast horn strictly for Core via Redis Pub/Sub.

Test Your Service Instincts

Step into the architect's chair for three real scenarios. Think about secret credentials, blast-radius isolation, and why workloads scale differently.

1. You want to convert Google Places price levels into a user's home currency using a paid third-party exchange-rate API key, then store the chosen stop's cost. Where does each piece belong?

2. Google Maps suffers a global outage (returning 502 timeouts). What happens when two teammates rename existing stops or reorder Day 2 in RoadStar?

3. According to ADR 0001, why is realtime built as a separate Go service instead of keeping WebSocket rooms inside the Node.js core process?

03

Five Homes for Different Data

Where your friend is standing right now is useless ten minutes from now — and saving it in a permanent database table every 5 seconds would create thousands of rows an hour plus a creepy surveillance log. RoadStar solves this by sorting every piece of data by how fast it expires.

The Household Filing Rule: Sort Data by How Fast It Expires

At home, you lock your house deed in a fireproof vault, write family memories in a bound journal, stick "stepped out for 5 mins" on a fridge sticky note, scribble driving estimates on an erasable whiteboard, and hold your pocket compass in your own hand. When RoadStar added live "on-the-trip" features, ADR 0009 turned that exact instinct into five strict storage tiers by asking three questions: Who needs it? For how long? And does edit order change the outcome?

👥

1. Who Needs It?

Does the whole travel group need to see this across devices, or does it belong strictly on your own screen?

⏳

2. For How Long?

Must it survive next month, expire in 24 hours, vanish 75 seconds after a tunnel, or disappear the instant you close your tab?

🔢

3. Does Order Change Meaning?

Swapping two itinerary edits can corrupt a schedule, whereas two rapid chat texts simply stack in arrival order.

🏦 Metaphor: The Fireproof Vault

Authoritative group decisions where edit order and conflict detection matter.

Home: PostgreSQL (db/schema.sql) Lifespan: Kept until deleted

📦 What Lives Here

Trips, days, stops (completed_at, travel_mode, position), KIV ideas & votes, and group meetup pins (trip_meetups).

🛡️ How Order Stays Safe

Stored in PostgreSQL, versioned (returning HTTP 409 on conflict), numbered by trip_change_seq, and audited in trip_changes.

🚫 What Stays Out

Chat messages, typing dots, and moving GPS coordinates never touch Tier 1 so they cannot bloat the undo/replay log.

⚠️
Why Should You Care? The #1 AI Coding Trap

Left unguided, AI coding assistants almost always stuff ephemeral "is typing" flags or 5-second GPS dots straight into PostgreSQL tables — or mix chat messages into the itinerary's undo sequence. Naming these five tiers lets you steer an AI architecturally in one sentence.

Inside Tier 1 & Tier 2: Two SQL Counters and Retry-Proof Chat

Opening db/schema.sql reveals two quiet masterstrokes: trip_changes aims its foreign key at trip_change_seq(trip_id) instead of trips(id) to dodge row-lock traffic jams, while trip_messages runs on a separate counter n guarded by a partial unique index on client_id. That index makes sending chat messages idempotent so tapping retry on patchy 4G never posts twin messages.

🔢 Plan Counter: trip_change_seq

Increments only when the actual itinerary changes (stops, days, KIV, meetups) and references trip_change_seq(trip_id) directly so logging mutations never waits on trips table locks.

💬 Chat Counter: trip_message_seq (n)

Advances independently for every chat message so reconnecting phones can ask GET /messages?after=n without ever touching or advancing the plan's version history.

db/schema.sql
CREATE TABLE IF NOT EXISTS trip_messages (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    trip_id UUID NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
    n INTEGER NOT NULL,
    user_id UUID REFERENCES users(id) ON DELETE SET NULL,
    kind VARCHAR(20) NOT NULL CHECK (kind IN ('text', 'location', 'share_started', 'share_stopped', 'meetup_set', 'meetup_cleared')),
    body TEXT,
    latitude NUMERIC(10, 7),
    longitude NUMERIC(10, 7),
    meta JSONB,
    client_id VARCHAR(64),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL,
    UNIQUE (trip_id, n)
);

-- A message sent again after a lost response is the same message.
CREATE UNIQUE INDEX IF NOT EXISTS idx_trip_messages_client ON trip_messages(trip_id, user_id, client_id) WHERE client_id IS NOT NULL;
PLAIN ENGLISH

Create Tier 2's append-only journal table for trip chat and timeline notices.

Give each row a random UUID, and auto-clean messages if the parent trip is deleted (ON DELETE CASCADE).

n is this chat message's per-trip ticket number; if a user deletes their account later, keep the message history with user_id set to null.

Strictly restrict kind to six known event types — regular texts, one-shot location pins, or live-share/meetup announcements.

Optional fields store message text, 7-decimal-place coordinates (~1 cm precision), or flexible JSONB metadata.

client_id holds a receipt stamp generated by the phone before hitting send, and UNIQUE (trip_id, n) guarantees no two messages share a sequence slot.

The retry shield: if the same user re-sends the same client_id after a tunnel drops the reply, PostgreSQL refuses a duplicate row so the server safely returns the original!

💡
Aha! Group Decisions vs. Personal Coordinates

Why does a Meetup Point live in Tier 1 PostgreSQL (trip_meetups) while everyone's walking ETA toward it lives in Tiers 3 and 4? Because "Meet at Shibuya Crossing at 15:00" is a shared group decision that must survive tomorrow, whereas your GPS dot moving toward it goes stale in 30 seconds!

Inside Tier 3: Self-Cleaning Presence in Go & Redis

In realtime/internal/server/presence.go, every Go server instance re-stamps its live WebSocket connections into Redis presence:<tripId> every 30 seconds with a 75-second expiry, so even a hard server crash cleans itself up automatically. Every Redis write travels single-file through one background worker channel (ops), guaranteeing a user's "left" event can never overtake the "joined" right before it.

⚡ 250ms Push Window

defaultPresenceThrottle batches rapid updates to at most 4 broadcasts per second per trip.

🔄 30s Heartbeat

defaultPresenceRefresh rewrites active entries well before Redis's countdown expires.

⏳ 75s Self-Destruct

defaultPresenceTTL drops any unrefreshed ghost entry after two missed heartbeats plus grace buffer.

🧵 1 Ordered Worker

ops runs on one goroutine so slow Redis calls never block live chat delivery.

presence.go
const (
	defaultPresenceThrottle = 250 * time.Millisecond // at most one push per trip in this window
	defaultPresenceRefresh  = 30 * time.Second       // rewrite this instance's entries
	defaultPresenceTTL      = 75 * time.Second       // an entry not refreshed in time is dropped
	presenceOpTimeout       = 2 * time.Second
	presenceQueueSize       = 1024
)

type presenceState struct {
	throttle time.Duration
	refresh  time.Duration
	ttl      time.Duration

	// Unique per process, so connection ids from different instances (or a
	// restarted one) never collide in the shared store.
	connPrefix string

	// Store writes run one at a time, in order, on one goroutine: a "left"
	// can never overtake the "joined" before it, and a slow Redis never holds
	// up message delivery.
	ops     chan func(context.Context)
	pending sync.WaitGroup
PLAIN ENGLISH

Define the five tuning knobs that keep Tier 3 presence responsive yet self-cleaning.

Cap outgoing room updates to once every 250ms, rewrite active entries every 30s, and tell Redis to auto-expire stale entries at 75s.

Give any single Redis write at most 2 seconds before timing out, and buffer up to 1,024 queued updates in memory.

presenceState holds each running Go server's live timers and coordination state.

connPrefix stamps every socket ID with a unique per-process badge so two scaled Go containers (or a restarted one) never overwrite each other's connections in Redis.

ops queues Redis write functions single-file onto one worker: "left" can never race past "joined", and a hiccuping Redis never freezes WebSocket messages.

pending uses a Go WaitGroup so graceful shutdown finishes in-flight presence cleanups cleanly.

Hands-On Challenge: Put Each Feature in Its Rightful Home

Now test your architectural instincts against the real RoadStar codebase. Drag each feature chip below into the exact storage tier where RoadStar keeps it (or tap a chip, then tap its target home on mobile).

📍 Member's live GPS dot
🧭 Which direction your phone is facing
🕒 Meetup pin at 15:00
🛣️ Driving polyline between two stops
💬 Quick reply: Running 10m late

Tier 1 — The Plan: PostgreSQL versioned row + trip_changes log

Drop here

Tier 2 — The Chat: PostgreSQL trip_messages with trip_message_seq & client_id

Drop here

Tier 3 — Live: Redis presence:<tripId> hash, expires on disconnect, never in Postgres

Drop here

Tier 4 — Derived: Redis maps:* 24h cache, recomputable anytime

Drop here

Tier 5 — Personal: Browser memory only via useHeading.ts, never sent over network

Drop here

Applied Quiz: Stress-Testing the Five Tiers

Three real-world scenarios — a crashed container disrupting cross-server fanout, a tempting schema shortcut, and a subway tunnel retry. Apply the five-tier rules to diagnose how RoadStar behaves and why.

1. The roadstar-redis container crashes in production and restarts 20 seconds later. While Redis is down, what breaks and what keeps working?

2. A teammate suggests adding last_lat and last_lng columns to trip_members in PostgreSQL and calling PUT /api/users/location every 3 seconds. Why did ADR 0009 reject this?

3. Riding through a subway tunnel with spotty data, Bob taps "On my way" in Trip Chat. The server saves it, but the response drops in the tunnel — so Bob taps "Tap to retry". Why doesn't the chat show "On my way" twice?

04

Syncing Without Overwriting

How stamped library index cards, infinite call numbers, and consecutive ticket counters took RoadStar from 79% rejected saves down to 0% false conflicts.

From 79% False Conflicts to 0%

Picture a trip itinerary as a drawer of library index cards: RoadStar uses server-authoritative Optimistic Concurrency Control (OCC) instead of automatic character-merging CRDTs because structured travel fields like times, budgets, and places fit human choice better than silent auto-merging. Keeping conflict checks in PostgreSQL also keeps tables clean and leaves the Go Realtime relay completely stateless.

Early stress tests with six friends editing one trip at the same time exposed a painful surprise documented in ADR 0006: up to 79% of saves failed until RoadStar narrowed what each edition stamp actually guards.

🏷️

Card Edition Stamp

Every stop card carries its own version number, so friends editing different stops never bump elbows.

🗂️

Infinite Call Numbers

Sliding a stop between "B" and "C" stamps "BV" on the moved card instead of renumbering the whole drawer.

🎟️

Consecutive Change Tickets

Every saved edit claims the next trip_change_seq ticket so phones leaving a subway tunnel replay only what they missed.

1
Design 1 — Single Trip Version (5–79% Saves Refused)

Every edit checked one shared trips.version counter, causing false conflicts even when six friends edited completely different days.

2
Design 2 — Day Version + Integer Order Index (16–77% False Conflicts)

Checking days.version isolated separate days, but numbering stops 0, 1, 2... forced every drag-and-drop move to renumber sibling stops on that day.

3
Design 3 — Row Version + Fractional Keys (0% False Conflicts)

Stop edits check only activities.version, day title/notes check days.version, and adding or reordering days checks trips.version — eliminating false conflicts completely.

🧭
Match Lock Scope to Human Intent

When a version stamp guards the whole document, polite neighbours trip over each other constantly; when each index card carries its own stamp, conflicts only happen when two people rewrite the exact same card at the same moment.

One Atomic SQL Check & Two Editors Colliding

When you save a stop, Core checks your expected edition number and bumps it by one inside a single atomic SQL UPDATE ... WHERE id = $19 AND version = $20 statement. If a friend saved a split-second earlier, zero rows match and Core returns a 409 Conflict payload ({ error, entity, days, latest_snapshot }) so the browser can show both versions side by side.

CODE · itinerary.service.js
             version = version + 1,
             updated_by = $18,
             updated_at = CURRENT_TIMESTAMP
         WHERE id = $19 AND version = $20
           AND day_id IN (SELECT id FROM days WHERE trip_id = $21)
         RETURNING *`,
        [
PLAIN ENGLISH

Stamp the stop card with the next edition number (version + 1) as we save.

Record which traveller made this edit and stamp the exact database clock time.

The safety gate: only update Stop $19 if its database version still equals $20.

Verify the stop actually belongs to a day inside this trip ($21) so cross-trip tampering fails.

Hand back the freshly saved row — if 0 rows come back, Core knows someone else beat us to it!

Click through the chat below to watch Alice and Bob edit the exact same stop card at version: 3 in the same second.

Fractional Keys — Sliding Between Neighbours

Instead of numbering stops 1, 2, 3, RoadStar uses fractional indexing with Base-62 strings (0-9A-Za-z) sorted byte-for-byte in PostgreSQL via TEXT COLLATE "C". Keys never end in '0' (so "a" and "a0" cannot represent the same slot), browsers send after_id rather than raw position strings, and dragging a stop updates only 1 row.

🔢

Old Integer order_index

Inserting a coffee stop at slot 1 shifts stops 1, 2, 3, 4 to 2, 3, 4, 5 — touching 5 rows and colliding with teammates editing those stops.

✂️

Fractional midpoint("B", "C")

Adjacent letters have no single character between them, so position.js extends by one character to "BV" — touching 1 row and leaving neighbours untouched.

CODE · position.js
function midpoint(a, b) {
  if (b !== null) {
    // Keep the shared prefix, then split what follows it.
    let n = 0;
    while ((a[n] || '0') === b[n]) n++;
    if (n > 0) return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));
  }
  const digitA = a ? DIGITS.indexOf(a[0]) : 0;
  const digitB = b !== null ? DIGITS.indexOf(b[0]) : DIGITS.length;
  if (digitB - digitA > 1) {
    return DIGITS[Math.round((digitA + digitB) / 2)];
  }
  // Adjacent first digits: no room at this length, so go one digit longer.
  if (b !== null && b.length > 1) return b.slice(0, 1);
  return DIGITS[digitA] + midpoint(a.slice(1), null);
}
PLAIN ENGLISH

Find a brand-new call number strictly between neighbour a (before) and neighbour b (after).

If both neighbours share leading letters (like "B4" and "B9"), peel off the shared prefix "B" and split the rest via recursion.

Look up each first character's numeric slot from 0 to 61 inside the Base-62 DIGITS alphabet.

If there is at least one character gap between them (like "B" and "F"), return the middle character ("D").

If the digits sit right next to each other (like "B" and "C"), append a middle character after "B" (giving "BV") so room never runs out.

Not Fighting Yourself — The Client SaveQueue

Row versioning creates a subtle trap for fast typists: what if you rename a stop at version: 1 and half a second later blur its cost box before the first HTTP reply comes back? createSaveQueue() chains your own in-flight saves per stop and translates your stale version: 1 to version: 2 through its private own map — while leaving teammates' edits unmapped so genuine 409 conflicts still trigger!

1
Edit #1 Starts (Title Blur at basedOn: 1)

inFlight stores the active Promise for Stop s1; when Core replies with version: 2, the queue records own: 1 → 2.

2
Edit #2 Waits in Line (Cost Blur Still Holding basedOn: 1)

Because Edit #2 queued behind Edit #1, it walks own (1 → 2) and automatically sends version: 2 instead of fighting your own earlier save.

3
Teammate Safety Preserved

If Bob bumped Stop s1 to version: 2, your own map has no 1 → 2 entry — so your browser sends version: 1 and properly opens the conflict panel.

CODE · saveQueue.ts
export function createSaveQueue(): SaveQueue {
  const inFlight = new Map<string, Promise<unknown>>();
  const own = new Map<string, Map<number, number>>(); // stop → sent version → resulting version

  return {
    queue(id, basedOn, send) {
      const run = () => {
        let version = basedOn;
        const versions = own.get(id);
        while (versions?.has(version)) version = versions.get(version)!;
        return send(version);
      };
      const next = (inFlight.get(id) ?? Promise.resolve()).then(run, run);
      inFlight.set(id, next);
      const done = () => {
        if (inFlight.get(id) === next) inFlight.delete(id);
      };
      next.then(done, done);
      return next;
    },
PLAIN ENGLISH

Create two per-stop lookup tables: inFlight for the active network save, and own for version hops this browser earned.

When a field queues a save for stop id, start with the version number the UI originally read (basedOn).

Follow the chain of our own completed saves (e.g. 1 → 2 → 3) so rapid back-to-back blurs always send our freshest version.

Chain run behind whatever save is currently in flight for this same stop — different stops still save in parallel!

Once the network request finishes (success or error), clear inFlight if no newer save has lined up behind it.

Catching Up After a Tunnel — trip_change_seq & changeOrder.ts

Per-row versions cannot order events across multiple rows — if a delayed update arrived after a delete, it could resurrect a deleted stop! Every database transaction claims a monotonic per-trip seq number as its very last SQL statement before COMMIT, logs to trip_changes, and browsers use createChangeOrder to park early WebSocket packets, wait 1000ms on gaps, and fetch GET /api/trips/:id/changes?since=N (reloading the full trip only on 410 Gone when more than 200 changes behind).

📱
WebSocket Socket
🧮
changeOrder.ts
🗄️
Core /changes
✨
Trip Itinerary UI
Click "Next Step" to trace how a phone heals a dropped tunnel packet
CODE · changeOrder.ts
  function settle() {
    if (last >= expected) return stopWaiting();
    gapTimer ??= setTimeout(() => {
      gapTimer = undefined;
      if (last < expected && !reloading) onGap();
    }, waitMs);
  }

  return {
    receive(seq, event) {
      if (seq <= last) return;
      expected = Math.max(expected, seq);
      early.set(seq, event);
      if (reloading) return;
      applyInOrder();
      settle();
    },
PLAIN ENGLISH

Check if we have applied every ticket up to the highest seen so far — if yes, cancel any gap timer.

If a gap remains (we saw 12 while still at 10), start a single 1000ms grace timer before calling onGap().

Ignore duplicate tickets we already applied (seq <= last) so replayed messages stay harmless.

Park incoming ticket seq in the early holding room and record the highest ticket number seen.

Drain consecutive tickets (last + 1, last + 2...) immediately, then call settle() in case a hole blocked the line.

💡
Aha! Deadlock Prevention on trip_change_seq

Why does trip_change_seq live in its own tiny table updated last instead of a column on trips? Stop edits lock days first while trip-header edits lock trips first — touching trips at the end of a stop edit would create a classic deadlock! Even better, recordChanges bumps seq by changes.length in one UPDATE so PostgreSQL skips redundant foreign-key checks mid-transaction.

Check Your Instincts — Concurrency & Ordering

Put your mental model to the test on four real design puzzles from RoadStar's sync engine.

1. When Alice gets a 409 adding a new Day (POST /days, checked against trips.version), apiClient.ts automatically retries up to 5 times with jittered backoff. Why does the browser never auto-retry a 409 when editing a Stop (PUT /activities/:id)?

2. In position.js, why does the key invariant isPosition forbid any fractional position key from ending with '0' (the very first character in DIGITS)?

3. Alice loads Stop X at version: 5. Bob saves Stop X so Core is now at version: 6, and Alice's WebSocket has not delivered Bob's event yet. Alice edits Stop X's title (basedOn: 5) through saveQueue. What happens?

4. Why couldn't RoadStar assign per-trip seq numbers using Redis INCR inside the Go Realtime service instead of PostgreSQL's trip_change_seq table?

05

Smart Helpers — Maps, Day Optimiser & AI Copilot

Ever clicked “Optimise day” or asked the AI Copilot to rearrange an afternoon, and wondered why neither one ever accidentally deletes a stop you already visited or silently overwrites a friend’s edit?

1. Maps Service — One Interface, Pair Caching & Degraded Mode

Think of RoadStar’s smart helpers as a travel architect sketching on tracing paper before touching the real house in PostgreSQL, starting with a ADR 0002 interface called LocationProvider. In local dev and CI, MockLocationProvider serves deterministic Singapore SMU fixtures, while production swaps in GoogleLocationProvider with narrow X-Goog-FieldMask field masks (still falling back automatically for synthetic ChIJMock* IDs!).

🔌

Mock vs. Google Switch

One LocationProvider contract powers place search, details, and route matrices — switching providers via config while keeping ChIJMock* test places working even in live Google mode.

⚡

Per-Pair 24h Redis Cache

Route legs are cached per origin-destination pair for 24 hours in Redis (backed by an in-memory LRU fallback) with a 150ms fail-open timeout so a slow cache never blocks a request.

🛡️

Degraded Mode (Never Cached)

If Google times out or hits HTTP 429 quota, Maps returns HTTP 200 with degraded: true and skips caching so routes recover the instant Google recovers.

CODE — maps-service/src/services/routes.service.ts
    } catch (err) {
      // Travel-time enrichment must not fail the itinerary edit path.
      if (
        err instanceof AppError &&
        (err.code === ErrorCode.UPSTREAM_ERROR ||
          err.code === ErrorCode.UPSTREAM_TIMEOUT ||
          err.code === ErrorCode.QUOTA_EXCEEDED)
      ) {
        return {
          mode,
          entries: [],
          degraded: true,
          cached: false,
        };
      }
      throw err;
    }
PLAIN ENGLISH

Intercept external roadblocks: When Google Routes throws an error, catch it before it can break the user’s itinerary save.

Check if upstream Google is at fault: Match 5xx crashes, network timeouts, or exhausted API quotas rather than our own code bugs.

Enter degraded mode cleanly: Return an empty entries: [] list for that travel mode so Core still saves the stop with null travel times.

Never cache a failure (cached: false): Keeping degraded responses out of Redis prevents a 10-second blip from breaking travel times for 24 hours.

Re-throw unexpected bugs: Anything else (like invalid coordinates) still throws loudly so real bugs aren’t hidden.

💡
Architectural Gold: Isolate Unpredictable Intelligence

External APIs and AI models are slow, rate-limited, and occasionally wrong. RoadStar tames both Google Maps and OpenAI behind graceful fallbacks, pair-level caches, and propose-then-commit versioned boundaries so core trip editing never goes down.

2. Day Route Optimiser & “Best Fit” Insertion

When you untangle crossed strings on tracing paper in core/src/optimise/route.js (up to 20 stops per day), your nailed-down pins never budge: Stop 0 is always fixed as the starting anchor, stops marked done (completed_at), stops you pin (📌), and optionally your final hotel (keep_end) stay locked in their slots. Short legs at or under walk_max_minutes walk while longer legs pick the fastest selected mode, and clicking Apply uses a Longest Increasing Subsequence (staying) to move the minimum rows via temporary '~' || id keys.

1
Fetch 10×10 Route Matrices (with Ruler Backup)

Core requests walking, driving, or transit leg matrices in 10×10 chunks; if Maps is in degraded mode, it falls back to straight-line Haversine distance × a 1.3x city-road detour factor.

2
Lock Fixed, Completed & Pinned Stops

Stop 0, every completed stop (completed_at), every user-pinned slot (📌), and optional keep_end enter the fixed set so midday re-optimising never rewrites history or dinner bookings.

3
Untangle via Nearest-Neighbour + twoOpt / improveFixed

A heuristic Nearest-Neighbour pass drafts an order, then 2-opt segment reversals (or improveFixed swaps around locked slots) shave off backtracking — the same cost grid also powers “Best fit” KIV insertion!

4
Verify Every Stop Version & Move Minimal Rows via LIS

POST .../optimise/apply checks every stop’s version in one transaction, leaves LIS staying stops untouched, and parks moving rows at '~' || id keys to dodge unique-order collisions.

CODE — core/src/optimise/route.js
function twoOpt(start, cost, keepEnd) {
  let order = start.slice();
  let best = pathCost(order, cost);
  const lastMovable = keepEnd ? order.length - 2 : order.length - 1;
  let improved = true;
  while (improved) {
    improved = false;
    for (let i = 1; i < lastMovable; i++) {
      for (let k = i + 1; k <= lastMovable; k++) {
        const next = [...order.slice(0, i), ...order.slice(i, k + 1).reverse(), ...order.slice(k + 1)];
        const c = pathCost(next, cost);
        if (c < best - 1e-9) {
          order = next;
          best = c;
          improved = true;
        }
      }
    }
  }
  return order;
}
PLAIN ENGLISH

Copy onto tracing paper: Clone the draft stop sequence (start.slice()) and score its total travel time in best.

Guard start & end anchors: Starting i at 1 keeps Stop 0 fixed, while keepEnd pulls lastMovable back by one so your final hotel stays put.

Uncross tangled loops: Test reversing every movable middle slice from index i through k to see if flipping that sub-path removes a detour.

Demand a real win (1e-9): Only adopt next if it beats best by more than tiny floating-point rounding noise, preventing endless ties.

Repeat until locally optimal: Keep scanning after every improvement until a full pass finds zero faster flips.

3. AI Copilot — Propose First, Never Mutate Directly

Built with FastAPI and OpenAI’s Responses API (gpt-4o-mini), ai-service boots cleanly even without OPENAI_API_KEY (returning HTTP 503 only if opened) and verifies Core trip membership and role before spending a single OpenAI token. A VIEWER receives only read tools (search_places, route_matrix, list_kiv_items), untrusted itinerary text is fenced inside <trip_data> tags against prompt injection, and write tools stream red-and-green ProposalDiff overlays over SSE (status, text_delta, tool_start, tool_result, proposal, done) instead of mutating Core!

🧑‍💻
Trip Editor
🤖
AI Service
🧠
OpenAI API
📋
ProposalDiffModal
🏛️
Core API & DB
Click “Next Step” to trace the Propose-then-Commit loop

4. Inside committer.py — Why AI Re-Reads Before Every Commit

Minutes can pass while you inspect the blueprint overlay in ProposalDiffModal, so when you click Approve, Committer.apply_all re-fetches the live trip from Core before every single proposal. It retries ordinary stop or day 409 conflicts at most once with refreshed versions, never retries schedule_kiv_item on 409 (so a KIV idea already scheduled by a friend isn’t scheduled twice!), and marks later proposals skipped if an earlier step fails.

CODE — ai-service/app/committer.py
    async def apply_all(self, proposals: list[Proposal]) -> list[CommitResult]:
        results: list[CommitResult] = []
        failed = False
        for proposal in proposals:
            if failed:
                results.append(CommitResult(proposal_id=proposal.id, status="skipped",
                                            message="Skipped after an earlier failure"))
                continue
            try:
                await self.apply_proposal(proposal)
                results.append(CommitResult(proposal_id=proposal.id, status="applied", message=proposal.summary))
            except CommitError as exc:
                failed = True
                results.append(CommitResult(proposal_id=proposal.id, status="failed",
                                            message=exc.message, partial=exc.partial))
        return results
PLAIN ENGLISH

Commit checked blueprints in sequence: Loop through the user-approved proposals list and collect a per-card CommitResult.

Halt cascading damage ("skipped"): If an earlier proposal failed, skip every remaining proposal instead of running follow-up steps against half-finished state.

Re-read fresh versions & apply: Inside apply_proposal, fetch live Core state right before writing and record "applied" on success.

Report exact conflict state ("failed"): On a CommitError (such as an unrecoverable 409), trip the failed breaker and flag partial if a multi-call edit stopped halfway.

🚨
Aha! Hallucination Guardrails in proposals.py

The language model is never trusted to invent a place_id or guess a KIV version (hallucination)! proposals.py rejects any place_id that wasn’t returned by search_places during this exact run (seen_places), and overwrites schedule_kiv_item’s version with the real version captured from list_kiv_items (seen_kiv).

5. Scenario Check — Smart Helpers Under Pressure

Put on your systems-architect hat and trace how Maps, the Day Optimiser, and the AI Committer behave when quotas run dry or collaborators edit at the same moment.

1. Google Routes API suddenly returns 429 QUOTA_EXCEEDED right as Alice adds a new café stop and Bob clicks “Optimise day.” Why must RoutesService avoid caching that response for 24 hours, and what happens to Alice and Bob?

2. The AI Copilot proposes scheduling KIV item "Night Safari" (version 2) onto Day 1. While you review ProposalDiffModal, your friend schedules "Night Safari" onto Day 2 (bumping its version to 3). What happens when you click Approve, and why doesn’t committer.py retry on 409 here?

3. It is 2:00 PM on Day 1 (6 stops in slots 0 through 5). You already ticked Stop 1 and Stop 2 as completed (✓), and you pinned (📌) your 7:00 PM dinner reservation at slot 5. When you click Optimise, which stops is route.js allowed to reorder?

06

Auth, Roles & Keeping Private Doors Locked

If browser scripts aren't allowed to read your secret login cookie, how does RoadStar verify your identity on a live WebSocket — and how does it kick a removed teammate out of a trip room mid-edit?

Festival Wristbands & Four Coordinated Security Gates

Think of RoadStar's security like a music festival with tamper-proof wristbands, backstage role passes, and welded staff-only tunnels. Instead of trusting a single lock, RoadStar coordinates four layers recorded across ADR 0003 and ADR 0006 so that even if one assumption slips, the next gate stops the request cold.

🚧

1. Edge Tunnel Weld

NGINX and Kubernetes Ingress return 403 Forbidden on /realtime/internal before public packets ever touch Go.

🎟️

2. Dual Wristband + Blacklist

Core verifies an 8-hour JWT and checks PostgreSQL's revoked_access_token table using a SHA-256 fingerprint.

🔌

3. Handshake + Origin Gate

Go Realtime validates the browser's HttpOnly cookie plus the Origin header, then confirms room membership with Core.

🔒

4. Ledger Row Locks

Every write transaction locks your trip_members row FOR SHARE so a demoted member cannot sneak in a stale edit.

When you sign in via POST /auth/login, Core checks your password against a 10-round bcrypt hash, confirms your account has no unredeemed verification_token row, and issues an 8-hour HS256 wristband in both an HttpOnly cookie (accessToken, immune to XSS token theft) and JSON data.accessToken (for CLI and test scripts). Logging out hashes that token with SHA-256 into revoked_access_token, which Core's authentication middleware checks on every protected call:

core/src/middleware/auth.middleware.js
  let decoded;
  try {
    decoded = jwt.verify(token, JWT_SECRET);
  } catch (err) {
    // 401: the caller isn't authenticated. 403 is for an authenticated caller
    // who isn't allowed, and would stop clients sending the user to log in.
    return res.status(401).json({ error: 'Invalid or expired token' });
  }

  const tokenHash = crypto.createHash('sha256').update(token).digest('hex');
  const revoked = await db.query(
    'SELECT 1 FROM revoked_access_token WHERE token_hash = $1 AND expires_at > CURRENT_TIMESTAMP',
    [tokenHash]
  );
  if (revoked.rows.length) {
    return res.status(401).json({ error: 'Access token has been revoked' });
  }

  req.user = decoded;
  req.authToken = token;
  return next();
}
PLAIN ENGLISH

Check that the wristband signature matches JWT_SECRET and the 8-hour timer hasn't expired.

If verification fails, return 401 Unauthorized (never 403!) so the React frontend knows to clear the stale session and send the user to /login.

Compute the token's SHA-256 fingerprint — we never store raw active tokens in the blacklist table.

Ask PostgreSQL if this fingerprint was logged out and hasn't naturally expired yet.

If found on the blacklist, reject immediately with 401 even though its cryptographic signature is still valid.

Attach the decoded user payload and raw token to req, then open the gate to the route handler.

🧭
Frontend Startup Gotcha Fixed in AuthProvider.tsx

When a brand-new guest visits /signup, React checks whether a cookie session already exists by calling GET /backend/api/users/me with { auth: false }. Without that flag, an unauthenticated guest's completely normal 401 response would trigger apiClient.ts's global session-expired listener and yank them away from /signup back to /login!

WebSocket Handshake Auth & Why URL Tokens Are Forbidden

Standard browser new WebSocket(url) calls cannot attach custom Authorization headers, and your React code cannot read an HttpOnly cookie to paste it anywhere. Because NGINX serves both the React app and /ws from the same same-origin gateway, the browser automatically carries your accessToken cookie onto the WebSocket upgrade while Go checks Origin against REALTIME_ALLOWED_ORIGINS to block Cross-Site WebSocket Hijacking.

🍪

Browser Tabs: Cookie + Origin

Browsers send Cookie: accessToken=... automatically on /ws, paired with strict Origin allowlist validation.

🧪

Scripts & Load Tests: Bearer

Non-browser WebSocket clients pass Bearer tokens in the Authorization header during handshake.

🚫

Forbidden: ?token=... URLs

URL query strings leak in plain text into NGINX logs, browser history, and Referer headers (ADR 0003).

Look at tokenFromRequest in Go Realtime — notice what is checked first, what is checked second, and how URL query parameters are completely ignored:

realtime/internal/auth/jwt.go
func tokenFromRequest(r *http.Request) (string, error) {
	if authorization := r.Header.Get("Authorization"); authorization != "" {
		parts := strings.SplitN(authorization, " ", 2)
		if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || strings.TrimSpace(parts[1]) == "" {
			return "", errors.New("authorization must use Bearer token")
		}
		return strings.TrimSpace(parts[1]), nil
	}

	if cookie, err := r.Cookie(AccessTokenCookie); err == nil && strings.TrimSpace(cookie.Value) != "" {
		return strings.TrimSpace(cookie.Value), nil
	}

	return "", ErrMissingToken
}
PLAIN ENGLISH

Inspect the incoming HTTP upgrade request before upgrading it to a WebSocket.

First, check if a CLI or Artillery load script supplied an Authorization header.

Split into two pieces and enforce strict Bearer <token> formatting — reject malformed headers immediately.

Return the clean Bearer token if valid.

Second, fall back to the browser's automatic accessToken HttpOnly cookie.

If neither header nor cookie exists, fail with ErrMissingToken — r.URL.Query() is never consulted!

Where RBAC Really Lives — FOR SHARE Locks & Live Eviction

Here is a codebase surprise that trips up anyone skimming folder names: core/src/middleware/rbac.middleware.js is completely empty (0 bytes)! Checking roles in an early Express middleware outside the database transaction creates a race condition: an owner could demote an editor to VIEWER a millisecond after middleware passed, letting the editor's half-finished stop delete still commit.

OWNER Full trip, day, stop, meetup, route-optimise & AI commit control; DELETE /trips/:id; invite, remove, or change member roles.
EDITOR Edit trip, days & stops, vote/must-go/schedule KIV ideas, set meetups, optimise days & commit AI plans; edit/delete only own KIV cards & self-leave.
VIEWER Read itinerary, post in Trip Chat, pitch new KIV ideas (and edit own), run insertion-fit previews; receives 403 on all plan mutations & AI /commit.
MEMBER_REMOVED Core broadcasts MEMBER_REMOVED; every Go Realtime pod delivers the event and calls Hub.EvictUser(room, userID) to boot all open tabs!

Instead of stateless middleware, every write transaction calls lockMemberRole first — holding a FOR SHARE lock on the caller's trip_members row until commit, so role changes wait for in-flight writes and any write starting after demotion fails with 403 before optimistic concurrency version checks run:

core/src/itinerary/concurrency.utils.js
async function lockMemberRole(client, tripId, userId) {
  const result = await client.query(
    'SELECT role FROM trip_members WHERE trip_id = $1 AND user_id = $2 FOR SHARE',
    [tripId, userId]
  );
  return result.rows[0]?.role ?? null;
}
PLAIN ENGLISH

Run inside the active PostgreSQL transaction client (BEGIN has already started).

Read this user's membership role and hold a shared row lock (FOR SHARE) until our write commits or rolls back.

Multiple tabs belonging to the same editor can still read their role simultaneously without blocking each other — only an owner's UPDATE or DELETE on trip_members must wait in line.

Return the live role (or null if already removed), letting the service reject unauthorized callers with 403.

1

Owner clicks Remove Member in Core

→
2

DELETE waits for any active FOR SHARE write

→
3

Core broadcasts MEMBER_REMOVED via Redis

→
4

Every Go pod runs Hub.EvictUser on that room

Welding Internal Doors & "Spot the Security Bug"

Core pushes live events to Go Realtime over an internal endpoint (POST /internal/broadcast) guarded by X-Internal-Token using Go's subtle.ConstantTimeCompare — a constant-time comparison. Practicing defense in depth, NGINX also blocks external callers from ever reaching /realtime/internal at the edge:

infrastructure/nginx/nginx.conf
        # Block internal realtime endpoints from external requests
        location ^~ /realtime/internal {
            default_type application/json;
            return 403 '{"error":"Forbidden: internal endpoint"}';
        }
PLAIN ENGLISH

Match any browser or internet request starting with /realtime/internal with high-priority prefix matching (^~) before general /realtime/ proxy rules.

Immediately slam the door with a JSON 403 Forbidden response inside NGINX — eliminating external brute-force attack or leaked-header exposure completely.

Now put on your security reviewer hat! An AI coding assistant drafted a custom WebSocket handshake handler below — click the exact line that introduces a serious vulnerability in RoadStar's threat model:

Click the vulnerable line in this WebSocket handshake:

1 const bearer = req.headers.authorization?.replace('Bearer ', '');
2 const cookieToken = req.cookies?.accessToken;
3 const token = bearer || cookieToken || req.query.token;
4 const claims = jwt.verify(token, process.env.JWT_SECRET);
5 if (!allowedOrigins.includes(req.headers.origin)) return res.status(403).end();

Check Your Security Instincts

Test how these four layers work together when debugging real authentication, role-demotion, and network-isolation scenarios.

Scenario 1 — 401 vs. 403

A junior teammate changes Core's stop-deletion route to return 401 Unauthorized instead of 403 Forbidden when a signed-in VIEWER tries to delete a stop. What broken behavior will users immediately report in the React frontend?

Why does RoadStar strictly separate 401 from 403?

Scenario 2 — Demotion & Eviction Race

An editor clicks "Save" on a stop update at almost the exact millisecond the trip owner clicks "Remove Member" on that editor, while the editor also has two live WebSocket tabs open.

How do PostgreSQL and Go Realtime coordinate so the removed editor cannot keep mutating or listening to the room?

Scenario 3 — Defense in Depth

Go Realtime's POST /internal/broadcast handler already verifies the X-Internal-Token secret header using subtle.ConstantTimeCompare. Yet both nginx.conf and Kubernetes Ingress also configure /realtime/internal to immediately return 403.

Why did the team add that extra 403 rule at the edge gateway?

07

Scaling, Kubernetes & When Things Break

If NGINX deals connections like a deck of cards across two Core servers and two Realtime servers, how does an edit sent to core-1 reach a teammate whose WebSocket landed on realtime-2 — and what happens if you pull the plug on realtime-2 mid-trip?

Twin Radio Towers & One Shared Studio Intercom

Picture two radio towers broadcasting to hikers in a valley, wired to one shared studio intercom (Redis) and watched by an autopilot mechanic (Kubernetes + ArgoCD). Because NGINX uses plain round-robin without sticky sessions (ADR 0004), whichever Pod receives Core's POST /internal/broadcast publishes to trips:<tripId> in Redis, while every Realtime pod subscribes to the wildcard pattern trips:* via PSubscribe and fans out to its own local sockets:

1

Alice's edit hits core-1 & commits in Postgres

→
2

core-1 posts to realtime-1 /internal/broadcast

→
3

realtime-1 publishes on Redis trips:<id>

→
4

Both realtime-1 & realtime-2 hear trips:* and push to Alice & Bob!

🗼

Tower 1 (realtime-1)

Holds Alice's open WebSocket in local RAM, receives Core's HTTP call, and hands the JSON event to Redis Pub/Sub.

🎙️

Shared Intercom (Redis)

Relays trips:<tripId> broadcasts and tracks cross-pod room presence with 90-second self-expiring heartbeats.

📡

Tower 2 (realtime-2)

Subscribes to trips:* at startup, catches Alice's event off Redis, and delivers it straight down Bob's local WebSocket.

realtime/internal/broker/redis.go
func (b *RedisBroker) Publish(ctx context.Context, room string, payload []byte) error {
	channel := channelPrefix + strings.TrimSpace(room)
	return b.client.Publish(ctx, channel, payload).Err()
}

func (b *RedisBroker) Subscribe(ctx context.Context, handler MessageHandler) error {
	b.mu.Lock()
	b.handler = handler
	b.mu.Unlock()

	pubsub := b.client.PSubscribe(ctx, patternAll)
	_, err := pubsub.Receive(ctx)
	if err != nil {
		_ = pubsub.Close()
		return fmt.Errorf("redis psubscribe failed: %w", err)
	}
	b.pubsub = pubsub

	subCtx, cancel := context.WithCancel(context.Background())
	b.cancel = cancel

	go b.listen(subCtx)
	return nil
}
PLAIN ENGLISH

Publish prefixes the trip ID to form trips:<tripId> and announces the raw JSON event into Redis.

Subscribe registers the local room hub callback that pushes events to sockets connected to this pod.

PSubscribe tunes into patternAll (trips:*) so one subscription covers every active trip room at once.

Wait for Redis's initial subscription confirmation at boot — if Redis isn't reachable yet, fail immediately so startup retries kick in.

Spawn a background goroutine (go b.listen) that streams incoming broadcasts to local WebSocket rooms for the life of the pod.

💡
Aha! Fail Fast at Boot, Stay Calm at Runtime

If Redis is unreachable when realtime starts, it retries 5 times and exits so NGINX never routes users to a deaf pod. But if Redis blips while already running, GET /health (health check) deliberately returns 200 OK with redis: unreachable instead of 503 Service Unavailable — because returning 503 would make NGINX rip down both Realtime pods simultaneously and drop every open WebSocket!

Why Only ONE Writable PostgreSQL? (ADR 0007)

RoadStar scales its stateless services (core, maps, realtime, frontend) via horizontal scaling across multiple replicas. By contrast, postgres deliberately runs as a single primary using Kubernetes's Recreate strategy attached to one 1Gi PVC — here is what would shatter if you put two writable databases behind round-robin:

💥

1. Broken Version Check

Alice saves v3 on DB-A (200 OK) while Bob saves v3 on DB-B (200 OK). Async logical replication silently overwrites one edit after both travelers saw "Saved!".

🛑

2. Halted Replication

Two stops inserted into the same gap on DB-A and DB-B compute the exact same fractional indexing position, crashing the UNIQUE index on (day_id, position) when changes replicate!

🚀

3. The True Scale Path

Pair 1 primary with a synchronous standby for hardware crashes; if one machine ever saturates, apply sharding by trip_id and add PgBouncer when 5 Core pods × 10 connection pool slots grow.

Horizontal (1–5 pods) core-service, maps-service, realtime-service, and frontend scale out freely with zero local state.
Single Writer (1 pod) postgres stays the sole serialization point for optimistic locking, trip_change_log sequence numbers, and unique positions (ADR 0007).

Kubernetes, Sealed Secrets & ArgoCD GitOps

On Minikube Kubernetes (ADR 0008), RoadStar's CI/CD pipeline in GitHub Actions runs unit/integration tests, builds non-root multi-stage Docker builds, scans for CRITICAL and HIGH CVEs with Trivy, pushes immutable commit-SHA tags to GHCR, and writes the new image tag into manifests/ using [skip ci]. Real API keys are encrypted with Bitnami Sealed Secrets (kubeseal), and one ArgoCD ApplicationSet reconciles all 7 cluster apps (common, postgres, redis, core-service, maps-service, realtime-service, frontend):

1

Commit lands on main

→
2

CI Tests + Docker Buildx

→
3

Trivy blocks HIGH/CRITICAL CVEs

→
4

Push SHA image to GHCR

→
5

Bot commits tag with [skip ci]

→
6

ArgoCD auto-syncs K8s

Look closely at lines 46–50 of applicationset.yaml — they solve a classic tug-of-war where ArgoCD's selfHeal would otherwise fight Kubernetes's HPA whenever traffic scales pods past replicas: 1:

manifests/argocd/applicationset.yaml
      source:
        repoURL: https://github.com/Nicrionn/fsd-roadstar.git
        targetRevision: main
        path: '{{path}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: roadstar
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
        syncOptions:
          - CreateNamespace=true
      ignoreDifferences:
        - group: apps
          kind: Deployment
          jsonPointers:
            - /spec/replicas
PLAIN ENGLISH

Watch the main branch of the GitHub repo for each of the 7 service folders ({{path}}) and deploy into the roadstar namespace.

prune: true deletes obsolete K8s objects removed from Git, while selfHeal: true reverts unauthorized live cluster drift.

The HPA truce: ignoreDifferences tells ArgoCD to ignore live changes to /spec/replicas so HPA can scale stateless services from 1 up to 5 pods (at 70% CPU / 80% RAM) without ArgoCD crushing them back down to 1!

🔀
Dual Ingress Routing Prevents Refresh Collisions

In manifests/common/, ingress.yaml routes direct paths (/api, /auth, /users, /ws, and fallback /) so refreshing /trips/:id in your browser serves the React SPA instead of raw backend JSON, while ingress-rewrite.yaml strips service prefixes (/backend, /core, /maps, /realtime → /$2) and blocks /realtime/internal at the cluster edge.

Proving It Works Under Fire — Lock-Gate Races & Load Insights

Firing Promise.all in a test rarely proves concurrency safety because one query often finishes on localhost before the second even arrives! RoadStar's deterministic test harness (raceBehindLock) holds a PostgreSQL FOR UPDATE lock until pg_stat_activity confirms every contender is physically queued on the row lock, then drops the gate at the exact same instant (alongside soak.integration.test.js firing 20 random writes per round using reproducible seed 464):

🏇

Starting-Gate Lock Harness

raceBehindLock holds a row lock while contenders line up in pg_stat_activity, guaranteeing genuine simultaneous collisions on release.

🔥

The bcrypt CPU Discovery

Artillery's 35 new logins/sec stress test spiked core-service to 250% CPU (triggering HPA 1 → 5 pods!) because 10-round bcrypt saturated a tight 250m CPU cap.

⚡

800-User Room Benchmark

realistic-trip-rooms.yml (800 users across 20 rooms, 2–5s think time) hit 3,799 / 3,799 requests (0.00% errors) at 13.9 ms median latency (6 ms full itinerary reads!).

core/src/tests/integration/race.js
/** Sessions in this database waiting on a lock right now. */
async function blockedCount() {
  const res = await db.query(
    `SELECT COUNT(*)::int AS n FROM pg_stat_activity
     WHERE datname = current_database() AND wait_event_type = 'Lock'`
  );
  return res.rows[0].n;
}

/**
 * Waits until `n` sessions are queued on a lock, or until `isDone()` returns
 * true; fails after a few seconds.
 */
async function waitUntilBlocked(n, isDone = () => false) {
  const deadline = Date.now() + BLOCKED_TIMEOUT_MS;
  let blocked = await blockedCount();
  while (blocked < n && !isDone()) {
    if (Date.now() > deadline) {
      throw new Error(`Only ${blocked} of ${n} contenders were waiting on the lock after ${BLOCKED_TIMEOUT_MS} ms: ` +
        'a contender may not need the locked row, or finished before reaching it');
    }
    await new Promise((resolve) => setTimeout(resolve, POLL_MS));
    blocked = await blockedCount();
  }
}
PLAIN ENGLISH

Query PostgreSQL's internal pg_stat_activity table to count how many connections are actively parked on wait_event_type = 'Lock'.

Poll every few milliseconds until all n competing requests are genuinely lined up against our starting-gate lock.

If a contender never reaches the lock before the timeout, fail loudly with a diagnostic error instead of letting a flaky test pass by accident!

Once all n contenders are queued, the caller commits/releases the gate lock so PostgreSQL wakes them simultaneously.

Pulling the Plug Mid-Trip — Graceful Pod Restarts

What happens when ArgoCD rolls out a new container image and Kubernetes terminates realtime-2 while Bob is actively planning a trip on it? Step through the live conversation between Kubernetes, realtime-2, Bob's browser, and Core:

Final Boss Quiz — Systems Design & Resilience

Put the whole RoadStar architecture together across GitOps, CI/CD security gates, load-test diagnostics, and distributed state.

Boss Question 1 — ArgoCD vs. HPA Drift

Before adding ignoreDifferences on /spec/replicas in applicationset.yaml, core-service kept flapping between Synced and OutOfSync in ArgoCD and killing newly scaled pods during heavy traffic.

What caused ArgoCD and Kubernetes to fight each other?

Boss Question 2 — CI/CD Loop & Trivy PR Gotcha

Each service's GitHub Actions workflow commits updated image SHA tags into manifests/ with [skip ci], and configures Docker Buildx with load: ${{ github.event_name != 'push' }}.

Why are both of those workflow settings essential?

Boss Question 3 — Artillery Bottleneck Diagnosis

During load testing at 35 brand-new user logins per second, core-service experienced socket timeouts even though PostgreSQL CPU remained relaxed and GET /api/trips/:id normally completes in 6 ms.

What actually caused the CPU bottleneck inside core-service?

Boss Question 4 — Why Not Multi-Master PostgreSQL?

An examiner asks: "You scaled Core, Maps, and Realtime horizontally to multiple pods. Why didn't you also put 2 writable PostgreSQL pods behind round-robin to double write throughput?"

Which architectural explanation best answers the examiner?