···1-- Raw records from firehose/jetstream
2-- Core table for all AT Protocol records before denormalization
3---
4--- Append-only log using plain MergeTree - all versions preserved for audit/rollback.
5--- Query-time deduplication via ORDER BY + LIMIT or window functions.
6--- JSON column stores full record, extract fields only when needed for ORDER BY/WHERE/JOINs
78CREATE TABLE IF NOT EXISTS raw_records (
9 -- Decomposed AT URI components (at://did/collection/rkey)
10 did String,
11 collection LowCardinality(String),
12 rkey String,
13-14- -- Content identifier from the record (content-addressed hash)
15 cid String,
16-17 -- Repository revision (TID) - monotonically increasing per DID, used for ordering
18 rev String,
19-20- -- Full record as native JSON (schema-flexible, queryable with record.field.subfield)
21 record JSON,
22-23- -- Operation: 'create', 'update', 'delete', 'cache' (fetched on-demand)
24 operation LowCardinality(String),
25-26- -- Firehose sequence number (metadata only, not for ordering - can jump on relay restart)
27 seq UInt64,
28-29 -- Event timestamp from firehose
30 event_time DateTime64(3),
31-32- -- When we indexed this record
33 indexed_at DateTime64(3) DEFAULT now64(3),
34-35 -- Validation state: 'unchecked', 'valid', 'invalid_rev', 'invalid_gap', 'invalid_account'
36- -- Populated by async batch validation, not in hot path
37 validation_state LowCardinality(String) DEFAULT 'unchecked',
38-39 -- Whether this came from live firehose (true) or backfill (false)
40- -- Backfill events may not reflect current state until repo is fully synced
41 is_live Bool DEFAULT true,
42-43 -- Materialized AT URI for convenience
44 uri String MATERIALIZED concat('at://', did, '/', collection, '/', rkey),
45-46 -- Projection for fast delete lookups by (did, cid)
47- -- Delete events include CID, so we can O(1) lookup the original record
48- -- to know what to decrement (e.g., which notebook's like count)
49 PROJECTION by_did_cid (
50 SELECT * ORDER BY (did, cid)
51 )
···1-- Raw records from firehose/jetstream
2-- Core table for all AT Protocol records before denormalization
000034CREATE TABLE IF NOT EXISTS raw_records (
5 -- Decomposed AT URI components (at://did/collection/rkey)
6 did String,
7 collection LowCardinality(String),
8 rkey String,
009 cid String,
010 -- Repository revision (TID) - monotonically increasing per DID, used for ordering
11 rev String,
0012 record JSON,
13+ -- Operation: 'create', 'update', 'delete', ('cache' - fetched on-demand)
014 operation LowCardinality(String),
15+ -- Firehose sequence number
016 seq UInt64,
017 -- Event timestamp from firehose
18 event_time DateTime64(3),
19+ -- When the database indexed this record
020 indexed_at DateTime64(3) DEFAULT now64(3),
021 -- Validation state: 'unchecked', 'valid', 'invalid_rev', 'invalid_gap', 'invalid_account'
022 validation_state LowCardinality(String) DEFAULT 'unchecked',
023 -- Whether this came from live firehose (true) or backfill (false)
024 is_live Bool DEFAULT true,
025 -- Materialized AT URI for convenience
26 uri String MATERIALIZED concat('at://', did, '/', collection, '/', rkey),
027 -- Projection for fast delete lookups by (did, cid)
0028 PROJECTION by_did_cid (
29 SELECT * ORDER BY (did, cid)
30 )
···5 -- The DID this identity event is about
6 did String,
78- -- Handle (may be empty if cleared)
9 handle String,
1011 -- Sequence number from firehose
···5 -- The DID this identity event is about
6 did String,
78+ -- Handle (may be empty)
9 handle String,
1011 -- Sequence number from firehose
···1-- Account events from firehose (#account messages)
2--- Tracks account status changes: active, deactivated, deleted, suspended, takendown
34CREATE TABLE IF NOT EXISTS raw_account_events (
5 -- The DID this account event is about
···1-- Account events from firehose (#account messages)
023CREATE TABLE IF NOT EXISTS raw_account_events (
4 -- The DID this account event is about
···2-- Tracks our position in the firehose stream for resumption after restart
34CREATE TABLE IF NOT EXISTS firehose_cursor (
5- -- Consumer identifier (allows multiple consumers with different cursors)
6 consumer_id String,
78 -- Last successfully processed sequence number
···2-- Tracks our position in the firehose stream for resumption after restart
34CREATE TABLE IF NOT EXISTS firehose_cursor (
05 consumer_id String,
67 -- Last successfully processed sequence number
···1-- Per-account revision state tracking
2-- Maintains latest rev/cid per DID for dedup and gap detection
3---
4--- AggregatingMergeTree with incremental MV from raw_records
5--- Query with argMaxMerge/maxMerge to finalize aggregates
67CREATE TABLE IF NOT EXISTS account_rev_state (
8 -- Account DID
···1-- Per-account revision state tracking
2-- Maintains latest rev/cid per DID for dedup and gap detection
00034CREATE TABLE IF NOT EXISTS account_rev_state (
5 -- Account DID
···1--- Incremental MV: fires on each insert to raw_records, maintains aggregate state
2--- Must be created after both account_rev_state (target) and raw_records (source) exist
34CREATE MATERIALIZED VIEW IF NOT EXISTS account_rev_state_mv TO account_rev_state AS
5SELECT
···1+023CREATE MATERIALIZED VIEW IF NOT EXISTS account_rev_state_mv TO account_rev_state AS
4SELECT
···1-- Auto-populate freed status from account events
2--- JOINs against handle_mappings to find current handle for the DID
3--- If no mapping exists yet, the JOIN fails silently (can't free unknown handles)
45CREATE MATERIALIZED VIEW IF NOT EXISTS handle_mappings_from_account_mv TO handle_mappings AS
6SELECT
···1-- Auto-populate freed status from account events
0023CREATE MATERIALIZED VIEW IF NOT EXISTS handle_mappings_from_account_mv TO handle_mappings AS
4SELECT
···1-- Weaver profile source table
2--- Populated by MV from raw_records, merged into profiles by refreshable MV
34CREATE TABLE IF NOT EXISTS profiles_weaver (
5 did String,
6-7- -- Raw profile JSON
8 profile String,
910 -- Extracted fields for coalescing
···1-- Weaver profile source table
023CREATE TABLE IF NOT EXISTS profiles_weaver (
4 did String,
005 profile String,
67 -- Extracted fields for coalescing
···3CREATE MATERIALIZED VIEW IF NOT EXISTS profiles_weaver_mv TO profiles_weaver AS
4SELECT
5 did,
6- toString(record) as profile,
7 coalesce(record.displayName, '') as display_name,
8 coalesce(record.description, '') as description,
9 coalesce(record.avatar.ref.`$link`, '') as avatar_cid,
···3CREATE MATERIALIZED VIEW IF NOT EXISTS profiles_weaver_mv TO profiles_weaver AS
4SELECT
5 did,
6+ record as profile,
7 coalesce(record.displayName, '') as display_name,
8 coalesce(record.description, '') as description,
9 coalesce(record.avatar.ref.`$link`, '') as avatar_cid,
···1-- Bluesky profile source table
2--- Populated by MV from raw_records, merged into profiles by refreshable MV
34CREATE TABLE IF NOT EXISTS profiles_bsky (
5 did String,
67- -- Raw profile JSON
8 profile String,
910 -- Extracted fields for coalescing
···1-- Bluesky profile source table
023CREATE TABLE IF NOT EXISTS profiles_bsky (
4 did String,
506 profile String,
78 -- Extracted fields for coalescing
···3CREATE MATERIALIZED VIEW IF NOT EXISTS profiles_bsky_mv TO profiles_bsky AS
4SELECT
5 did,
6- toString(record) as profile,
7 coalesce(record.displayName, '') as display_name,
8 coalesce(record.description, '') as description,
9 coalesce(record.avatar.ref.`$link`, '') as avatar_cid,
···3CREATE MATERIALIZED VIEW IF NOT EXISTS profiles_bsky_mv TO profiles_bsky AS
4SELECT
5 did,
6+ record as profile,
7 coalesce(record.displayName, '') as display_name,
8 coalesce(record.description, '') as description,
9 coalesce(record.avatar.ref.`$link`, '') as avatar_cid,
···1-- Unified profiles view
2--- Refreshable MV that merges weaver + bsky profiles with handle resolution
3--- Queries are pure reads, no merge computation needed
4-5CREATE MATERIALIZED VIEW IF NOT EXISTS profiles
6REFRESH EVERY 1 MINUTE
7ENGINE = ReplacingMergeTree(indexed_at)
···9AS SELECT
10 if(w.did != '', w.did, b.did) as did,
1112- -- Handle from handle_mappings (empty if not resolved yet)
13 coalesce(h.handle, '') as handle,
1415 -- Raw profiles per source
···1-- Unified profiles view
0002CREATE MATERIALIZED VIEW IF NOT EXISTS profiles
3REFRESH EVERY 1 MINUTE
4ENGINE = ReplacingMergeTree(indexed_at)
···6AS SELECT
7 if(w.did != '', w.did, b.did) as did,
809 coalesce(h.handle, '') as handle,
1011 -- Raw profiles per source
···1--- Notebook engagement counts
2--- Updated by MVs from likes, bookmarks, subscriptions (added later with graph tables)
3--- Joined with notebooks at query time
45CREATE TABLE IF NOT EXISTS notebook_counts (
6 did String,
···1+-- Notebook engagement counts table stub
0023CREATE TABLE IF NOT EXISTS notebook_counts (
4 did String,
···1--- Entry engagement counts
2--- Updated by MVs from likes, bookmarks (added later with graph tables)
3--- Joined with entries at query time
45CREATE TABLE IF NOT EXISTS entry_counts (
6 did String,
···1+-- Entry engagement counts table stub
0023CREATE TABLE IF NOT EXISTS entry_counts (
4 did String,
···1-- Draft stub records
2--- Anchors for unpublished content, enables draft discovery via queries
34CREATE TABLE IF NOT EXISTS drafts (
5 -- Identity
···1-- Draft stub records
023CREATE TABLE IF NOT EXISTS drafts (
4 -- Identity
···1-- Notebook entries mapping (denormalized for reverse lookup)
2-- Maps entries to the notebooks that contain them
3--- Enables reverse lookup: find notebooks containing an entry
45CREATE TABLE IF NOT EXISTS notebook_entries (
6 -- Entry being referenced
···1-- Notebook entries mapping (denormalized for reverse lookup)
2-- Maps entries to the notebooks that contain them
034CREATE TABLE IF NOT EXISTS notebook_entries (
5 -- Entry being referenced
···1-- Populate notebook_entries from notebooks
2--- Extracts entry references from the entryList in notebook records
3--- Incremental MV: triggers on INSERT to notebooks, writes to notebook_entries
45CREATE MATERIALIZED VIEW IF NOT EXISTS notebook_entries_mv
6TO notebook_entries
7AS
8SELECT
9- -- Parse entry URI to extract did and rkey
10- -- URI format: at://did:plc:xxx/sh.weaver.notebook.entry/rkey
11- -- assumeNotNull is safe here because WHERE filters guarantee non-null
12 assumeNotNull(extract(entry_uri, 'at://([^/]+)/')) as entry_did,
13 assumeNotNull(extract(entry_uri, '/sh\\.weaver\\.notebook\\.entry/([^/]+)$')) as entry_rkey,
14
···1-- Populate notebook_entries from notebooks
0023CREATE MATERIALIZED VIEW IF NOT EXISTS notebook_entries_mv
4TO notebook_entries
5AS
6SELECT
0007 assumeNotNull(extract(entry_uri, 'at://([^/]+)/')) as entry_did,
8 assumeNotNull(extract(entry_uri, '/sh\\.weaver\\.notebook\\.entry/([^/]+)$')) as entry_rkey,
9
···133 Ok(row)
134 }
135136- /// List entries for a notebook's author (did).
137 ///
138- /// Note: This is a simplified version. The full implementation would
139- /// need to join with notebook's entryList to get proper ordering.
140- /// For now, we just list entries by the same author, ordered by rkey (notebook order).
141 pub async fn list_notebook_entries(
142 &self,
143- did: &str,
0144 limit: u32,
145- cursor: Option<&str>,
146 ) -> Result<Vec<EntryRow>, IndexError> {
147- // Note: rkey ordering is intentional here - it's the notebook's entry order
148- let query = if cursor.is_some() {
149- r#"
150- SELECT did, rkey, cid, uri, title, path, tags, author_dids, created_at, indexed_at, record
151- FROM (
152- SELECT did, rkey, cid, uri, title, path, tags, author_dids, created_at, updated_at, indexed_at, record,
153- ROW_NUMBER() OVER (PARTITION BY rkey ORDER BY updated_at DESC) as rn
154- FROM entries FINAL
155- WHERE did = ?
156- AND deleted_at = toDateTime64(0, 3)
157- AND rkey > ?
158- )
159- WHERE rn = 1
160- ORDER BY rkey ASC
161- LIMIT ?
162- "#
163- } else {
164- r#"
165- SELECT did, rkey, cid, uri, title, path, tags, author_dids, created_at, indexed_at, record
166- FROM (
167- SELECT did, rkey, cid, uri, title, path, tags, author_dids, created_at, updated_at, indexed_at, record,
168- ROW_NUMBER() OVER (PARTITION BY rkey ORDER BY updated_at DESC) as rn
169- FROM entries FINAL
170- WHERE did = ?
171- AND deleted_at = toDateTime64(0, 3)
172- )
173- WHERE rn = 1
174- ORDER BY rkey ASC
175- LIMIT ?
176- "#
177- };
178179- let mut q = self.inner().query(query).bind(did);
180-181- if let Some(c) = cursor {
182- q = q.bind(c);
183- }
184185- let rows =
186- q.bind(limit)
187- .fetch_all::<EntryRow>()
188- .await
189- .map_err(|e| ClickHouseError::Query {
190- message: "failed to list notebook entries".into(),
191- source: e,
192- })?;
00000193194 Ok(rows)
195 }
···133 Ok(row)
134 }
135136+ /// List entries for a specific notebook, ordered by position in the notebook.
137 ///
138+ /// Uses notebook_entries table to get entries that belong to this notebook.
00139 pub async fn list_notebook_entries(
140 &self,
141+ notebook_did: &str,
142+ notebook_rkey: &str,
143 limit: u32,
144+ cursor: Option<u32>,
145 ) -> Result<Vec<EntryRow>, IndexError> {
146+ let query = r#"
147+ SELECT
148+ e.did AS did,
149+ e.rkey AS rkey,
150+ e.cid AS cid,
151+ e.uri AS uri,
152+ e.title AS title,
153+ e.path AS path,
154+ e.tags AS tags,
155+ e.author_dids AS author_dids,
156+ e.created_at AS created_at,
157+ e.indexed_at AS indexed_at,
158+ e.record AS record
159+ FROM notebook_entries ne FINAL
160+ INNER JOIN entries e ON
161+ e.did = ne.entry_did
162+ AND e.rkey = ne.entry_rkey
163+ AND e.deleted_at = toDateTime64(0, 3)
164+ WHERE ne.notebook_did = ?
165+ AND ne.notebook_rkey = ?
166+ AND ne.position > ?
167+ ORDER BY ne.position ASC
168+ LIMIT ?
169+ "#;
0000000170171+ let cursor_val = cursor.unwrap_or(0);
0000172173+ let rows = self
174+ .inner()
175+ .query(query)
176+ .bind(notebook_did)
177+ .bind(notebook_rkey)
178+ .bind(cursor_val)
179+ .bind(limit)
180+ .fetch_all::<EntryRow>()
181+ .await
182+ .map_err(|e| ClickHouseError::Query {
183+ message: "failed to list notebook entries".into(),
184+ source: e,
185+ })?;
186187 Ok(rows)
188 }
···12use self::repo::XrpcErrorResponse;
1314pub mod actor;
015pub mod collab;
16pub mod edit;
017pub mod notebook;
18pub mod repo;
19
···12use self::repo::XrpcErrorResponse;
1314pub mod actor;
15+pub mod bsky;
16pub mod collab;
17pub mod edit;
18+pub mod identity;
19pub mod notebook;
20pub mod repo;
21
+27-29
crates/weaver-index/src/endpoints/notebook.rs
···45 let did_str = did.as_str();
46 let name = args.name.as_ref();
4748- // Fetch notebook and entries in parallel - both just need the DID
49 let limit = args.entry_limit.unwrap_or(50).clamp(1, 100) as u32;
50- let cursor = args.entry_cursor.as_deref();
0005152- let (notebook_result, entries_result) = tokio::try_join!(
53- async {
54- state
55- .clickhouse
56- .resolve_notebook(did_str, name)
57- .await
58- .map_err(|e| {
59- tracing::error!("Failed to resolve notebook: {}", e);
60- XrpcErrorResponse::internal_error("Database query failed")
61- })
62- },
63- async {
64- state
65- .clickhouse
66- .list_notebook_entries(did_str, limit + 1, cursor)
67- .await
68- .map_err(|e| {
69- tracing::error!("Failed to list entries: {}", e);
70- XrpcErrorResponse::internal_error("Database query failed")
71- })
72- }
73- )?;
7475- let notebook_row =
76- notebook_result.ok_or_else(|| XrpcErrorResponse::not_found("Notebook not found"))?;
77- let entry_rows = entries_result;
0000007879 // Fetch notebook contributors (evidence-based)
80 let notebook_contributors = state
···183 entries.push(book_entry);
184 }
185186- // Build cursor for pagination
187 let next_cursor = if has_more {
188- entry_rows.last().map(|e| e.rkey.to_string().into())
00189 } else {
190 None
191 };
···45 let did_str = did.as_str();
46 let name = args.name.as_ref();
47048 let limit = args.entry_limit.unwrap_or(50).clamp(1, 100) as u32;
49+ let cursor: Option<u32> = args
50+ .entry_cursor
51+ .as_deref()
52+ .and_then(|c| c.parse().ok());
5354+ // Fetch notebook first to get its rkey
55+ let notebook_row = state
56+ .clickhouse
57+ .resolve_notebook(did_str, name)
58+ .await
59+ .map_err(|e| {
60+ tracing::error!("Failed to resolve notebook: {}", e);
61+ XrpcErrorResponse::internal_error("Database query failed")
62+ })?
63+ .ok_or_else(|| XrpcErrorResponse::not_found("Notebook not found"))?;
0000000000006465+ // Now fetch entries using notebook's rkey
66+ let entry_rows = state
67+ .clickhouse
68+ .list_notebook_entries(did_str, ¬ebook_row.rkey, limit + 1, cursor)
69+ .await
70+ .map_err(|e| {
71+ tracing::error!("Failed to list entries: {}", e);
72+ XrpcErrorResponse::internal_error("Database query failed")
73+ })?;
7475 // Fetch notebook contributors (evidence-based)
76 let notebook_contributors = state
···179 entries.push(book_entry);
180 }
181182+ // Build cursor for pagination (position-based)
183 let next_cursor = if has_more {
184+ // Position = cursor offset + number of entries returned
185+ let last_position = cursor.unwrap_or(0) + entry_rows.len() as u32;
186+ Some(last_position.to_string().into())
187 } else {
188 None
189 };
···1+If you've been to this site before, you maybe noticed it loaded a fair bit more quickly this time. That's not really because the web server creating this HTML got a whole lot better. It did require some refactoring, but it was mostly in the vein of taking some code and adding new code that did the same thing gated behind a cargo feature. This did, however, have the side effect of, in the final binary, replacing functions that are literally hundreds of lines, that in turn call functions that may also be hundreds of lines, making several cascading network requests, with functions that look like this, which make by and large a single network request and return exactly what is required.
2+3+```rust
4+#[cfg(feature = "use-index")]
5+fn fetch_entry_view(
6+ &self,
7+ entry_ref: &StrongRef<'_>,
8+) -> impl Future<Output = Result<EntryView<'static>, WeaverError>>
9+where
10+ Self: Sized,
11+{
12+ async move {
13+ use weaver_api::sh_weaver::notebook::get_entry::GetEntry;
14+15+ let resp = self
16+ .send(GetEntry::new().uri(entry_ref.uri.clone()).build())
17+ .await
18+ .map_err(|e| AgentError::from(ClientError::from(e)))?;
19+20+ let output = resp.into_output().map_err(|e| {
21+ AgentError::xrpc(e.into))
22+ })?;
23+24+ Ok(output.value.into_static())
25+ }
26+}
27+```
28+29+Of course the reason is that I finally got round to building the Weaver AppView. I'm going to be calling mine the Index, because Weaver is about writing and I think "AppView" as a term kind of sucks and "index" is much more elegant, on top of being a good descriptor of what the big backend service now powering Weaver does. ![[at://did:plc:ragtjsm2j2vknwkz3zp4oxrd/app.bsky.feed.post/3lyucxfxq622w]]
30+For the uninitiated, because I expect at least some people reading this aren't big into AT Protocol development, an AppView is an instance of the kind of big backend service that Bluesky PBLLC runs which powers essentially every Bluesky client, with a few notable exceptions, such as [Red Dwarf](https://reddwarf.app/), and (partially, eventually more completely) [Blacksky](https://blacksky.community/). It listens to the [Firehose](https://bsky.network/) [event stream](https://atproto.com/specs/event-stream) from the main Bluesky Relay and analyzes the data which comes through that pertains to Bluesky, producing your timeline feeds, figuring out who follows you, who you block and who blocks you (and filtering them out of your view of the app), how many people liked your last post, and so on. Because the records in your PDS (and those of all the other people on Bluesky) need context and relationship and so on to give them meaning, and then that context can be passed along to you without your app having to go collect it all. ![[at://did:plc:uu5axsmbm2or2dngy4gwchec/app.bsky.feed.post/3lsc2tzfsys2f]]
31+It's a very normal backend with some weird constraints because of the protocol, and in it's practice the thing that separates the day-to-day Bluesky experience from the Mastodon experience the most. It's also by far the most centralising force in the network, because it also does moderation, and because it's quite expensive to run. A full index of all Bluesky activity takes a lot of storage (futur's Zeppelin experiment detailed above took about 16 terabytes of storage using PostgreSQL for the database and cost $200/month to run), and then it takes that much more computing power to calculate all the relationships between the data on the fly as new events come in and then serve personalized versions to everyone that uses it.
32+33+It's not the only AppView out there, most atproto apps have something like this. Tangled, Streamplace, Leaflet, and so on all have substantial backends. Some (like Tangled) actually combine the front end you interact with and the AppView into a single service. But in general these are big, complicated persistent services you have to backfill from existing data to bootstrap, and they really strongly shape your app, whether they're literally part of the same executable or hosted on the same server or not. And when I started building Weaver in earnest, not only did I still have a few big unanswered questions about how I wanted Weaver to work, how it needed to work, I also didn't want to fundamentally tie it to some big server, create this centralising force. I wanted it to be possible for someone else to run it without being dependent on me personally, ideally possible even if all they had access to was a static site host like GitHub Pages or a browser runtime platform like Cloudflare Workers, so long as someone somewhere was running a couple of generic services. I wanted to be able to distribute the fullstack server version as basically just an executable in a directory of files with no other dependencies, which could easily be run in any container hosting environment with zero persistent storage required. Hell, you could technically serve it as a blob or series of blobs from your PDS with the right entry point if I did my job right.
34+35+I succeeded.
36+37+Well, I don't know if you can serve `weaver-app` purely via `com.atproto.sync.getBlob` request, but it doesn't need much.
38+## Constellation
39+![[at://did:plc:ttdrpj45ibqunmfhdsb4zdwq/app.bsky.feed.post/3m6pckslkt222]] Ana's leaflet does a good job of explaining more or less how Weaver worked up until now. It used direct requests to personal data servers (mostly mine) as well as many calls to [Constellation](https://constellation.microcosm.blue/) and [Slingshot](https://slingshot.microcosm.blue/), and some even to [UFOs](https://ufos.microcosm.blue/), plus a couple of judicious calls to the Bluesky AppView for profiles and post embeds. ![[at://did:plc:hdhoaan3xa3jiuq4fg4mefid/app.bsky.feed.post/3m5jzclsvpc2c]]
40+The three things linked above are generic services that provide back-links, a record cache, and a running feed of the most recent instances of all lexicons on the network, respectively. That's more than enough to build an app with, though it's not always easy. For some things it can be pretty straightforward. Constellation can tell you what notebooks an entry is in. It can tell you which edit history records are related to this notebook entry. For single-layer relationships it's straightforward. However you then have to also fetch the records individually, because it doesn't provide you the records, just the URIs you need to find them. Slingshot doesn't currently have an endpoint that will batch fetch a list of URIs for you. And the PDS only has endpoints like [`com.atproto.repo.listRecords`](https://docs.bsky.app/docs/api/com-atproto-repo-list-records), which gives you a paginated list of all records of a specific type, but doesn't let you narrow that down easily, so you have to page through until you find what you wanted.
41+42+This wouldn't be too bad if I was fine with almost everything after the hostname in my web URLs being gobbledegook record keys, but I wanted people to be able to link within a notebook like they normally would if they were linking within an Obsidian Vault, by name or by path, something human-readable. So some queries became the good old N+1 requests, because I had to list a lot of records and fetch them until I could find the one that matched. Or worse still, particularly once I introduce collaboration and draft syncing to the editor. Loading a draft of an entry with a lot of edit history could take 100 or more requests, to check permissions, find all the edit records, figure out which ones mattered, publish the collaboration session record, check for collaborators, and so on. It was pretty slow going, particularly when one could not pre-fetch and cache and generate everything server-side on a real CPU rather than in a browser after downloading a nice chunk of WebAssembly code. My profile page [alpha.weaver.sh/nonbinary.computer](https://alpha.weaver.sh/nonbinary.computer) often took quite some time to load due to a frustrating quirk of Dioxus, the Rust web framework I've used for the front-end, which prevented server-side rendering from waiting until everything important had been fetched to render the complete page on that specific route, forcing me to load it client-side.
43+44+Some stuff is just complicated to graph out, to find and pull all the relevant data together in order, and some connections aren't the kinds of things you can graph generically. For example, in order to work without any sort of service that has access to indefinite authenticated sessions of more than one person at once, Weaver handles collaborative writing and publishing by having each collaborator write to their own repository and publish there, and then, when the published version is requested, figuring out which version of an entry or notebook is most up-to-date, and displaying that one. It matches by record key across more than one repository, determined at request time by the state of multiple other records in those users' repositories.
45+46+# Shape of Data
47+All of that being said, this was still the correct route, particularly for me. Because not only does this provide a powerful fallback mode, built-in protection against me going AWOL, it was critical in the design process of the index. My friend Ollie, when talking about database and API design, always says that, regardless of the specific technology you use, you need to structure your data based on how you need to query into it. Whatever interface you put in front of it, be it GraphQL, SQL, gRPC, XRPC, server functions, AJAX, literally any way that you can have the part of your app that people interact with pull the specific data they want from where it's stored, how well that performs, how many cycles your server or client spends collecting it, sorting it, or waiting on it, how much memory it takes, how much bandwidth it takes, depends on how that data is shaped, and you, when you are designing your app and all the services that go into it, get to choose that shape.
48+49+Bluesky developers have said that hydrating blocks, mutes, and labels and applying the appropriate ones to the feed content based on the preferences of the user takes quite a bit of compute at scale, and that even the seemingly simple [Following feed](https://jazco.dev/2025/02/19/imperfection/), which is mostly a reverse-chronological feed of posts by people you follow explicitly (plus a few simple rules), is remarkably resource-intensive to produce for them. The extremely clever [string interning](https://jazco.dev/2025/09/26/interning/) and [bitmap tricks](https://jazco.dev/2024/04/20/roaring-bitmaps/) implemented by a brilliant engineer during their time at Bluesky are all oriented toward figuring out the most efficient way to structure the data to make the desired query emerge naturally from it. 
50+51+It's intuitive that this matters a lot when you use something like RocksDB, or FoundationDB, or Redis, which are fundamentally key-value stores. What your key contains there determines almost everything about how easy it is to find and manipulate the values you want. Fig and I have had some struggles getting a backup of their Constellation service running in real-time and keeping up with Jetstream on my home server, because the only storage on said home server with enough free space for Constellation's full index is a ZFS pool that's primarily hard-drive based, and the way the Constellation RocksDB backend storage is structured makes processing delete events extremely expensive on a hard drive where seek times are nontrivial. On a Pi 4 with an SSD, it runs just fine. ![[at://did:plc:44ybard66vv44zksje25o7dz/app.bsky.feed.post/3m7e3hnyh5c2u]]
52+But it's a problem for every database. Custom feed builder service [graze.social](https://graze.social/) ran into difficulties with Postgres early on in their development, as they rapidly gained popularity. They ended up using the same database I did, Clickhouse, for many of the same reasons. ![[at://did:plc:i6y3jdklpvkjvynvsrnqfdoq/app.bsky.feed.post/3m7ecmqcwys23]]
53+And while thankfully I don't think that a platform oriented around long-form written content will ever have the kinds of following timeline graph write amplification problems Bluesky has dealt with, even if it becomes successful beyond my wildest dreams, there are definitely going to be areas where latency matters a ton and the workload is very write-heavy, like real-time collaboration, particularly if a large number of people work on a document simultaneously, even while the vast majority of requests will primarily be reading data out.
54+55+One reason why the edit records for Weaver have three link fields (and may get more!), even though it may seem a bit redundant, is precisely because those links make it easy to graph the relationships between them, to trace a tree of edits backward to the root, while also allowing direct access and a direct relationship to the root snapshot and the thing it's associated with.
56+57+In contrast, notebook entry records lack links to other parts of the notebook in and of themselves because calculating them would be challenging, and updating one entry would require not just updating the entry itself and notebook it's in, but also neighbouring entries in said notebook. With the shape of collaborative publishing in Weaver, that would result in up to 4 writes to the PDS when you publish an entry, in addition to any blob uploads. And trying to link the other way in edit history (root to edit head) is similarly challenging.
58+59+I anticipated some of these. but others emerged only because I ran into them while building the web app. I've had to manually fix up records more than once because I made breaking changes to my lexicons after discovering I really wanted X piece of metadata or cross-linkage. If I'd built the index first or alongside—particularly if the index remained a separate service from the web app as I intended it to, to keep the web app simple—it would likely have constrained my choices and potentially cut off certain solutions, due to the time it takes to dump the database and re-run backfill even at a very small scale. Building a big chunk of the front end first told me exactly what the index needed to provide easy access to.
60+# ClickHAUS
61+So what does Weaver's index look like? Well it starts with either the firehose or the new Tap sync tool. The index ingests from either over a WebSocket connection, does a bit of processing (less is required when ingesting from Tap, and that's currently what I've deployed) and then dumps them in the Clickhouse database. I chose it as the primary index database on recommendation from a friend, and after doing a lot of reading. It fits atproto data well, as Graze found. Because it isolates concurrent inserts and selects so that you can just dump data in, while it cleans things up asynchronously after, it does wonderfully when you have a single major input point or a set of them to dump into that fans out, which you can then transform and then read from.
62+63+I will not claim that the tables you can find in the weaver repository are especially **good** database design overall, but they work, and we'll see how they scale. This is one of three main input tables. One for record writes, one for identity events, and one for account events.
64+```SQL
65+CREATE TABLE IF NOT EXISTS raw_records (
66+ did String,
67+ collection LowCardinality(String),
68+ rkey String,
69+ cid String,
70+ -- Repository revision (TID)
71+ rev String,
72+ record JSON,
73+ -- Operation: 'create', 'update', 'delete', 'cache' (fetched on-demand)
74+ operation LowCardinality(String),
75+ -- Firehose sequence number
76+ seq UInt64,
77+ -- Event timestamp from firehose
78+ event_time DateTime64(3),
79+ -- When the database indexed this record
80+ indexed_at DateTime64(3) DEFAULT now64(3),
81+ -- Validation state: 'unchecked', 'valid', 'invalid_rev', 'invalid_gap', 'invalid_account'
82+ validation_state LowCardinality(String) DEFAULT 'unchecked',
83+ -- Whether this came from live firehose (true) or backfill (false)
84+ is_live Bool DEFAULT true,
85+ -- Materialized AT URI for convenience
86+ uri String MATERIALIZED concat('at://', did, '/', collection, '/', rkey),
87+ -- Projection for fast delete lookups by (did, cid)
88+ PROJECTION by_did_cid (
89+ SELECT * ORDER BY (did, cid)
90+ )
91+)
92+ENGINE = MergeTree()
93+ORDER BY (collection, did, rkey, event_time, indexed_at);
94+```
95+From here we fan out into a cascading series of materialized views and other specialised tables. These break out the different record types, calculate metadata, and pull critical fields out of the record JSON for easier querying. Clickhouse's wild-ass compression means we're not too badly off replicating data on disk this way. Seriously, their JSON type ends up being the same size as a CBOR BLOB on disk in my testing, though it *does* have some quirks, as I discovered when I read back Datetime fields and got...not the format I put in. Thankfully there's a config setting for that. We also build out the list of who contributed to a published entry and determine the canonical record for it, so that fetching a fully hydrated entry with all contributor profiles only takes a couple of `SELECT` queries that themselves avoid performing extensive table scans due to reasonable choices of `ORDER BY` fields in the denormalized tables they query. And then I can do quirky things like power a profile fetch endpoint that will provide either a Weaver or a Bluesky profile, while also unifying fields so that we can easily get at the critical stuff in common. This is a relatively expensive calculation, but people thankfully don't edit their profiles that often, and this is why we don't keep the stats in the same table.
96+97+However, this is ***also*** why Clickhouse will not be the only database used in the index.
98+99+# Why is it always SQLite?
100+When it comes to things like real-time collaboration sessions with almost keystroke-level cursor tracking and rapid per-user writeback/readback, where latency matters and we can't wait around for the merge cycle to produce the right state, *don't* work well in Clickhouse. But they sure do in SQLite!
101+102+If there's one thing the AT Protocol developer community loves more than base32-encoded timestamps it's SQLite. In fairness, we're in good company, the whole world loves SQLite. It's a good fucking embedded database and very hard to beat for write or read performance so long as you're not trying to hit it massively concurrently. Of course, that concurrency limitation does end up mattering as you scale. And here we take a cue from the Typescript PDS implementation and discover the magic of buying, well, a lot more than two of them, and of using the filesystem like a hierarchical key-value store.
103+104+<iframe width="560" height="315" src="https://www.youtube.com/embed/CZs-YcmxyUw?si=bd3GmSxMVQGdqHAR" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
105+106+This part of the data backend is still *very* much a work-in-progress and isn't used yet in the deployed version, but I did want to discuss the architecture. Unlike the PDS, we don't divide primarily by DID, instead we shard by resource, designated by collection and record key.
107+108+```rust
109+pub struct ShardKey {
110+ pub collection: SmolStr,
111+ pub rkey: SmolStr,
112+}
113+114+impl ShardKey {
115+...
116+ /// Directory path: {base}/{hash(collection,rkey)[0..2]}/{rkey}/
117+ fn dir_path(&self, base: &Path) -> PathBuf {
118+ base.join(self.hash_prefix()).join(self.rkey.as_str())
119+ }
120+...
121+}
122+/// A single SQLite shard for a resource
123+pub struct SqliteShard {
124+ conn: Mutex<Connection>,
125+ path: PathBuf,
126+ last_accessed: Mutex<Instant>,
127+}
128+/// Routes resources to their SQLite shards
129+pub struct ShardRouter {
130+ base_path: PathBuf,
131+ shards: DashMap<ShardKey, std::sync::Arc<SqliteShard>>,
132+}
133+```
134+135+The hash of the shard key plus the record key gives us the directory where we put the database file for this resource. Ultimately this may be moved out of the main index off onto something more comparable to the Tangled knot server or Streamplace nodes, depending on what constraints we run into if things go exceptionally well, but for now it lives as part of the index. In there we can tee off raw events from the incoming firehose and then transform them into the correct forms in memory, optionally persisted to disk, alongside Clickhouse and probably, for the specific things we want it for with a local scope, faster.
136+137+And direct communication, either by using something like oatproxy to swap the auth relationships around a bit (currently the index is accessed via service proxying through the PDS when authenticated) or via an iroh channel from the client, gets stuff there without having to wait for the relay to pick it up and fan it out to us, which then means that users can read their own writes very effectively. The handler hits the relevant SQLite shard if present and Clickhouse in parallel, merging the data to provide the most up-to-date form. For real-time collaboration this is critical. The current `iroh-gossip` implementation works well and requires only a generic iroh relay, but it runs into the problem every gossip protocol runs into the more concurrent users you have.
138+139+The exact method of authentication of that side-channel is by far the largest remaining unanswered question about Weaver right now, aside from "Will anyone (else) use it?"
140+141+If people have ideas, I'm all ears.
142+143+I hope you found this interesting. I enjoyed writing it out.