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.
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.
| Layer | Choice | Why |
|---|---|---|
| HTTP | Go standard library net/http with method-prefixed ServeMux patterns | The API surface is ten endpoints; a framework would add a dependency without removing work. |
| Persistence | pgx with hand-written SQL in per-domain services | The query surface is small and the SQL is the clearest description of each access path. No ORM, no generated types. |
| Realtime | Socket.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. |
| Auth | Clerk session JWTs verified in-process | No identity service of our own, and no per-request network call once the JWKS cache is warm. |
| Client | React 19, Vite, strict TypeScript, YouTube IFrame API | The client renders state and reports local player events; all authority stays server-side. |
| Delivery | Render for the API, Neon for PostgreSQL, Vercel for the SPA, GitHub Actions for CI | Every 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.
| Package | Responsibility |
|---|---|
| cmd/api | Wiring: configuration, connection pool, migrations, services, socket hub, HTTP server, graceful shutdown |
| internal/httpapi | The route table and dependency wiring for REST, docs, health, and the socket mount |
| internal/httpx | Recovery, request logging, security headers, CORS, Clerk authentication, fixed-window rate limits, JSON responses |
| internal/auth | Session token verification, key-id parsing, the in-memory JWKS cache, and the one-method Verifier interface |
| internal/realtime | Socket hub, presence, queue, host transfer, room broadcasts, and per-event panic recovery |
| internal/rooms | Room creation, idempotent membership, host succession in transactions, and leave semantics |
| internal/playback | The three snapshot writers, snapshot reads, and position normalization |
| internal/db | pgx pool, embedded migrations, Prisma adoption, advisory locking |
| internal/openapi | The 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
500without 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
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.
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
| Column | Type | Constraint |
|---|---|---|
| id | text | Primary key, CUID-shaped |
| clerk_user_id | text | Unique, not null |
| username | text | Unique, not null |
| created_at | timestamp(3) | Default now() |
| updated_at | timestamp(3) | Written on every update |
rooms
| Column | Type | Constraint |
|---|---|---|
| id | text | Primary key |
| room_code | text | Unique, six characters |
| host_user_id | text | FK users, ON DELETE RESTRICT |
| current_video_id | text | Nullable until a track loads |
| current_title | text | Nullable |
| current_thumbnail_url | text | Nullable, YouTube hosts only |
| current_duration | double precision | Nullable, seconds |
| is_playing | boolean | Default false |
| playback_position | double precision | Default 0, seconds |
| playback_updated_at | timestamp(3) | UTC wall clock, nullable |
| playback_updated_by | text | FK users, ON DELETE SET NULL |
| created_at / updated_at | timestamp(3) | Maintained by the writers |
room_members
| Column | Type | Constraint |
|---|---|---|
| room_id | text | Composite PK, FK rooms, CASCADE |
| user_id | text | Composite PK, FK users, CASCADE |
| joined_at | timestamp(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
| Column | Type | Constraint |
|---|---|---|
| id | text | Primary key |
| room_id | text | FK rooms, CASCADE |
| user_id | text | FK users, CASCADE |
| content | text | 1–500 UTF-16 units, validated server-side |
| created_at | timestamp(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_idxsupports host lookups;room_members_user_id_idxsupports eviction by user and “rooms I belong to”.messages_room_id_created_at_idxcovers the history window; the query addsidas 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.
| Snapshot field | Type | Meaning |
|---|---|---|
| videoId | string | null | The loaded YouTube video, or null when the room is empty |
| title | string | null | Display title captured when the host loaded the track |
| thumbnailUrl | string | null | Sanitized YouTube thumbnail URL |
| duration | number | null | Duration in seconds, parsed from the ISO-8601 string supplied by the client |
| isPlaying | boolean | Whether the playhead is advancing |
| position | number | Seconds elapsed at the instant of updatedAt |
| updatedAt | string | null | UTC ISO instant of the last control; the interpolation anchor |
| serverTime | string | UTC ISO instant of the response, sent alongside every snapshot |
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.
Room lifecycle (REST)
- Create: generate a six-character code from a 31-character alphabet that omits
I,L,O,0, and1, then insert the room and the host membership in one transaction, retrying up to ten times on a unique collision. - Join: resolve the caller, load the room, return it unchanged when the caller is already a member, otherwise insert with
ON CONFLICT DO NOTHINGand return the hydrated room. - Leave: non-hosts delete their membership; a host with a successor updates
host_user_idand deletes the membership in one transaction; the last member deletes the room, cascading memberships and messages. - 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
- Manual: the host names a member; the update only applies if the caller is still the host, then
host:updateis broadcast with reasonmanual. - Disconnect: when the host's last socket drops, the hub arms a 30-second countdown and broadcasts
host:pendingwith the likely successor and deadline. - Return: any new socket from the host inside the window cancels the countdown and clears the pending banner.
- Expiry: members are read in join order, the first online member becomes host, and the role change is announced with reason
disconnect.
Chat
- Validate the payload as non-empty and at most 500 UTF-16 units, matching the Node server's limit for emoji-heavy text.
- Re-check membership in the same query that resolves the room id, so a stale connection cannot post.
- Insert the message and join the author row in one statement; the database timestamp is the one broadcast.
- Broadcast
chat:newto the room, then acknowledge the sender. Nothing is broadcast before the write succeeds.
Queue
- The queue is host-only and lives in memory, capped at 50 items.
- Add, prepend, remove, reorder, and clear each mutate the slice and broadcast the full queue.
- Advance dequeues the next track and writes it as a new playback snapshot; an empty queue clears playback.
- 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
| Event | Payload | Authorization | Rate limit |
|---|---|---|---|
| room:join | { roomCode } | Member of the room | 20 / 60s |
| room:leave | { roomCode } | Joined socket | none |
| playback:set | { roomCode, track } | Host only | 40 / 10s |
| playback:control | { roomCode, action, position } | Host only | 40 / 10s |
| playback:clear | { roomCode } | Host only | 40 / 10s |
| queue:add | { roomCode, track } | Host only | 100 / 10s |
| queue:prepend | { roomCode, track } | Host only | 100 / 10s |
| queue:remove | { roomCode, index } | Host only | 100 / 10s |
| queue:reorder | { roomCode, fromIndex, toIndex } | Host only | 100 / 10s |
| queue:advance | { roomCode } | Host only | 100 / 10s |
| queue:clear | { roomCode } | Host only | 100 / 10s |
| chat:send | { roomCode, content } | Member | 15 / 10s |
| host:transfer | { roomCode, userId } | Host only | 10 / 60s |
Server to client
| Event | When | Payload |
|---|---|---|
| presence:update | A member's first socket joins, their last socket leaves, or the host changes | { members, hostUserId }, each member carrying an online flag |
| playback:update | Track set, play, pause, seek, clear, or queue advance | The full snapshot described above |
| queue:update | Any queue mutation | The full ordered queue |
| chat:new | A message was persisted | { id, roomId, userId, username, content, createdAt } |
| host:update | Manual transfer, disconnect transfer, or REST leave | { hostUserId, hostUsername, previousHostUserId, previousHostUsername, reason } |
| host:pending | A 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
| Store | Shape | Bound | Cleared by |
|---|---|---|---|
| presence | Room code → user id → set of socket ids | Room size times tabs per user | Last socket disconnect, REST leave, or eviction |
| queue | Room code → ordered track list | 50 items | Clear, playback clear, or room exit |
| pending transfers | Room code → timer, host id, deadline | One per room | Expiry, reconnect, manual transfer, or leave |
| connection rooms | Socket id → set of joined room codes | One entry per live socket | Disconnect or eviction |
| rate windows | Bucket and user → fixed-window counter | One entry per active key | Window 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
- Clerk completes sign-in in the browser and issues a short-lived session JWT.
- REST calls carry it as
Authorization: Bearer …. Missing or malformed tokens answer401before any handler runs. - 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 unknownkidforces a refetch, which handles key rotation. - The token's authorized party is checked against the configured origins, and an empty subject is rejected.
- The verified Clerk subject is resolved to an application user row; only that identity enters the request context.
- The socket handshake runs the same verifier on the connect payload and attaches the resolved user to the connection.
Authorization matrix
| Action | Member | Host |
|---|---|---|
| Read room state, presence, history | yes | yes |
| Chat | yes | yes |
| Join live socket session | yes | yes |
| Set, play, pause, seek, clear playback | no | yes |
| Queue add, remove, reorder, advance, clear | no | yes |
| Transfer the host role | no | yes |
| Create a room, leave a room | yes | yes |
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
| Input | Rule | Enforced in |
|---|---|---|
| Username | Trimmed, 3–20 characters, letters, numbers, and underscores only; unique | Validation plus a unique index |
| Room code | Six characters, uppercase A–Z and 0–9; generated from an alphabet without I, L, O, 0, or 1 | Room code validation |
| Chat content | Trimmed, non-empty, at most 500 UTF-16 units | Message validation |
| Search query | 1–200 UTF-16 units | Music validation |
| Video reference | An 11-character [A-Za-z0-9_-] id, or a URL on a YouTube host using a watch, embed, shorts, live, or short-link path | Music validation |
| Playlist reference | Playlist ID characters, 2–100 long; resolved to at most 50 tracks | Music validation |
| Thumbnail URL | HTTPS only, at most 500 characters, on ytimg.com, ggpht.com, youtube.com, or a subdomain of one | Thumbnail sanitizer |
| Track metadata | Valid video id; title capped at 300 runes and duration at 20 characters | Playback track validation |
| JSON body | At most 100 KB, answered with 413 above the cap | Request decoding |
| Queue indexes | Must be integers in range; invalid indexes are ignored rather than guessed | Socket handlers |
REST rate limits
| Endpoint | Limit |
|---|---|
| GET /api/me | 60 / 60s |
| POST /api/users/profile | 10 / 10m |
| POST /api/rooms | 15 / 5m |
| POST /api/rooms/{code}/join | 30 / 5m |
| GET /api/rooms/{code} | 60 / 5m |
| POST /api/rooms/{code}/leave | 60 / 5m |
| GET /api/music/search | 30 / 60s |
| GET /api/music/video | 60 / 60s |
| GET /api/music/playlist | 15 / 60s |
Socket rate limits
| Bucket | Limit |
|---|---|
| room:join | 20 / 60s |
| playback:set, control, clear | 40 / 10s |
| queue:* | 100 / 10s |
| chat:send | 15 / 10s |
| host:transfer | 10 / 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, and204preflight responses. Unlisted origins receive no CORS headers. - Responses set
nosniff,SAMEORIGINframes,no-referrer, HSTS for 180 days with subdomains, andsame-originopener 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, andUnwrapso the handshake is not broken by instrumentation.
Failure behavior
- Domain errors carry an HTTP status; handlers stay thin. Internal failures become a generic
500and never leak SQL or stack traces. - Errors use a single
messagefield, except unauthenticated REST calls, which also returnauthenticated: 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, not500.
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
- Load configuration from the environment; values in the environment win over the optional
.envfile. - Open the pgx connection pool to PostgreSQL.
- Apply embedded migrations under an advisory lock; adopt any existing Prisma migration history.
- Construct users, rooms, playback, messages, and music services, then wire them into the socket hub and router.
- Serve REST, Socket.IO, the docs page, and the health probe on
0.0.0.0:$PORT. - Shut down gracefully on
SIGINTorSIGTERM.
Deployment
| Piece | Platform | Detail |
|---|---|---|
| API | Render | Free web service from the repository blueprint, building ./cmd/api; health probe on /api/health |
| Database | Neon | Serverless PostgreSQL over TLS |
| Frontend | Vercel | SPA rewrite to index.html plus static security headers |
| Auth | Clerk | Production instance on a custom domain; authorized parties mirror the API's CORS origins |
| CI | GitHub Actions | Build, 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_URLis 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/Kolkataand 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
httptestserver, 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/healthis 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 endpointsEvery 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.