Carrel
Real-time collaborative code & notes workspace with Yjs CRDTs and binary WebSocket multiplexing
CRDT Workspace • Binary WebSockets • Fastify + SQLite

Description
A hardened TypeScript monorepo workspace built around raw WebSocket binary frame multiplexing (sync, awareness, and control) over Yjs CRDTs, Fastify, and SQLite WAL snapshots. Features deterministic host-succession state machines, single-use nonce HMAC tickets, scrypt concurrency limiting, and a CodeMirror 6 editor with 80ms lerp remote carets.
Timeline
10 Days
Role
Systems & Full-Stack Engineer
Status
Production
Year
2026
Deployment
Monorepo / Docker
Core Stack
Fastify / Yjs / CodeMirror 6
Why I Built It
Understanding the core problems, proposed solutions, and realized product achievements.
Most collaborative web editors either wrap WebSockets in heavy JSON polling or accept raw unauthenticated sockets that crumble under spoofed proxy headers, scrypt event-loop blocking, and host tab refreshes.
Host opens room, sets optional scrypt-hashed passcode, and shares invite link.
Peer requests POST /api/rooms/:id/ticket — server verifies passcode inside a concurrency-4 scrypt limiter and issues a nonce-bound single-use HMAC ticket.
Browser upgrades /ws with the ticket; server consumes the nonce once so replay attacks fail immediately.
Host's Wi-Fi drops unexpectedly. Instead of instantly breaking room admin, server enters a 5000ms HOST_GRACE_MS window and marks hostPending.
Host reconnects inside the 5s grace window — socket re-attaches seamlessly with zero host_changed churn.
Multiplex 3 protocols over one WebSocket with a 1-byte header
shared/src/frames.tsFrame byte 0 carries raw y-protocols/sync binary updates, byte 1 carries awareness (selections/carets/line highlights), and byte 2 carries typed JSON control events.
Isolate CPU-heavy scrypt hashing with a strict concurrency queue
server/src/throttle.tsPasscode checks use async scrypt with per-room random salts inside a concurrency-4 limiter so brute-force bursts can't starve Fastify's WebSocket event loop.
Run deterministic seniority succession + 30s flicker grace
server/src/host.tsIf grace expires, min(joinedAt) (tie-broken by clientId) promotes the next senior occupant; a 30s SENIORITY_WINDOW_MS map preserves standing across quick refreshes.
Coalesce awareness frames & lerp remote carets at 80ms
client/src/collab/CarrelProvider.tsCodeMirror 6 renders remote carets with an 80ms interpolation curve (automatically disabled under prefers-reduced-motion) while coalescing rapid awareness bursts.
Zero race-condition host splits, bounded memory/CPU under brute-force tests, and sub-frame collaborative editing verified across Playwright multi-peer E2E tests.
- Binary frame types
- 3 muxed
- Scrypt concurrency cap
- 4 ops
- Caret interpolation
- 80 ms lerp
- Kick lockout window
- 10 min
Architecture Pipelines
Visual system flow diagrams representing data pipelines and structured checks.
@carrel/shared
Shared Zod schemas, binary frame constants, close codes (4000–4008), and syntax language definitions.
Fastify + HMAC Tickets
Single-use nonce-bound WS upgrade tickets, TRUST_PROXY anti-spoof rate limiting, and progressive passcode lockouts.
Y.Doc + SQLite WAL
In-memory Y.Doc per room with MAX_DOC_BYTES guard and debounced binary snapshot persistence in better-sqlite3.
Deterministic Host FSM
5000ms grace timer, atomic make_host handover, vacant room promotion, and creator-key reclamation.
React + CodeMirror 6
Dark & Paper editorial themes, 80ms lerp carets, double-click pinned gutter highlights, and 4-state presence.
Features & Capabilities
Key features and built-in components implemented inside the codebase.
- ✓Yjs CRDT collaborative editing over 1-byte multiplexed binary WebSocket frames (sync, awareness, control)
- ✓Single-use nonce HMAC WebSocket upgrade tickets with TRUST_PROXY-aware rate limiting
- ✓Async scrypt passcode hashing capped at 4 concurrent operations to protect event-loop responsiveness
- ✓Deterministic host succession: 5000ms reconnect grace window, seniority election, and atomic make_host handover
- ✓CodeMirror 6 editor with custom Dark & Paper themes, 80ms lerp remote carets, and synchronized gutter line highlights
- ✓4-state presence tracking (Typing -> Active -> Idle at 60s -> Away on hidden tab) with frame coalescing
- ✓Duplicate client replacement (close code 4000), 10-minute kick lockout (4003), and MAX_DOC_BYTES size guards
Solving Complex Bottlenecks
A deep dive into security rule architectures, race conditions, and verification solutions.
Password verification needs slow key derivation (scrypt), but running dozens of concurrent scrypt checks on the Node server would block WebSocket keystrokes for everyone else.
Synchronous hashing stalls the single-threaded event loop, while unbounded async libuv calls exhaust the threadpool and starve I/O.
Bind non-blocking scrypt to a 4-slot semaphore queue
server/src/throttle.tsApply progressive lockout backoff per normalized client IP
server/src/throttle.tsDisable naive X-Forwarded-For trust unless TRUST_PROXY is explicitly set
server/src/index.ts"Auth security isn't just picking scrypt over SHA-256 — unthrottled expensive cryptography is itself a denial-of-service vector against real-time sockets."
Development Journey
A chronological day-by-day log detailing core milestones and features added.
Shared Binary Protocol & Fastify Core
Defined 1-byte framed multiplexing in @carrel/shared and wired Yjs + SQLite WAL snapshot persistence in @carrel/server.
HMAC Tickets, Scrypt Limiter & CodeMirror 6
Implemented nonce tickets, concurrency-4 scrypt throttling, custom Dark/Paper syntax tokens, and 80ms lerped remote carets.
Host Succession FSM, Gutter Highlights & E2E Suite
Shipped 5000ms host grace, atomic handover, synchronized gutter pins, and full Playwright multi-user verification.
Operational Metrics
No public-facing site to audit — these are the safeguards that keep an unattended pipeline honest.
nonce-bound upgrade tickets expire after TICKET_TTL_MS and cannot be replayed across sockets
concurrency semaphore ensures password checks never starve real-time Yjs sync frames
absorbs brief Wi-Fi drops before running deterministic min(joinedAt) succession
oversized binary payloads are rejected cleanly without tearing down valid peer connections
Trade-off Explanations
Concise rationales for technology selections and future roadmaps.
1-Byte Multiplexed Frames Over Socket.IO
Raw WebSockets + YjsInstead of pulling in Socket.IO overhead and extra polling layers, a single WebSocket prefixes binary Yjs sync/awareness frames and JSON control events with 1 byte—keeping latency tight and protocol code inspectable.
Zero-Infra Persistence With Debounced Snapshots
better-sqlite3 (WAL)Keeping active Y.Doc state in memory and flushing debounced binary snapshots into SQLite WAL mode gives crash durability in one Docker container without Redis or Postgres.
Modular Editor State Over Heavy Monaco Bundles
CodeMirror 6CodeMirror 6 ships dramatically smaller client JS than Monaco while giving clean extension hooks for custom Dark/Paper syntax tokens and lerped remote caret decorations.
"Evaluating scaling adjustments and cache controls shows true engineering maturity."
- ✓Add end-to-end encrypted room payloads (client-side key derivation) so even the server only stores opaque CRDT blobs.
- ✓Support multi-file tabs inside a single Carrel room backed by nested Y.Map document namespaces.
- ✓Stream compressed incremental update logs between debounced full snapshots to shrink disk writes under heavy paste bursts.
Visual Gallery
Scrollable preview tracks showcasing panel responsive structures.
Finished exploring this session?
End the workspace session to release resources and return back to the primary portfolio index.

