JamzyAPI openapi.json

System design · REST · Real-time

How Jamzy works, end to end.

Jamzy is a real-time social listening app: a room code, a shared YouTube queue, and one host whose play, pause, seek, and track changes every listener follows. This page documents the engineering behind it — the architecture, the PostgreSQL data model, the playback synchronization protocol, the control flows, the socket contract, the security posture, the deployment, and the full REST reference.

StackGo 1.27 · PostgreSQL · Socket.IO v4 ClientReact 19 · Vite · TypeScript DeployRender · Neon · Vercel

System at a glance

The product question is narrow: how do several browsers watch the same video at the same second without screen sharing? The answer shapes the whole system. The server owns playback state, PostgreSQL is the source of truth, and every client interpolates its playhead from the same timestamped snapshot.

10REST endpointsProfiles, rooms, and YouTube resolution
13Socket events inSix events broadcast back to the room
4PostgreSQL tablesUsers, rooms, memberships, messages
60Go testsAcross 14 files, including end-to-end

Principle 01

Server-authoritative playback

The host's play, pause, seek, and track changes are database mutations. Each one stores a position and a UTC timestamp, then broadcasts the resulting snapshot. No viewer is trusted to drive another viewer's player.

Principle 02

State split by lifetime

Identity, rooms, membership, chat, and playback snapshots are durable and live in PostgreSQL. Presence, the queue, host-handover countdowns, and rate-limit windows are session state and live in guarded in-process memory.

Principle 03

Fail closed on identity

Both transports resolve identity from a verified Clerk session token. The backend never takes the caller's identity, host status, or role from a payload, and re-checks host authority against the database on every mutation.

LayerChoiceWhy
HTTPGo standard library net/http with method-prefixed ServeMux patternsThe API surface is ten endpoints; a framework would add a dependency without removing work.
Persistencepgx with hand-written SQL in per-domain servicesThe query surface is small and the SQL is the clearest description of each access path. No ORM, no generated types.
RealtimeSocket.IO v4 over Engine.IO v4, mounted at /socket.io/Matches the socket.io-client wire protocol used by the React client, including acknowledgements and rooms.
AuthClerk session JWTs verified in-processNo identity service of our own, and no per-request network call once the JWKS cache is warm.
ClientReact 19, Vite, strict TypeScript, YouTube IFrame APIThe client renders state and reports local player events; all authority stays server-side.
DeliveryRender for the API, Neon for PostgreSQL, Vercel for the SPA, GitHub Actions for CIEvery runtime is reproducible from the repository, and none of them is a server to patch.

Architecture

One Go binary serves the REST API, the Socket.IO endpoint, and this page. Persistence is a single PostgreSQL database. Clerk issues and signs the session tokens; the YouTube Data API supplies the catalog.

Architecture diagram: React browser client, Go API process with REST, Socket.IO and domain services, PostgreSQL, Clerk, and the YouTube Data API GO API · RENDER · ONE PROCESS Browser React 19 SPA · Vercel Clerk session socket.io-client YouTube IFrame API TypeScript · Vite REST · /api/* ServeMux · JSON · Bearer JWT Socket.IO · /socket.io/ EIO=4 · goroutine per event Middleware recover · log · CORS · rate limits Domain services rooms · playback · messages · music Clerk session JWTs · JWKS PostgreSQL Neon · TLS users · rooms room_members messages YouTube Data API search · videos playlists REST + JWT Socket.IO v4 pgx · SQL JWKS API key stays server-side
REST and Socket.IO share one process and one set of domain services. PostgreSQL holds the only durable state; Clerk signs identity, and the YouTube key never reaches the browser.
PackageResponsibility
cmd/apiWiring: configuration, connection pool, migrations, services, socket hub, HTTP server, graceful shutdown
internal/httpapiThe route table and dependency wiring for REST, docs, health, and the socket mount
internal/httpxRecovery, request logging, security headers, CORS, Clerk authentication, fixed-window rate limits, JSON responses
internal/authSession token verification, key-id parsing, the in-memory JWKS cache, and the one-method Verifier interface
internal/realtimeSocket hub, presence, queue, host transfer, room broadcasts, and per-event panic recovery
internal/roomsRoom creation, idempotent membership, host succession in transactions, and leave semantics
internal/playbackThe three snapshot writers, snapshot reads, and position normalization
internal/dbpgx pool, embedded migrations, Prisma adoption, advisory locking
internal/openapiThe embedded OpenAPI document and this reference page

Concurrency model

  • Every socket event runs in its own goroutine, so slow database work cannot stall the transport.
  • Each handler recovers panics and logs the stack; a bad payload becomes one error acknowledgement, not a process exit.
  • Presence, queue, pending transfers, and per-connection room caches are maps behind mutexes.
  • HTTP routes are wrapped in recovery middleware that answers 500 without leaking internals.

State ownership

Durable (PostgreSQL): users, rooms including the playback snapshot, memberships, and chat history.

Ephemeral (process memory): presence, the queue, host-transfer countdowns, the per-connection joined-room set, and rate-limit windows.

The two meet once: the room:join acknowledgement returns presence, the persisted playback snapshot, the in-memory queue, and recent chat in a single round trip.

Request lifecycle

Recover → Request log → Security headers → CORS → ServeMux → RequireAuth → Rate limit → Handler → Service → pgx · SQL Authentication runs before the limiter, so a rate-limit bucket is keyed by the verified Clerk user rather than by IP. The health probe and this page bypass both; every other route takes the full chain.

Database design

Four tables carry all durable state. Playback lives on the room row itself, which keeps the hottest read path to a single indexed lookup and makes every host action one atomic statement.

Entity relationship diagram for users, rooms, room_members, and messages users id · text · PK clerk_user_id · unique username · unique created_at · timestamp(3) updated_at · timestamp(3) rooms id · text · PK room_code · unique host_user_id · FK users current_video_id · nullable current_duration · nullable is_playing · bool playback_position · float playback_updated_at room_members room_id · PK · FK rooms user_id · PK · FK users joined_at · timestamp(3) messages id · text · PK room_id · FK rooms user_id · FK users content · text · created_at hosts · 1:N · ON DELETE RESTRICT memberships · 1:N room_members · 1:N messages · 1:N
Playback columns live on rooms. Membership is a composite-key join table, so a user can never join the same room twice, and chat rows cascade with both the room and the author.

users

ColumnTypeConstraint
idtextPrimary key, CUID-shaped
clerk_user_idtextUnique, not null
usernametextUnique, not null
created_attimestamp(3)Default now()
updated_attimestamp(3)Written on every update

rooms

ColumnTypeConstraint
idtextPrimary key
room_codetextUnique, six characters
host_user_idtextFK users, ON DELETE RESTRICT
current_video_idtextNullable until a track loads
current_titletextNullable
current_thumbnail_urltextNullable, YouTube hosts only
current_durationdouble precisionNullable, seconds
is_playingbooleanDefault false
playback_positiondouble precisionDefault 0, seconds
playback_updated_attimestamp(3)UTC wall clock, nullable
playback_updated_bytextFK users, ON DELETE SET NULL
created_at / updated_attimestamp(3)Maintained by the writers

room_members

ColumnTypeConstraint
room_idtextComposite PK, FK rooms, CASCADE
user_idtextComposite PK, FK users, CASCADE
joined_attimestamp(3)Default now(), used for succession

Joining is an INSERT … ON CONFLICT DO NOTHING, so repeated joins are idempotent and the original joined_at is preserved.

messages

ColumnTypeConstraint
idtextPrimary key
room_idtextFK rooms, CASCADE
user_idtextFK users, CASCADE
contenttext1–500 UTF-16 units, validated server-side
created_attimestamp(3)Default now()

The join response replays the last 50 messages in ascending order, selected with created_at DESC, id DESC for deterministic ties.

Keys, indexes, and access paths

  • Uniqueness enforces product rules. One profile per Clerk subject, one owner per username, one room per code, one membership per user and room.
  • rooms_host_user_id_idx supports host lookups; room_members_user_id_idx supports eviction by user and “rooms I belong to”.
  • messages_room_id_created_at_idx covers the history window; the query adds id as a tie-breaker so pagination-free replays stay stable.
  • Presence and host succession read members ordered by joined_at ASC, user_id ASC, so the “longest-standing member” rule is deterministic and needs no extra column.
  • Room deletion cascades to memberships and messages; a host cannot be deleted while a room still references them because the host foreign key is RESTRICT.

Migration pipeline

The executable schema is the SQL in internal/db/migrations, embedded into the binary and applied on startup. prisma/schema.prisma is kept as the readable model and the reference for writing the next migration, but nothing executes it.

A session-level PostgreSQL advisory lock serializes concurrent booters, each migration and its version row commit in one transaction, and databases already migrated by Prisma are adopted by reading _prisma_migrations instead of replaying history. A new migration is one SQL file plus the matching change to the schema file.

Two consequences of dropping Prisma

Identifiers are generated in Go. Prisma's cuid() only ran inside the Prisma client, so the Go service generates CUID-shaped ids itself, mixing a millisecond timestamp, a per-process counter, and random characters.

Timestamps are formatted explicitly. Responses render times as 2006-01-02T15:04:05.000Z to match what the client parses, and JSON writers disable Go's default HTML escaping so song titles and chat text keep & characters intact.

Playback synchronization

Playback is not streamed as a position. The server writes a snapshot when the host acts, and each client derives the live position locally from that snapshot and its own clock.

expected = position + (now − updatedAt) × playbackRate position and updatedAt come from the last snapshot; now is the browser clock; playbackRate is the listener's local 0.5×–2× setting.
Snapshot fieldTypeMeaning
videoIdstring | nullThe loaded YouTube video, or null when the room is empty
titlestring | nullDisplay title captured when the host loaded the track
thumbnailUrlstring | nullSanitized YouTube thumbnail URL
durationnumber | nullDuration in seconds, parsed from the ISO-8601 string supplied by the client
isPlayingbooleanWhether the playhead is advancing
positionnumberSeconds elapsed at the instant of updatedAt
updatedAtstring | nullUTC ISO instant of the last control; the interpolation anchor
serverTimestringUTC ISO instant of the response, sent alongside every snapshot
Sequence diagram: host control writes a snapshot, PostgreSQL returns it, and the API broadcasts it to the room Host Go API PostgreSQL Listener playback:control { action, position } verify JWT and membership assert host role UPDATE rooms · timezone('UTC', now()) row snapshot · position, updatedAt, serverTime ack { ok, playback } playback:update · every socket in the room expected = position + (now − updatedAt) 5 s monitor reseeks when drift exceeds 2 s
One write and one broadcast per host action. Listeners do not wait for per-frame updates, and a late packet only shifts the next local derivation.

Why interpolate instead of streaming positions

  • Bandwidth stays flat: one event per action, not sixty per second.
  • Late joiners derive the correct position from the first snapshot, so the room does not need a replay buffer.
  • Buffering and tab throttling are absorbed locally; the server never waits for a player to catch up.

Drift correction on the client

  • A five-second interval compares the live YouTube player time with the derived expectation.
  • If the gap exceeds two seconds, the client silently seeks to the expected position.
  • Elapsed time is multiplied by the current playback rate, so the derived expectation tracks a listener who has changed speed instead of fighting the player.
  • The host runs the same logic; the host is not a special playback source.

The timezone bug this design had to survive

playback_updated_at is a PostgreSQL timestamp without time zone. On a database whose session zone was not UTC, writing now() stored local wall clock while pgx read it back as UTC, so joiners derived a negative elapsed time, clamped it to zero, and never caught up with the host.

All three playback writers now persist timezone('UTC', now()), making the stored value agree with the driver's UTC reads on every database. A committed regression test pins a scratch database to Asia/Kolkata, repeats a real leave-and-rejoin, and fails if any writer reverts to a zone-local now().

Control flows

The REST contract owns durable membership; the socket session owns live attendance. A browser joins a room twice — once over REST to persist membership, once over Socket.IO to receive state — and the two are linked only by the room code.

Sequence diagram: REST membership join followed by the Socket.IO room join acknowledgement Browser REST Socket.IO PostgreSQL POST /api/rooms/{code}/join INSERT … ON CONFLICT DO NOTHING membership row, idempotent 200 room state connect { token } verify JWT load application user room:join { roomCode } membership, playback, last 50 messages presence data, snapshot, history ack { presence, playback, messages, queue }
REST persists membership before any live state is requested. The socket join then answers with four things at once, so the room UI renders in one pass.
Sequence diagram: host disconnect starts a thirty second countdown and a compare-and-swap transfer Host socket Hub PostgreSQL Room members disconnect presence.removeSocket user becomes offline load members · joined_at ASC host:pending { successor, deadline +30 s } reconnect within 30 s cancels the handover otherwise the timer fires UPDATE … WHERE host_user_id = $old 1 row updated · compare-and-swap host:update { reason } + presence:update
Refreshing a tab drops the socket but keeps the member. The grace window absorbs that; only an expired countdown moves the role, and the conditional update makes two competing transfers safe.

Room lifecycle (REST)

  1. Create: generate a six-character code from a 31-character alphabet that omits I, L, O, 0, and 1, then insert the room and the host membership in one transaction, retrying up to ten times on a unique collision.
  2. Join: resolve the caller, load the room, return it unchanged when the caller is already a member, otherwise insert with ON CONFLICT DO NOTHING and return the hydrated room.
  3. Leave: non-hosts delete their membership; a host with a successor updates host_user_id and deletes the membership in one transaction; the last member deletes the room, cascading memberships and messages.
  4. Hooks: leave evicts the user's sockets, clears any pending countdown, and announces the new host through an interface implemented by the realtime hub.

Host transfer

  1. Manual: the host names a member; the update only applies if the caller is still the host, then host:update is broadcast with reason manual.
  2. Disconnect: when the host's last socket drops, the hub arms a 30-second countdown and broadcasts host:pending with the likely successor and deadline.
  3. Return: any new socket from the host inside the window cancels the countdown and clears the pending banner.
  4. Expiry: members are read in join order, the first online member becomes host, and the role change is announced with reason disconnect.

Chat

  1. Validate the payload as non-empty and at most 500 UTF-16 units, matching the Node server's limit for emoji-heavy text.
  2. Re-check membership in the same query that resolves the room id, so a stale connection cannot post.
  3. Insert the message and join the author row in one statement; the database timestamp is the one broadcast.
  4. Broadcast chat:new to the room, then acknowledge the sender. Nothing is broadcast before the write succeeds.

Queue

  1. The queue is host-only and lives in memory, capped at 50 items.
  2. Add, prepend, remove, reorder, and clear each mutate the slice and broadcast the full queue.
  3. Advance dequeues the next track and writes it as a new playback snapshot; an empty queue clears playback.
  4. Every mutation replies with the authoritative queue after the broadcast, so a client never guesses the order.

Real-time contract

The Socket.IO server is mounted at /socket.io/ and speaks Engine.IO v4. The Clerk token travels in the connect packet payload as {"token": "…"}; a rejected handshake answers with connect_error.

Client to server

EventPayloadAuthorizationRate limit
room:join{ roomCode }Member of the room20 / 60s
room:leave{ roomCode }Joined socketnone
playback:set{ roomCode, track }Host only40 / 10s
playback:control{ roomCode, action, position }Host only40 / 10s
playback:clear{ roomCode }Host only40 / 10s
queue:add{ roomCode, track }Host only100 / 10s
queue:prepend{ roomCode, track }Host only100 / 10s
queue:remove{ roomCode, index }Host only100 / 10s
queue:reorder{ roomCode, fromIndex, toIndex }Host only100 / 10s
queue:advance{ roomCode }Host only100 / 10s
queue:clear{ roomCode }Host only100 / 10s
chat:send{ roomCode, content }Member15 / 10s
host:transfer{ roomCode, userId }Host only10 / 60s

Server to client

EventWhenPayload
presence:updateA member's first socket joins, their last socket leaves, or the host changes{ members, hostUserId }, each member carrying an online flag
playback:updateTrack set, play, pause, seek, clear, or queue advanceThe full snapshot described above
queue:updateAny queue mutationThe full ordered queue
chat:newA message was persisted{ id, roomId, userId, username, content, createdAt }
host:updateManual transfer, disconnect transfer, or REST leave{ hostUserId, hostUsername, previousHostUserId, previousHostUsername, reason }
host:pendingA host countdown starts or is cancelled{ pending, hostUserId, hostUsername, successorUsername?, deadline? }

Acknowledgements

Every client-to-server event takes a payload and an acknowledgement callback. Success replies carry ok: true plus the authoritative state for that domain; failures carry ok: false and a message meant for display.

{
  "ok": false,
  "message": "Only the host can control playback"
}

Join acknowledgement

One round trip returns everything the room screen needs, including the derived-state anchors for playback.

{
  "ok": true,
  "presence": {
    "members": [
      { "userId": "usr_…", "username": "ada", "online": true }
    ],
    "hostUserId": "usr_…"
  },
  "playback": {
    "videoId": "dQw4w9WgXcQ",
    "isPlaying": true,
    "position": 42.5,
    "updatedAt": "2026-10-21T09:30:00.000Z",
    "serverTime": "2026-10-21T09:30:01.120Z"
  },
  "messages": [],
  "queue": []
}

Ephemeral stores

StoreShapeBoundCleared by
presenceRoom code → user id → set of socket idsRoom size times tabs per userLast socket disconnect, REST leave, or eviction
queueRoom code → ordered track list50 itemsClear, playback clear, or room exit
pending transfersRoom code → timer, host id, deadlineOne per roomExpiry, reconnect, manual transfer, or leave
connection roomsSocket id → set of joined room codesOne entry per live socketDisconnect or eviction
rate windowsBucket and user → fixed-window counterOne entry per active keyWindow rollover

Why broadcasts are emitted per socket

The Socket.IO library's adapter pre-encodes broadcast frames, and a defect in its WebSocket transport returns from the flush loop after writing a pre-encoded frame instead of continuing, silently dropping every packet behind it. In Jamzy the common case is a broadcast plus an acknowledgement in the same flush, so host actions lost their acknowledgements.

The fix avoids the defective path entirely: the hub looks up the room's socket ids and calls Emit per socket, which never marks a frame pre-encoded. The branch is structurally unreachable rather than avoided by timing, and the cost — encoding once per recipient instead of once per room — is irrelevant at this scale.

Security model

Authentication answers who the caller is; authorization answers what they may do. Both are enforced server-side on every transport, and neither trusts a field the client can set.

Authentication path

  1. Clerk completes sign-in in the browser and issues a short-lived session JWT.
  2. REST calls carry it as Authorization: Bearer …. Missing or malformed tokens answer 401 before any handler runs.
  3. The verifier parses the token header's kid, reads the matching key from an in-memory JWKS map refreshed at most hourly, and verifies signature plus claims. An unknown kid forces a refetch, which handles key rotation.
  4. The token's authorized party is checked against the configured origins, and an empty subject is rejected.
  5. The verified Clerk subject is resolved to an application user row; only that identity enters the request context.
  6. The socket handshake runs the same verifier on the connect payload and attaches the resolved user to the connection.

Authorization matrix

ActionMemberHost
Read room state, presence, historyyesyes
Chatyesyes
Join live socket sessionyesyes
Set, play, pause, seek, clear playbacknoyes
Queue add, remove, reorder, advance, clearnoyes
Transfer the host rolenoyes
Create a room, leave a roomyesyes

Host checks read host_user_id from the database, not from the payload. Chat re-resolves membership in SQL before writing, and a REST leave evicts the user's live sockets.

Input validation

InputRuleEnforced in
UsernameTrimmed, 3–20 characters, letters, numbers, and underscores only; uniqueValidation plus a unique index
Room codeSix characters, uppercase A–Z and 0–9; generated from an alphabet without I, L, O, 0, or 1Room code validation
Chat contentTrimmed, non-empty, at most 500 UTF-16 unitsMessage validation
Search query1–200 UTF-16 unitsMusic validation
Video referenceAn 11-character [A-Za-z0-9_-] id, or a URL on a YouTube host using a watch, embed, shorts, live, or short-link pathMusic validation
Playlist referencePlaylist ID characters, 2–100 long; resolved to at most 50 tracksMusic validation
Thumbnail URLHTTPS only, at most 500 characters, on ytimg.com, ggpht.com, youtube.com, or a subdomain of oneThumbnail sanitizer
Track metadataValid video id; title capped at 300 runes and duration at 20 charactersPlayback track validation
JSON bodyAt most 100 KB, answered with 413 above the capRequest decoding
Queue indexesMust be integers in range; invalid indexes are ignored rather than guessedSocket handlers

REST rate limits

EndpointLimit
GET /api/me60 / 60s
POST /api/users/profile10 / 10m
POST /api/rooms15 / 5m
POST /api/rooms/{code}/join30 / 5m
GET /api/rooms/{code}60 / 5m
POST /api/rooms/{code}/leave60 / 5m
GET /api/music/search30 / 60s
GET /api/music/video60 / 60s
GET /api/music/playlist15 / 60s

Socket rate limits

BucketLimit
room:join20 / 60s
playback:set, control, clear40 / 10s
queue:*100 / 10s
chat:send15 / 10s
host:transfer10 / 60s

Exceeding a limit answers with a message containing the retry delay; REST additionally sends Retry-After.

Transport and headers

  • CORS is an explicit origin allowlist with Vary: Origin, credentials enabled, and 204 preflight responses. Unlisted origins receive no CORS headers.
  • Responses set nosniff, SAMEORIGIN frames, no-referrer, HSTS for 180 days with subdomains, and same-origin opener policy.
  • There is no Content-Security-Policy: the API answers JSON, and this page is a self-contained document with inline styles and scripts and no third-party requests.
  • Socket.IO's HTTP upgrade passes through the logging wrapper, which forwards Hijack, Flush, and Unwrap so the handshake is not broken by instrumentation.

Failure behavior

  • Domain errors carry an HTTP status; handlers stay thin. Internal failures become a generic 500 and never leak SQL or stack traces.
  • Errors use a single message field, except unauthenticated REST calls, which also return authenticated: false.
  • Host-only refusals and other typed application errors are safe to display; unknown internal errors are replaced with a fallback message.
  • Panics are recovered per HTTP route and per socket event, logged with a stack, and contained to one response.
  • Malformed JSON is a client mistake and answers 400, not 500.

Operations and verification

The service is a single binary whose only hard runtime dependency is PostgreSQL and the Clerk secret; the YouTube key is optional, and music routes answer 503 without it. Migrations ship inside the binary, so deployment is a build and a restart.

Startup sequence

  1. Load configuration from the environment; values in the environment win over the optional .env file.
  2. Open the pgx connection pool to PostgreSQL.
  3. Apply embedded migrations under an advisory lock; adopt any existing Prisma migration history.
  4. Construct users, rooms, playback, messages, and music services, then wire them into the socket hub and router.
  5. Serve REST, Socket.IO, the docs page, and the health probe on 0.0.0.0:$PORT.
  6. Shut down gracefully on SIGINT or SIGTERM.

Deployment

PiecePlatformDetail
APIRenderFree web service from the repository blueprint, building ./cmd/api; health probe on /api/health
DatabaseNeonServerless PostgreSQL over TLS
FrontendVercelSPA rewrite to index.html plus static security headers
AuthClerkProduction instance on a custom domain; authorized parties mirror the API's CORS origins
CIGitHub ActionsBuild, vet, format check, and tests on the server; install and build on the client

Test strategy

  • Sixty test functions across fourteen files. Unit tests sit beside the packages and need no database.
  • The end-to-end suite runs the real stack against a real PostgreSQL database and is skipped unless TEST_DATABASE_URL is set.
  • There is no Go Socket.IO client, so the suite includes a hand-written Engine.IO v4 client: it dials over Gorilla WebSocket, frames Engine.IO packets by hand, splits records on 0x1e, and asserts the packets a browser would receive.
  • A timezone regression test pins the database to Asia/Kolkata and repeats a real leave-and-rejoin, so the playhead contract is enforced, not just documented.
  • The Clerk verifier test points the SDK at a stub backend through an httptest server, exercising the cold-cache key fetch without network access.

Observability

  • Every HTTP request logs method, path, status, and duration.
  • Socket connects and disconnects log the user, socket id, and disconnect reason.
  • Host transfer decisions log the room, both hosts, and whether the trigger was manual, disconnect, or leave.
  • Rate-limit rejections and recovered panics log warnings and stacks respectively.
  • GET /api/health is the platform liveness probe and runs no authentication, database query, or rate limit.

Known limitations

  • Single instance. Presence, queue, countdowns, and rate windows live in process memory. A restart loses them, and a second instance would not share them; a Redis adapter and a shared store are the way out.
  • Cold starts. On free tiers the API and database sleep; the first request after a pause can take 30–60 seconds.
  • Clock skew. The playhead compares the browser clock with the server timestamp, so a badly skewed client can drift until the next reseek.
  • Documentation drift. The OpenAPI document is hand-written and must be updated with the handlers it describes.
  • No browser automation. The client is verified by a strict TypeScript build and a manual pass through the full flow, not by a committed browser test.

What scaling would require

  • Shared realtime state: move presence, queue, and pending transfers behind Redis and enable a Socket.IO adapter so any instance can broadcast to any room.
  • Distributed limiting: key fixed windows in the shared store rather than in each process.
  • Instrumentation: metrics for socket latency, broadcast fan-out, playback drift, and rate-limit rejections, with tracing across HTTP and socket paths.
  • Queue durability: persist queues per room if they should survive a restart or follow a room across instances.
  • Automated client smoke test: drive sign-in, onboarding, room creation, playback, and chat in CI.

REST API reference

10 endpoints

Every REST route rendered from the embedded OpenAPI 3.1 document. Every route under /api except the health probe requires a Clerk session token; rate limits are per authenticated user and per endpoint. The machine-readable document is served at /docs/openapi.json.