~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zlay

atproto relay in zig · mirror of https://tangled.org/zat.dev/zlay

0
0
378 lines · 21.3 KB Raw History
# historical design notes

These notes describe earlier implementations and projections, including the RocksDB collection index. They are retained as history, not the current architecture or a capacity guarantee. See [current design](../architecture/design.md).

# zlay — system design

an AT Protocol relay that crawls PDS instances directly, validates commit
signatures, and rebroadcasts to downstream consumers over WebSocket.

## code organization

`src/` holds exactly two things: `main.zig` (the composition root / entrypoint)
and `internal/` (everything else). a top-level file is a declaration that it is
core to the system; only `main.zig` qualifies. this mirrors the sibling `zat`
repo's `root.zig` + `internal/` convention.

inside `internal/`, most modules are flat files — each is one cohesive concern
(`slurper`, `subscriber`, `frame_worker`, `host_ops`, `validator`, `event_log`,
`broadcaster`). a subfolder is introduced **only when a cluster earns it with
several cohesive files**, never to make an abstract pipeline-stage statement:

- `internal/collection_index/` — the secondary index feature: the RocksDB
  `index` plus its `backfill`, `cleaner`, and `resync` maintenance.
- `internal/api/` — XRPC + admin HTTP handlers (`router`, `http`, `xrpc`,
  `admin`, `main` facade).
- `internal/util/` — extensions to the standard library: things that could
  have been in `std` but aren't (`env`, `time`, `lru`, `ring_buffer`,
  `thread_pool`). flat namespace (`util.timestamp`); no domain knowledge.
- `internal/atproto/` — AT Protocol / relay domain logic shared across modules
  (`hostname` parsing + validation, `host_check` describeServer/SSRF/relay-loop
  detection). encodes relay *policy*, so it is not `util`.

the rule: a folder must justify itself with multiple cohesive files; otherwise
it's a flat file in `internal/`. a single-file folder is the smell we avoid.
if a helper gets copy-pasted into a third module, move it into `util/` or
`atproto/` rather than re-declaring it.

tests are aggregated through `src/tests.zig` (rooted at `src/` so every
`internal/` import resolves) — add an `@import` line there for a new file with
`test` blocks.

## data flow

```
PDS instances (N hosts)
  │
  ▼
Subscriber (one reader thread per host)
  │  header decode, cursor tracking, rate limiting
  │  submits raw frame to processing pool
  ▼
Frame Pool (configurable workers, default 16)
  │  full CBOR decode, DID → UID resolution via postgres
  │  ▼
  │  Validator
  │  │  cache lookup: DID → signing key (secp256k1 / p256)
  │  │  cache hit → verify commit signature (zat SDK)
  │  │  cache miss → skip, queue background resolution
  │  ▼
  │  DiskPersist
  │  │  append to event log (28-byte LE header + CBOR payload)
  │  │  assign relay sequence number (monotonic, relay-scoped)
  │  │  write postgres metadata (account state, host cursor)
  │  ▼
  │  Broadcaster
  │     resequence frame with relay seq
  │     fan out to all connected consumers via SharedFrame (ref-counted)
  │     per-consumer buffer (65,536 frames) + write fiber; a consumer whose
  │     buffer fills is kicked by flag only (ConsumerTooSlow is sent by its
  │     own write fiber) — the broadcaster never writes to a consumer socket
  ▼
Downstream consumers (WebSocket)
```

additionally:
- **collection index** (RocksDB): subscriber calls `trackCommitOps` on each
  validated commit; stores `(collection, did)` pairs for `listReposByCollection`
- **event log**: append-only files rotated every 10K events, configurable
  retention (env: `RELAY_RETENTION_HOURS`; production runs 2h — at ~185
  segments/hour the window costs ~8.5G/hour, and deep replay belongs to
  stream.waow.tech's archive). supports cursor replay from disk (in-memory
  50K-frame ring as the no-persist fallback)
- **cursor replay**: a consumer that connects with a cursor is flagged
  `replaying` and skipped by live fan-out while disk playback runs in 4,096
  entry / 16 MiB chunks at the consumer's own pace (replay waits for buffer
  space instead of kicking). once a chunk comes back empty, live frames are
  staged, one more disk pass collects what was broadcast meanwhile (every
  broadcast frame is on disk first), and staged frames newer than the last
  replayed seq follow in order: no gap, no reordering, duplicates only at the
  boundary. playback reads outside the persist mutex through a 256 KiB block
  reader. the publish path (`persist_order` lock, `BroadcastQueue.push`)
  spins for a short budget and then sleeps between retries, so a stalled drain
  costs backpressure, not CPU (see the 2026-10-18 incident in the relay repo)
- **slurper**: orchestrates subscribers. bootstraps host list from seed relay's
  `listHosts` API, spawns/stops workers, processes `requestCrawl` requests

## threading model

| thread type | count at ~2,750 PDS | stack size | responsibility |
|---|---|---|---|
| subscriber readers | ~2,750 | 8 MB | one per host — lightweight WebSocket read loop, header decode, cursor tracking, rate limiting, submit to pool, upstream keepalive (zio: the subscriber fiber pings while the read loop runs as a cancelable task; Threaded: SO_RCVTIMEO heartbeat in the read loop) |
| frame pool workers | 16 (env: `FRAME_WORKERS`) | 8 MB | CBOR decode, validation, DB persist, broadcast |
| resolver threads | 4–8 (env: `RESOLVER_THREADS`) | 8 MB | DID document resolution, signing key extraction, cache population |
| consumer write threads | 1 per downstream consumer | 8 MB | drain ring buffer → WebSocket write, ping/pong keepalive |
| flush thread | 1 | 8 MB | batched writes to event log (100ms or 400 events) |
| GC thread | 1 | 8 MB | event log file cleanup every 10 minutes |
| crawl queue thread | 1 | 8 MB | process `requestCrawl` — validate hostname, describeServer, spawn worker |
| metrics server | 1 | 8 MB | HTTP on internal port, prometheus scrape |
| main thread | 1 | default | signal handling, shutdown coordination |

total: ~2,770 + consumers. subscriber reader threads run blocking WebSocket
read loops — lightweight, no async runtime, no event loop. each reader does
minimal work per frame (header decode, cursor update, rate limit check) and
spends most time blocked in `recv()`. heavy processing (full CBOR decode, CAR
parse, ECDSA verify, DB persist, broadcast) runs on pool workers. the header
is intentionally decoded twice — once by the reader for routing, once by the
pool worker for full processing. this double decode costs ~1–2μs per frame,
far cheaper than serializing parsed state across threads.

the 8 MB stack size (vs zig's 16 MB default) supports ReleaseSafe's TLS
handshake path (~134 KiB peak stack from `tls.Client.init` + `KeyShare.init`).
only touched pages count as RSS — reader threads use ~0.45 MiB RSS each since
the deepest paths (crypto, CBOR, DB) now run on pool workers.

## memory model

**allocator**: `std.heap.c_allocator` (libc malloc). glibc has per-thread
arenas and `madvise`-based page return. the general-purpose allocator (GPA)
is a debug allocator that never returns freed pages — unsuitable for
long-running servers. **mimalloc was evaluated (2026-06) and ruled out** — it
does not return memory to the OS under zlay's ~2,800-thread-heap workload, RSS
climbs unbounded (v2/v3/purge-forced/even under glibc). glibc malloc's
page-return is what keeps RSS flat; see [musl-investigation.md](musl-investigation.md).

**shared TLS CA bundle**: loaded once by the slurper, passed to all ~2,750
subscriber connections via `config.ca_bundle`. without this, each websocket.zig
TLS client calls `Bundle.rescan()` and loads its own copy (~800 KB each),
totaling ~2.2 GiB of duplicate CA certificates in memory.

**arena per frame**: each subscriber creates a `std.heap.ArenaAllocator` per
WebSocket message. all CBOR decode temporaries, CAR parse buffers, and MST
nodes live in this arena. freed in bulk after the frame is processed. this
prevents fragmentation from per-field allocations.

**shared frames**: the broadcaster creates one `SharedFrame` per broadcast.
consumers acquire references; the frame is freed when the last consumer
releases. this avoids copying frame bytes per consumer.

**validator cache**: `StringHashMap(CachedKey)` — DID string → 75-byte
fixed-size struct (key type + 33-byte compressed pubkey + resolve timestamp).
capped at 250K entries (env: `VALIDATOR_CACHE_SIZE`), LRU-ish eviction of
oldest 10% when full. ~37 MB at capacity. the resolve queue uses a
`StringHashMapUnmanaged(void)` as a dedupe set to prevent the same DID from
being queued multiple times. migration checks are interleaved with DID
resolutions (1 per 10) to prevent starvation.

**ring buffer**: 50K-entry in-memory frame history for cursor replay when
disk replay isn't available. entries are `(seq, data)` pairs with data duped
from broadcast.

## persistence

### event log (append-only files)

format matches indigo's `diskpersist`:
```
[4B flags LE] [4B kind LE] [4B payload_len LE] [8B uid LE] [8B seq LE] [payload]
```

files named `evts-{startSeq}`, rotated every 10K events. buffered writes
flushed every 100ms or 400 events (whichever comes first). GC runs every 10
minutes: deletes refs+files older than `RELAY_RETENTION_HOURS` (production:
2h), enforces the `RELAY_MAX_EVENTS_GB` byte cap, then sweeps orphaned
segments no `log_file_refs` row references (a failed file delete would
otherwise leak the file forever — 2026-08-27).

frame workers also flush accepted events before updating repo state or
acknowledging upstream progress. each subscriber keeps a bounded queue of 256
completion receipts: its cursor advances only through the successful prefix,
even when workers finish different DIDs out of order. a processing failure
causes reconnect from that prefix; connection teardown waits for outstanding
receipts before freeing their storage. these writes protect process-restart
replay; they do not add an fsync guarantee for host or power failure.

shutdown stops readers and drains frame workers while DB and broadcast
consumers remain running, then flushes the log and stops those consumers.
rotation prepares and registers the replacement segment before releasing the
active file, so allocation, file creation, or DB errors leave it usable.

cursor replay: `playback(cursor)` binary-searches log files for the starting
seq, then streams entries forward. the broadcaster tries disk first, falls
back to in-memory ring buffer.

### postgres

tables:
- `account` — uid, did, status, upstream_status, host_id
- `account_repo` — uid, rev, commit_data_cid (latest repo state)
- `host` — id, hostname, status, last_seq, failed_attempts
- `log_file_refs` — seq→file mapping for cursor binary search
- `domain_ban` — banned domain suffixes
- `backfill_progress` — collection backfill cursor tracking

connection pool: `DB_POOL_SIZE` connections (default 20). DB requests from the
frame workers are routed through a `DbRequestQueue` (2 worker threads) rather than
each worker hitting the pool directly.

**per-commit query path & caching.** each #commit event would otherwise run ~7–8
uid-keyed point reads/writes. several are cached app-side to cut postgres load:
- `did_cache` (LRU, 500K): DID → uid, ~92% hit.
- `host_id_cache` (LRU, 500K): uid → host_id — host_id mutates ~5 orders of
  magnitude slower than it's read and `setAccountHostId` is its sole writer, so a
  read-through/write-through cache eliminates a per-event point read.
- `account(host_id)` is indexed so the per-host `COUNT(*)` on new-account
  admission is an index scan, not an 8.7M-row seq scan.

this caching + indexing cut steady-state postgres CPU ~38%/frame (12h A/B,
2026-06-12). see `docs/history/handoffs/HANDOFF-2026-06-11-postgres-workload.md` for the
full per-statement profile.

### RocksDB (collection index)

two column families:
- `rbc`: `<collection>\0<did>` → `()` — prefix scan by collection
- `cbr`: `<did>\0<collection>` → `()` — per-repo deletion

populated live from firehose commits. backfill from source relay's
`listReposByCollection` for historical data.

## scaling limits

current deployment: ~2,780 PDS hosts, running on a 32 GB / 16 CPU node.
steady-state memory: ~1.1 GiB (ReleaseSafe, with frame pool). postgres alongside
at ~240 MiB. resource limits: 8 GiB memory, 1 GiB request, 1000m CPU.

| component | current (~2,750 PDS) | at 10x (~27,500 PDS) | status |
|---|---|---|---|
| thread stacks | ~22 GB virtual (2,750 × 8 MB), ~1.2 GiB RSS | ~220 GB virtual | **breaks** — virtual exceeds 32 GB node, but RSS scales sublinearly (~0.45 MiB/thread) |
| pg pool | 20 connections (`DB_POOL_SIZE`) + DbRequestQueue | bump size + queue workers | **improved** — host_id/did caches cut per-event reads; queue decouples workers from the pool |
| resolver queue | `ArrayList` + dedupe set | same | **ok** — dedupe prevents unbounded growth from duplicate DIDs |
| validator cache | 250K entries, ~19 MB | same (capped) | **degrades** — miss rate climbs with more unique DIDs |
| broadcaster | O(n consumers) under mutex, contention from 16 pool workers (not ~2,750 threads) | same | **improved** — contention reduced from ~2,750 threads to N workers |
| RocksDB | manageable write rate | ~1.4M writes/sec projected | **needs** compaction tuning |
| event log | buffered, 100ms flush | fine — sequential I/O | ok |
| kernel threads | ~2,800 (below 30K default) | ~28,000 (near default max) | **breaks** without `sysctl` tuning |
| RSS | ~1.1 GiB (ReleaseSafe) | ~4–6 GiB projected | ok — fits 32 GB node |

### what breaks first

1. **thread count**: linux default `kernel.threads-max` is ~30K. at 27,500
   subscriber threads + resolver + consumer + system threads, we hit the wall.
   virtual address space for stacks alone is ~55 GB.

2. **postgres pool**: 20 connections (`DB_POOL_SIZE`), fed via the DbRequestQueue.
   the did→uid and uid→host_id caches mean most events don't touch postgres for
   identity at all (~92% host_id hit); the remaining per-commit writes
   (account_repo upsert) dominate. at 10x, the upsert rate and the resolver
   queue — not the pool size — are the pressure points.

3. **validator cache miss rate**: 250K cache with 60M+ DIDs means ~99% miss
   rate for cold starts. resolver threads (4–8) can't keep up with the
   resolution queue at 10x ingest rate.

## migration path

### near-term (no architecture change)
- ~~expose pool-size env var~~ — **done**: `DB_POOL_SIZE` (default 20); raise to 50 if the upsert rate saturates the pool.
- increase `VALIDATOR_CACHE_SIZE` from 250K to 2M+ (costs ~150 MB)
- tune `RESOLVER_THREADS` to 16–32 for higher resolution throughput
- `sysctl kernel.threads-max=65536` on deploy node

### mid-term (thread pool — **done**, commit f0c7baf)
- ~~replace one-thread-per-host with a thread pool of N workers~~ — **done**: reader threads (one per PDS) submit raw frames to a shared processing pool (default 16 workers). heavy work (CBOR decode, validation, persist, broadcast) runs on pool workers.
- thread count is still O(hosts) for readers, but reader threads are lightweight — no crypto, no DB, no broadcast contention.
- remaining: IO multiplexing to reduce reader thread count from O(hosts) to O(cores)

### long-term (async I/O) — **done**: zio in production (2026-08)

> the section below is the historical assessment that led here. outcome:
> zlay adopted [zio](https://tangled.org/zzstoatzz.io/zio) via `-Dbackend=zio`
> — a drop-in `std.Io` vtable running cooperative fibers on one epoll scheduler
> thread. after a first canary failed at minute 35 (root cause: zio's ms-truncating
> timeout conversion made sub-ms sleeps return without parking, so `while (!done)
> io.sleep(100us)` spinners owned the scheduler), the fix (round non-zero sleeps
> up to ≥1ms) shipped and canary #2 certified: ~90 threads vs ~2,800, RSS band
> 1.33–1.47 GiB vs 2.27 GiB flat, at identical live load. `Io.Threaded` remains
> the default build and rollback path. full record:
> [handoffs/HANDOFF-2026-08-04-zio-backend.md](handoffs/HANDOFF-2026-08-04-zio-backend.md)
> and [handoffs/HANDOFF-2026-08-05-zio-canary.md](handoffs/HANDOFF-2026-08-05-zio-canary.md).
> note: subscriber connect is now sequential per-address (no `Io.Group`, no
> v4/v6 racing) on both backends — a deliberate behavioral change kept from
> this work. an earlier "stack aliasing under group churn" diagnosis was
> retracted as a detector artifact (see the 08-04 handoff's correction).
> 2026-10: the single-scheduler fork was replaced by lalinsky's zio (N executor
> threads, work stealing, io_uring/epoll), at parity on a fleet-scale A/B with
> 48 threads instead of 75 — see
> [handoffs/HANDOFF-2026-10-29-lalinsky-zio.md](handoffs/HANDOFF-2026-10-29-lalinsky-zio.md).
- zig 0.16's `Io` (io_uring/kqueue) would replace OS threads with fibers
  (~2,800 → ~35), scaling toward 100K+ hosts per process.
- **attempted and shelved twice** — `Io.Evented` ran in production, was reverted
  on a misdiagnosis, was re-enabled, then shelved for good at `e6cdf84`
  (2026-04-09): 8 cross-Io crash classes, a fiber-context-switch GPF, and an
  untraced ~10-15% coverage regression. stdlib `Io.Evented` still doesn't
  implement networking (verified against 0.16.0 release, `Uring.zig:774-789`).
  see [evented-attempt.md](evented-attempt.md).
- 2026-06 reassessment: the relevant path is no longer "wait for stdlib Evented"
  but **[zio](https://tangled.org/zzstoatzz.io/zio)** — an ordinary package
  implementing the `std.Io` vtable, no compiler fork and no stdlib patch. it is
  an active project with zlay named as its first intended consumer; see its
  `docs/adoption-guide.md`, `benchmarks.md`, and `fiber-gauntlet-2026-07-09.md`.
  not yet wired into zlay.
- zio differs from the shelved `Io.Evented` attempt in two ways that matter
  here: its core is a **readiness loop** (epoll/kqueue driving per-connection
  state machines) with no stack switching — so the ReleaseSafe GPF class does
  not apply — and it is a **hybrid**, wrapping an inner `Io.Threaded` and
  delegating everything it does not implement. graceful degradation rather than
  the all-or-nothing dual-Io segregation that made the Evented attempt fragile.
- **`pg.Pool` Io-agnosticism is NOT a prerequisite** — measured 2026-07-31, not
  reasoned. a Threaded `pg.Pool` driven from zio fibers was correct at every
  size tried (64/256/1024 concurrent callers, up to 20,480 ops, plus repeat
  runs): zero failures, zero wrong results, no crash. the Evented-era corruption
  class did not reproduce. zio's futex ops do wake both domains, as its rule 2
  claims.
  - but calling the pool *from fibers* serializes everything. with a starved
    pool (8 conns, 256 callers, 20ms queries): Threaded 7.6s / 337 ops-sec vs
    zio-fibers 58.5s / 44 ops-sec. max acquire-wait under zio was 0.02ms —
    fibers never contend, because each one blocks the whole loop thread for its
    query. 2,560 ops × 20ms ≈ 51s serial, against 58.5s observed.
  - so the fix is not a smarter pool; it is **not doing DB work on fibers**.
    the two-io split plus `DbRequestQueue` that zlay already has is the correct
    architecture, and should be kept rather than dissolved.
  - caveats: macOS/kqueue and Debug, not linux/epoll under ReleaseSafe; longest
    run ~60s, so slow-onset faults are not excluded.
- **remaining open questions**, in order:
  1. the ~10-15% coverage regression from the Evented era is still unexplained.
     it was never root-caused, so it cannot be assumed specific to `Io.Uring`.
  2. re-run the above on linux under ReleaseSafe, and soak for longer than a
     minute, before trusting the safety result for production.
  3. validate zio's throughput numbers against zlay's actual socket workload —
     its benchmarks are its own; `Io.Threaded` remains the reference column.
- cheaper intermediate step that needs none of the above: the reader-thread
  multiplexing on the near-term list, which cuts most of the ~2,800 threads
  without introducing a second Io type.

## deliberate divergences from indigo

documented policy choices where zlay intentionally differs from the Go relay
(bluesky-social/indigo). these are not bugs — each reflects a tradeoff
appropriate for zlay's architecture.

### per-PDS concurrency model

indigo uses goroutines (M:N scheduling on a small thread pool). zlay writes
one blocking reader per host against `std.Io`; the backend decides what that
costs. under `Io.Threaded` (default build) each reader is an OS thread mostly
blocked in `recv()`. under zio (production, `-Dbackend=zio`) the same readers
run as cooperative fibers spread over `RELAY_IO_EXECUTORS` executor threads.

observability: prometheus metrics expose thread count, RSS, per-host memory,
and zio scheduler internals (`zio_sched_*`).

### skip-on-miss validation

when the validator has no cached signing key for a DID (cache miss or pending
new-account verification), zlay broadcasts the frame while the key resolves
in the background. indigo blocks on DID resolution before forwarding.

zlay trades a brief trust window for throughput. the window is bounded:
- new accounts trigger async DID doc verification; on mismatch → rejected
- signature failures trigger key eviction + re-resolution (sync spec guidance)
- next commit from the same DID hits the refreshed cache

### consumer buffer sizing

zlay uses an 8K-entry per-consumer ring buffer (vs indigo's 16K-entry channel).
can be tuned independently based on observed `ConsumerTooSlow` disconnect rate.
the ring buffer is lock-free (atomic read/write indices), so the bottleneck is
consumer write throughput, not buffer contention.