02.Carrel
Active Session
01 . Project Overview

Carrel

Real-time collaborative code & notes workspace with Yjs CRDTs and binary WebSocket multiplexing

CRDT Workspace • Binary WebSockets • Fastify + SQLite

carrel/hero.webp
Hero view

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

View Source Code
02 . Core Rationale

Why I Built It

Understanding the core problems, proposed solutions, and realized product achievements.

The problem

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.

What actually happens
T+0ms

Host opens room, sets optional scrypt-hashed passcode, and shares invite link.

T+2s

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.

T+2.1s

Browser upgrades /ws with the ticket; server consumes the nonce once so replay attacks fail immediately.

T+15s

Host's Wi-Fi drops unexpectedly. Instead of instantly breaking room admin, server enters a 5000ms HOST_GRACE_MS window and marks hostPending.

T+18s

Host reconnects inside the 5s grace window — socket re-attaches seamlessly with zero host_changed churn.

The fix, step by step
1
Multiplex 3 protocols over one WebSocket with a 1-byte header
shared/src/frames.ts

Frame 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.

2
Isolate CPU-heavy scrypt hashing with a strict concurrency queue
server/src/throttle.ts

Passcode 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.

3
Run deterministic seniority succession + 30s flicker grace
server/src/host.ts

If grace expires, min(joinedAt) (tie-broken by clientId) promotes the next senior occupant; a 30s SENIORITY_WINDOW_MS map preserves standing across quick refreshes.

4
Coalesce awareness frames & lerp remote carets at 80ms
client/src/collab/CarrelProvider.ts

CodeMirror 6 renders remote carets with an 80ms interpolation curve (automatically disabled under prefers-reduced-motion) while coalescing rapid awareness bursts.

Result

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
03 . System Pipeline

Architecture Pipelines

Visual system flow diagrams representing data pipelines and structured checks.

Pipeline Data flow nodes (Glows on Hover)
01 // shared-proto

@carrel/shared

Shared Zod schemas, binary frame constants, close codes (4000–4008), and syntax language definitions.

02 // fastify-auth

Fastify + HMAC Tickets

Single-use nonce-bound WS upgrade tickets, TRUST_PROXY anti-spoof rate limiting, and progressive passcode lockouts.

03 // yjs-sqlite

Y.Doc + SQLite WAL

In-memory Y.Doc per room with MAX_DOC_BYTES guard and debounced binary snapshot persistence in better-sqlite3.

04 // host-fsm

Deterministic Host FSM

5000ms grace timer, atomic make_host handover, vacant room promotion, and creator-key reclamation.

05 // cm6-client

React + CodeMirror 6

Dark & Paper editorial themes, 80ms lerp carets, double-click pinned gutter highlights, and 4-state presence.

04 . Core Capabilities

Features & Capabilities

Key features and built-in components implemented inside the codebase.

Feature Checklist
  • ✓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
03 . Technical Barriers

Solving Complex Bottlenecks

A deep dive into security rule architectures, race conditions, and verification solutions.

Problem

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.

Why it was difficult

Synchronous hashing stalls the single-threaded event loop, while unbounded async libuv calls exhaust the threadpool and starve I/O.

The fix
1
Bind non-blocking scrypt to a 4-slot semaphore queue
server/src/throttle.ts
2
Apply progressive lockout backoff per normalized client IP
server/src/throttle.ts
3
Disable naive X-Forwarded-For trust unless TRUST_PROXY is explicitly set
server/src/index.ts
What I learned

"Auth security isn't just picking scrypt over SHA-256 — unthrottled expensive cryptography is itself a denial-of-service vector against real-time sockets."

06 . Build Log Timeline

Development Journey

A chronological day-by-day log detailing core milestones and features added.

Milestone timeline
Phase 1–2

Shared Binary Protocol & Fastify Core

Defined 1-byte framed multiplexing in @carrel/shared and wired Yjs + SQLite WAL snapshot persistence in @carrel/server.

Phase 3–4

HMAC Tickets, Scrypt Limiter & CodeMirror 6

Implemented nonce tickets, concurrency-4 scrypt throttling, custom Dark/Paper syntax tokens, and 80ms lerped remote carets.

Phase 5

Host Succession FSM, Gutter Highlights & E2E Suite

Shipped 5000ms host grace, atomic handover, synchronized gutter pins, and full Playwright multi-user verification.

07 . System Reliability

Operational Metrics

No public-facing site to audit — these are the safeguards that keep an unattended pipeline honest.

Auth ticket model1-use HMAC

nonce-bound upgrade tickets expire after TICKET_TTL_MS and cannot be replayed across sockets

Crypto isolation4 max scrypt

concurrency semaphore ensures password checks never starve real-time Yjs sync frames

Host grace window5000 ms

absorbs brief Wi-Fi drops before running deterministic min(joinedAt) succession

Document guardMAX_DOC_BYTES

oversized binary payloads are rejected cleanly without tearing down valid peer connections

05 . Architecture Decisions

Trade-off Explanations

Concise rationales for technology selections and future roadmaps.

Design Choices

1-Byte Multiplexed Frames Over Socket.IO

Raw WebSockets + Yjs

Instead 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 6

CodeMirror 6 ships dramatically smaller client JS than Monaco while giving clean extension hooks for custom Dark/Paper syntax tokens and lerped remote caret decorations.

If I built V2...

"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.
06 . Screenshots

Visual Gallery

Scrollable preview tracks showcasing panel responsive structures.

Horizontal Screenshot Scroll
Dark Workspace & Remote Carets
Dark Workspace & Remote Carets
Host Handover & Activity Feed
Host Handover & Activity Feed
host handover & presence
Secondary screenshot

Finished exploring this session?

End the workspace session to release resources and return back to the primary portfolio index.

Opening.theCarrel.

> Initializing Session...

INITIALIZING_WORKSPACE·0%