The Problem#
Design a Twitter-like social network where no single company owns the users, their data or the algorithm, but the product still feels like one fast, global app:
- Users post short texts with images, reply, repost, like and follow, and see a home timeline and threads, just like any microblogging app.
- A user's identity (their handle and account) and data (posts, follows, likes) are portable: they can move to another hosting provider without losing followers or history, even if the old provider disappears or turns hostile.
- Anyone can build a feed algorithm ("Science", "Cats", "Quiet posters") that users subscribe to, and anyone can run a moderation service whose labels users choose to apply.
- The network must work at the scale of tens of millions of users, with a global view of every public post, so search, counts ("1.2K likes") and threads are complete.
- Many independent operators run parts of the system, and some of them may be buggy or malicious. The data must be verifiable: a post claiming to be from a user must be provably signed by them.
This is the design behind Bluesky and its Authenticated Transfer Protocol (AT Protocol, or atproto). Bluesky launched in private beta in February 2023, opened to the public in February 2024, and passed 10 million registered users by October 2024, with growth continuing after that. It has open-sourced its servers and published the architecture (Kleppmann et al., "Bluesky and the AT Protocol: Usable Decentralized Social Media", 2024).
What makes the problem interesting:
- Decentralisation versus a good product. Users want global search, complete reply threads, accurate like counts and fast timelines. These are easy when one company holds all the data and hard when the data is spread across thousands of servers.
- Identity without a central authority. If your username belongs to a server ("alice@server.social"), you lose it when the server dies. The design needs identifiers that outlive any server, plus human-friendly names.
- Trusting data from strangers. An indexer receives posts from servers it does not control. Each record must carry proof of authorship and integrity.
- Algorithm and moderation choice. The design must let third parties rank and label content without access to private infrastructure, and must still protect users from abuse.
- Big-world indexing. Some component must see the whole network to build views, which pushes towards large aggregators. The design must keep those aggregators replaceable.
Analogy. Think of email combined with a public library. Each person keeps their own letters in a mailbox they can move between post offices (the personal data server), and every letter is sealed with their personal signet (signatures). A wire service collects copies of every public letter from all post offices and broadcasts them (the relay and its firehose). Newspapers subscribe to the wire and publish curated digests: front pages, threads and counts (app views and feed generators). Independent review boards attach warning stickers to letters (labelers), and each reader chooses which boards they trust. Anyone can open a new post office, newspaper or review board, and readers can switch without losing their address.
Background: a few terms used in this design#
- Federation: many independently run servers that cooperate through a shared protocol, as email servers do. Mastodon is federated.
- Decentralised: no single operator controls the network. Federation is one way to decentralise; peer-to-peer is another.
- AT Protocol (atproto): the open protocol behind Bluesky, covering identity, data repositories, schemas and synchronisation.
- Personal Data Server (PDS): the server that hosts a user's account and data repository, and speaks for them on the network.
- Repository (repo): a user's complete public dataset (posts, likes, follows, profile) stored as a signed, content-addressed tree.
- Record: one item in a repo, such as a single post or like, encoded in a compact binary format (DAG-CBOR).
- CID (content identifier): a hash-based identifier of a piece of data; if the data changes, the CID changes.
- Merkle tree: a tree where each node includes the hashes of its children, so one root hash commits to all the data below it.
- DID (decentralised identifier): a W3C-standard permanent identifier for an account, such as
did:plc:abc123..., which resolves to a DID document holding the user's keys and server address. - Handle: a human-readable name, which is a DNS domain such as
alice.bsky.socialoralice.com, mapped to a DID. - Relay: a service that subscribes to many PDSes and merges their update streams into one network-wide stream.
- Firehose: the real-time stream of every repository change on the network.
- App View: a service that consumes the firehose and builds the indexes an app needs: timelines, threads, counts, search.
- Lexicon: atproto's schema language, defining record types and API methods with namespaced IDs such as
app.bsky.feed.post. - XRPC: atproto's convention for HTTP APIs:
GET /xrpc/<method-id>for queries andPOSTfor procedures. - Feed generator: a third-party service that returns a ranked list of post references for a custom feed.
- Labeler: a moderation service that publishes signed labels ("spam", "nudity", "misleading") about accounts or posts.
- ActivityPub: the W3C standard (2018) for federated social networking, used by Mastodon.
For the centralised baseline this design departs from, the news feed case study (Design a News Feed (Facebook / Twitter)) covers fan-out and timelines. For the event-stream ideas, see Pub/Sub and Event Streaming.
Clarifying Questions#
| Question | Assumption for this design |
|---|---|
| How decentralised must it be? | Every role (hosting, indexing, feeds, moderation) can be run by anyone; no role requires permission from a central company. |
| Must users be able to leave their host? | Yes, including when the old host is offline or uncooperative ("credible exit"). |
| Which data is public? | Posts, likes, reposts, follows, blocks and profiles are public and signed. Direct messages are out of scope (or handled by a separate, centralised service at first). |
| How many users? | 40 million registered accounts, 5 million daily actives, growing to 100 million. |
| How many writes? | About 50 million repo events per day (posts, likes, follows, reposts, deletes), peaks of 5,000 per second. |
| Do we need global search and complete counts? | Yes. Users expect complete threads and like counts, which requires full-network indexing. |
| Who builds timelines? | An App View run by the main operator, but others may run their own. |
| Custom feeds? | Yes, third-party feed generators that any user can subscribe to. |
| Moderation? | Layered: hosting providers remove illegal content, App Views enforce their policies, and users subscribe to independent labelers. |
| Media? | Images and short videos stored as blobs on the user's PDS, served through a CDN. |
| Interoperability with Mastodon? | Not required, but bridges should be possible. |
| Latency targets? | A post appears in followers' timelines within a few seconds; timeline reads p99 under 300 ms. |
Requirements#
Functional requirements
- Users create accounts with a portable identity (a DID) and a handle (a domain name), and can change both handle and hosting provider.
- Users write records (posts, replies, likes, reposts, follows, blocks, profile updates) to their own signed repository on a PDS.
- The network synchronises every public change in near real time through relays and a firehose that anyone can consume.
- App Views build and serve timelines, threads, profiles, notifications, counts and search from the firehose.
- Users choose custom feeds built by third-party feed generators.
- Users choose labelers (moderation services) and control how labels affect what they see; hosts and App Views enforce baseline policies.
- Users can migrate their account to another PDS, keeping DID, followers and history.
Non-functional requirements
- Verifiability: every record can be checked against the author's signing key without trusting the server that delivered it.
- Availability and durability: the network survives the loss of any single PDS, relay or App View; a user's data survives their host's death if they (or anyone) hold a copy of the repo.
- Latency: post-to-timeline under about 5 seconds end to end; timeline and thread reads p99 under 300 ms from the App View.
- Scale: firehose throughput of thousands of events per second with headroom for 10 times growth; App View indexes of billions of records.
- Openness: all interfaces are documented and permissionless: running a PDS, relay, App View, feed generator or labeler needs no approval.
- Safety: illegal content can be removed quickly at several layers; abuse such as spam and harassment can be filtered by users and operators.
- Cost: a small PDS (one person or a few thousand users) runs on a cheap virtual machine; only the network-wide roles (relay, App View) need serious infrastructure.
Capacity Estimation#
We size the network-wide roles, because they are the expensive ones. The method follows Back-of-the-Envelope Estimation. The numbers below are assumptions for the design, not published Bluesky figures.
Accounts and activity.
- 40 million accounts, 5 million daily active users (DAU).
- Per DAU per day: 0.6 posts or replies, 6 likes, 0.8 reposts, 1 follow or unfollow, plus profile and list edits. That is about 9 records per DAU, or 45 million records a day; add deletes and other writes for about 50 million repo events per day.
- Average rate: 50 million / 86,400 ≈ 580 events per second. Peak (news events, evenings in the Americas): about 8 times average, 5,000 events per second.
Firehose size. Each event carries the commit (signed root, about 300 bytes), the changed record (a post is about 300–600 bytes in DAG-CBOR; a like about 150 bytes) and the changed Merkle tree nodes (a few blocks of 100–400 bytes each, because changing one leaf rewrites the path to the root). A typical event is 1–2 KB on the wire.
- Average: 580 × 1.5 KB ≈ 0.9 MB/s, or about 75 GB per day.
- Peak: 5,000 × 1.5 KB ≈ 7.5 MB/s, or about 60 Mbit/s per subscriber.
- With 500 consumers (App Views, feed generators, labelers, researchers), a relay serves 30 Gbit/s at peak. This is why relays fan out through multiple edge nodes, and why lighter streams (JSON-only, filtered by collection) exist for consumers that do not need proofs.
Repository storage (all PDSes combined).
- Records: 40 million accounts × an average of 2,000 records × 400 bytes ≈ 32 TB of record data. The Merkle tree adds about 30–50%, so about 45 TB of repo data across all PDSes.
- Blobs (images, video): 0.15 images per post × 3 million posts per day × 500 KB ≈ 225 GB per day, about 80 TB per year before video. Blobs dominate PDS storage.
- The distribution is skewed: a large provider hosting most users holds most of this, split across many PDS instances (each holding, say, 100,000–500,000 accounts with SQLite per account); a self-hoster with one account needs a few GB.
Relay.
- A relay that keeps the event log for a backfill window of 72 hours holds about 75 GB × 3 ≈ 225 GB; one that mirrors every repo holds the full 45 TB.
- It holds a connection to every PDS: thousands of small PDSes plus the large provider's instances. Each connection is a WebSocket, so tens of thousands of idle sockets, trivial for one well-sized server.
- Signature verification: 5,000 events per second × about 50 µs per ECDSA verification (P-256 or secp256k1) = 0.25 CPU-seconds per second, easily one machine.
App View.
- Indexes every record into query-friendly tables: posts by author and time, replies by thread root, likes by subject, follows both directions, and counts.
- 32 TB of records becomes about 50–100 TB of indexed data with secondary indexes and replication, in a wide-column store or sharded SQL.
- Reads: 5 million DAU × 40 timeline, thread and profile requests a day ≈ 200 million requests per day ≈ 2,300 per second, peaking at about 20,000 per second, each fanning out to tens of keyed reads (hydration). That is about 500,000 storage reads per second at peak, served mostly from caches.
Feed generators. The top custom feeds serve hundreds of thousands of users. A feed generator consuming the firehose and keeping a few days of candidate posts needs a few GB of storage and handles hundreds to thousands of skeleton requests per second, because the App View hydrates the posts. That keeps third-party feeds cheap to run.
Identity. A DID directory (the PLC directory) with 40 million DIDs × an average of 3 operations × 1 KB ≈ 120 GB of signed operations. Resolutions are cached heavily by every service; uncached resolutions are perhaps a few thousand per second.
Takeaway. The PDS role is cheap and widely distributed. The relay is bandwidth-heavy but CPU-light. The App View is the largest piece: an ordinary large-scale social-network backend whose input is a public stream.
Core Entities#
- Account (DID): permanent identifier, DID document (signing key, rotation keys, PDS endpoint, handle), status (active, deactivated, taken down).
- Handle: domain name to DID mapping, verified both ways.
- Repository: per-DID signed Merkle Search Tree of records; head commit (root CID, revision, signature).
- Record: collection (NSID such as
app.bsky.feed.post), record key, CID, value (typed by a Lexicon schema). Addressed by an AT URI such asat://did:plc:abc/app.bsky.feed.post/3kq2.... - Blob: binary media referenced from a record by CID, stored on the PDS.
- Commit event: firehose message with repo DID, sequence number, revision, operations (create, update, delete with paths and CIDs) and the changed tree blocks.
- Post view (App View): a hydrated post with author profile, counts, viewer state (liked, reposted), labels and embeds.
- Feed generator: a record declaring a custom feed (display name, description, service DID), plus the external service that answers skeleton requests.
- Label: a signed statement by a labeler: source DID, subject (account DID or record URI and CID), value ("spam", "porn", "!hide"), timestamp, optional expiry, optional negation.
- Labeler service: declares its label values and their definitions in a service record; publishes labels through a query and subscription API.
API Design#
atproto APIs follow XRPC: HTTP endpoints named by Lexicon method IDs, with JSON bodies, authenticated by tokens. There are two families: com.atproto.* (protocol-level: repos, sync, identity) and app.bsky.* (the microblogging application). The API ideas come from API Design Best Practices and the styles in API Styles: REST, gRPC, GraphQL and More.
Writing records (client to its own PDS):
POST /xrpc/com.atproto.repo.createRecord
body: repo=did:plc:alice, collection=app.bsky.feed.post,
record: text, createdAt, langs, reply refs, embed refs
returns: uri at://did:plc:alice/app.bsky.feed.post/3kq2abc, cid
POST /xrpc/com.atproto.repo.deleteRecord repo, collection, rkey
POST /xrpc/com.atproto.repo.applyWrites batch of creates, updates, deletes in one commit
POST /xrpc/com.atproto.repo.uploadBlob binary body, returns blob ref with CID and MIME typeReading views (client through its PDS, proxied to an App View):
GET /xrpc/app.bsky.feed.getTimeline cursor, limit
GET /xrpc/app.bsky.feed.getPostThread uri, depth, parentHeight
GET /xrpc/app.bsky.feed.getFeed feed=at://did:plc:gen/app.bsky.feed.generator/science, cursor
GET /xrpc/app.bsky.actor.getProfile actor=handle or DID
GET /xrpc/app.bsky.notification.listNotificationsSynchronisation (PDS to relay to consumers):
GET /xrpc/com.atproto.sync.subscribeRepos WebSocket, cursor = last sequence seen
GET /xrpc/com.atproto.sync.getRepo did, returns the whole repo as a CAR file
GET /xrpc/com.atproto.sync.getRecord did, collection, rkey, returns record plus proof blocks
GET /xrpc/com.atproto.sync.getBlob did, cidFeed generator (App View to feed service):
GET /xrpc/app.bsky.feed.getFeedSkeleton feed, cursor, limit; viewer identified by a signed token
returns: feed = list of post URIs, cursorLabeler (consumers to labeler):
GET /xrpc/com.atproto.label.subscribeLabels WebSocket stream of signed labels
GET /xrpc/com.atproto.label.queryLabels uriPatterns, sourcesDesign notes.
- Writes go only to the user's own PDS. No other server can write into a user's repo, which is what makes the data verifiable and portable.
- Reads are views, not records.
getTimelinereturns hydrated post views from an App View, not raw records; the client never assembles a timeline from thousands of repos. - Cursors are opaque. Timeline cursors encode a sort key (time plus tie-breaker); firehose cursors are sequence numbers, so consumers resume exactly where they left off after a disconnect.
- Service proxying. The client talks to its PDS, which forwards
app.bsky.*reads to the App View with a service-auth token signed by the user's PDS. The user can point their client at a different App View. - Idempotency.
applyWritescan carry aswapCommit(expected current revision), giving compare-and-swap semantics so a retried batch does not apply twice. See Idempotency and Safe Retries.
High-Level Design#
We build the design one requirement at a time. The key idea, borrowed from how the web itself scales, is to separate speech from reach: hosting a user's data (speech) is cheap and decentralised, while aggregating, ranking and moderating it (reach) is done by replaceable services that anyone can run.
1) Each user owns a signed repository on a PDS#
The client writes every action (post, like, follow) as a record in the user's repository on their PDS. The PDS signs each new commit with the account's signing key and stores the records and blobs. The PDS is the user's home on the network: it holds their account, authenticates their client and speaks for them.
2) Identity that outlives any server#
The account's permanent identifier is a DID. The DID resolves (through the PLC directory or did:web) to a DID document listing the signing key, the current PDS URL and the handle. The handle is a domain name; the domain points back to the DID with a DNS TXT record or a well-known HTTPS file. Changing hosts means updating the DID document; followers follow the DID, not the host.
3) Network-wide synchronisation through relays#
Each PDS publishes an ordered stream of its repo commits. A relay subscribes to every PDS it knows about, verifies signatures, and merges all streams into one firehose. Consumers connect to the relay instead of to thousands of PDSes. Anyone can run a relay, and a PDS can be crawled by several.
4) App Views build the product#
An App View consumes the firehose and indexes records into tables designed for the app: posts by author, threads by root, follows both ways, likes by subject, counts. It serves timelines, threads, profiles and notifications as hydrated views. Clients reach the App View through their PDS. Because the input is public, a competitor can build a different App View from the same data.
5) Custom feeds from independent services#
A feed generator is a service that consumes the firehose (or any other data), selects and ranks posts, and answers getFeedSkeleton with a list of post URIs. The App View calls it on behalf of the user and hydrates the URIs into full post views, applying blocks and moderation. The generator never needs to serve post content, so it stays small.
6) Stackable moderation with labelers#
Moderation is split into layers. PDS hosts and relays remove illegal content and take down abusive accounts. The App View enforces its own policy. Labelers publish signed labels about accounts and posts. The user chooses which labelers to subscribe to and how each label is handled (hide, warn, show). The App View fetches and attaches labels from the user's chosen labelers when it builds views.
7) Account migration#
To move hosts, the user creates an account on the new PDS with the same DID, imports the repo (a CAR file) and blobs, and updates the DID document to point to the new PDS and signing key. Relays and App Views see the identity change and fetch from the new host. Followers keep following the same DID, so nothing breaks. If the old PDS is gone, the user's rotation key still lets them update their DID document, and a repo backup restores their data.
The full high-level design#
Components:
- Client apps: official and third-party apps. They authenticate with the user's PDS and send all requests there.
- PDS fleet (large host): many PDS instances, each hosting hundreds of thousands of accounts with a per-account database, plus an entryway that routes logins to the right instance.
- Community and self-hosted PDSes: the same software run by others. They join the network by asking a relay to crawl them.
- Blob storage plus CDN: images and video referenced from records. The App View serves them through a CDN, fetched from the user's PDS by CID.
- PLC directory: a public, auditable log of signed DID operations for
did:plcidentities.did:webidentities resolve through the user's own web server. - Relays: subscribe to PDS event streams, verify commits, assign global sequence numbers, and serve the firehose.
- Lightweight stream: a simplified JSON stream (Bluesky runs one called Jetstream) for consumers that do not need Merkle proofs.
- App View: the biggest service: an indexer plus a query API, view caches and media proxy.
- Feed generators: third-party ranking services that return post URIs.
- Labelers: moderation services that publish signed labels; Bluesky publishes its moderation tool, Ozone, as open source so others can run labelers.
- Search and notifications: services built on the same firehose (full-text search index, push notifications).
Key Flows#
Flow 1: Alice posts and Bob sees it in his timeline#
Alice's client writes a record to her PDS. The PDS commits it to her repo, signs the new root and emits a commit event. The relay verifies and sequences it into the firehose. The App View indexes the post, fans it out to followers' timelines (or marks it for fan-out on read) and Bob's next timeline request includes it.
End-to-end latency is typically one to a few seconds: tens of milliseconds at the PDS, tens to hundreds of milliseconds through the relay, and indexing time at the App View, which depends on load.
Flow 2: Bob opens a custom feed#
Bob subscribes to a "Science" feed run by an independent developer. The App View asks the feed generator for a skeleton, then hydrates and filters it.
Flow 3: Alice moves to a new PDS#
Alice's current host is shutting down. She creates an account on a new PDS with her existing DID, copies her data, and updates her DID document.
If the old PDS is unreachable, Alice signs the PLC operation with her own rotation key (held on her device or with a recovery service) instead of asking the old PDS, and restores the repo from a backup or from a relay or App View copy, because the repo is signed and its integrity can be checked by anyone.
Data Model#
There are two very different data models: the protocol data in each user's repo (the source of truth, owned by the user) and the view data in an App View (derived, owned by the operator, rebuildable from the firehose).
Protocol data on the PDS. Each account has one repository: a key-value map from collection/record-key to record, stored as a Merkle Search Tree. The head commit names the root and is signed. A PDS stores, per account, the blocks (content-addressed by CID), the record index and the blob references.
View data in the App View. Records become rows in tables shaped by queries: posts by author, threads by root, likes and reposts by subject, follows in both directions, and aggregated counts.
App View tables (illustrative SQL; a wide-column store uses the same keys as partition and clustering keys):
CREATE TABLE post (
uri TEXT PRIMARY KEY, -- at://did/app.bsky.feed.post/rkey
cid TEXT NOT NULL,
author_did TEXT NOT NULL,
reply_root_uri TEXT,
reply_parent_uri TEXT,
text TEXT,
langs TEXT[],
created_at TIMESTAMPTZ NOT NULL, -- claimed by the author
indexed_at TIMESTAMPTZ NOT NULL, -- when the App View saw it
sort_at TIMESTAMPTZ NOT NULL -- least of the two, defends against backdating
);
CREATE INDEX post_by_author ON post (author_did, sort_at DESC);
CREATE INDEX post_by_root ON post (reply_root_uri, sort_at);
CREATE TABLE follow (
uri TEXT PRIMARY KEY,
creator_did TEXT NOT NULL,
subject_did TEXT NOT NULL,
UNIQUE (creator_did, subject_did)
);
CREATE INDEX follow_by_subject ON follow (subject_did, creator_did);
CREATE TABLE like_idx (
subject_uri TEXT NOT NULL,
creator_did TEXT NOT NULL,
uri TEXT NOT NULL,
PRIMARY KEY (subject_uri, creator_did) -- one like per user per post
);
CREATE TABLE timeline_entry (
owner_did TEXT NOT NULL, -- whose home timeline
sort_at TIMESTAMPTZ NOT NULL,
post_uri TEXT NOT NULL,
repost_uri TEXT,
PRIMARY KEY (owner_did, sort_at, post_uri)
);Records reference each other by strong references (URI plus CID): a reply stores the URI and CID of its parent and root, and a like stores the URI and CID of the post. The CID pins the exact version liked or replied to, so an edited post cannot silently change what earlier replies responded to.
| Data | Store | Why |
|---|---|---|
| Repo blocks and record index (per account) | SQLite file per account on the PDS | Small, isolated, easy to move or delete with the account; no cross-account joins needed |
| Blobs | Object storage behind the PDS; CDN in front of the App View | Large, immutable, content-addressed by CID |
| PLC operations | Append-only log with an audit API | Every DID change is a signed, hash-chained operation anyone can verify |
| Relay event log | Append-only log keyed by sequence number (disk or a log store such as Kafka) | Replay from a cursor for consumers that disconnect |
| App View posts, follows, likes | Sharded wide-column store (Cassandra or ScyllaDB) or sharded PostgreSQL | Billions of rows, keyed lookups, high write rate from the firehose |
| Timelines | Wide-column store or Redis lists per user | Append-heavy, read newest first |
| Counts | Counter rows with batched increments, cached in Redis | Hot posts get thousands of likes per minute |
| Search | Elasticsearch or OpenSearch | Full-text and language-aware queries |
| Labels | Indexed by subject URI and source DID in a key-value store plus an in-memory cache | Every view needs labels for many subjects |
The store choices follow Choosing a Database: A Decision Guide.
Deep Dives#
1. Federation vs centralisation: the design space#
There are four broad ways to build a social network, and atproto is a deliberate mix of them.
Centralised (Twitter, Instagram). One company stores everything and runs every service. Strengths: global search, complete threads, accurate counts, fast iteration, one moderation policy, strong spam defences from seeing everything. Weaknesses: users cannot leave without losing their audience; the company's ranking and moderation decisions apply to everyone; the service can disappear, change rules or lock out developers overnight.
Federated, server-to-server (email, Mastodon and ActivityPub). Many servers (instances) each host a community. When Alice on server A posts, server A pushes the post to every server that has one of her followers. Each server sees only what is delivered to it. Strengths: no single owner, local communities with their own norms, small operators can join. Weaknesses: identity belongs to the server (alice@a.social), so a server shutdown ends the account; each server has a partial view, so threads, counts and search are incomplete; and popular posts cause delivery fan-out to thousands of servers.
Peer-to-peer or key-based (Secure Scuttlebutt, Nostr). Users hold keys, sign their posts, and publish to peers or to dumb relays. Strengths: identity is a key pair no server can take away. Weaknesses: losing the key loses the identity, discovery and global views are hard, and every client does a lot of work.
Aggregation over open data (atproto). atproto borrows from all three:
- From peer-to-peer: data is self-certifying: signed by the user and content-addressed, so it can be served by anyone and verified by everyone.
- From federation: users are hosted by servers (PDSes) they choose, which handle the hard parts of key management and availability.
- From centralised design: big indexers (relays and App Views) see the whole network and build global views, giving a product that feels like Twitter.
The trick is that the big indexers hold only derived, public data. If an App View misbehaves, another can be built from the same firehose; if a relay censors, another relay can crawl the same PDSes. The "lock-in" moves from the data to the operational cost of running a full index, which the design tries to keep moderate.
The web analogy. The architecture mirrors the web: websites (PDSes) publish content, crawlers (relays) collect it, search engines and aggregators (App Views and feed generators) build services on top. Nobody needs permission to publish, and anyone with enough resources can build a competing aggregator.
| Property | Centralised | ActivityPub federation | atproto |
|---|---|---|---|
| Who owns identity | Company | Instance (domain in the username) | User (DID plus own domain handle) |
| Data portability | Export only | Followers move, posts do not | Full repo moves, signed |
| Global view (search, counts) | Yes | Partial per server | Yes, via relays and App Views |
| Who ranks feeds | Company | Usually chronological per server | Any feed generator the user picks |
| Who moderates | Company | Each instance admin plus defederation | Layered: hosts, App Views, chosen labelers |
| Cost of joining as an operator | Not allowed | Run a server | Run a PDS (small) or an App View (large) |
| Delivery model | Internal | Push from author's server to followers' servers | Pull through a relay into indexers |
When centralisation still wins. If the product needs private data by default (messaging, health), strong cross-user consistency (marketplaces), or extremely fast product iteration, a centralised system is simpler. Decentralisation pays off when the network's value is its public conversation, and when trust in any single operator is the limiting factor.
2. Signed data repositories#
Each user's data is a repository: a key-value map from paths to records, organised as a Merkle tree and committed with a signature. This turns user data into something like a Git repository: content-addressed, verifiable and replicable.
Records and paths. A path is collection/record-key, for example app.bsky.feed.post/3kq2fzmw7bk2s. The collection is a Lexicon NSID (namespaced identifier) that names the schema. The record key for posts is a TID (timestamp identifier): a 13-character base32 string encoding a 64-bit value made of a microsecond timestamp and a small random clock identifier, so keys sort by creation time. Some records use fixed keys, such as app.bsky.actor.profile/self.
Content addressing. Each record is encoded as DAG-CBOR (a deterministic binary JSON-like format) and hashed with SHA-256 to give a CID. Identical bytes give an identical CID; any change gives a different one. References between records use the CID to pin a specific version.
The Merkle Search Tree (MST). The repo's keys are arranged in a Merkle Search Tree, a structure introduced by Auvolat and Taïani ("Merkle Search Trees: Efficient State-Based CRDTs in Open Networks", 2019). Each key's layer in the tree is decided by its hash: count the leading zero bits of SHA-256(key) and divide by two (rounding down), so about one key in 4 reaches layer 1, one in 16 layer 2, and so on, giving an average fan-out of 4. Within a node, keys are sorted, with pointers to subtrees between them. The key property: the tree shape depends only on the set of keys, not on insertion order. Two servers holding the same records build byte-identical trees with the same root CID.
Why this matters:
- Cheap proofs. To prove that
app.bsky.feed.post/3kq2...has a certain CID in a repo with a given signed root, a server sends the path of nodes from the root to the leaf: about log base 4 of the record count. A repo with 10,000 records has a depth of about 7, so a proof is about 7 small blocks. - Cheap diffs. Two versions of a repo share all subtrees that did not change. A commit that adds one record changes only the nodes on one root-to-leaf path. Sync sends only those new blocks.
- Deterministic structure. Because shape is history-independent, two copies can be compared by root CID, and differences found by walking down mismatched subtrees, like comparing two Git trees.
Commits. A commit object contains the DID, a revision (a TID that increases with each commit), the root CID of the MST, a pointer to the previous commit (in earlier versions) and a signature over these fields made with the account's signing key (P-256 or secp256k1 ECDSA). The signing key is listed in the DID document, so anyone can check that a commit was authorised by the account's current key.
Repository export. A whole repo is serialised as a CAR file (Content Addressable aRchive): a header naming the root CID followed by every block. Exporting, backing up and migrating a repo means copying a CAR file. A typical active user's repo is a few MB to tens of MB without blobs.
What a writer does. The PDS applies the write to the MST (insert, update or delete a key), recomputes CIDs for nodes on the changed path, creates a new commit with a new revision, signs it and stores the new blocks. The old blocks that are no longer referenced can be garbage-collected, since history is not kept by default: the repo is a current state, not a full log. Deletes are real deletes: the record disappears from the tree, and downstream indexers are told to remove it.
Trade-offs.
- Signing every commit costs CPU (about 50–100 µs per signature), trivial per user but noticeable for a PDS committing thousands of writes per second; batching writes with
applyWritesreduces signatures. - Content addressing makes edits subtle: an edited post has a new CID, so likes and replies that reference the old CID point to an older version. The App View must decide whether to show "edited" or treat likes as applying to the record regardless of version.
- The repo is public. Anything private (DMs, drafts, mutes) must live outside it, in PDS-private storage or separate services.
- Keeping no history means a deleted post is gone from the source, but copies in indexers or archives can remain; deletion relies on well-behaved consumers honouring delete events.
The deterministic-structure idea links to the convergence properties of CRDTs in Conflict Resolution, OT and CRDTs.
3. Portable identity: DIDs and handles#
Identity has two layers: a permanent machine identifier (the DID) and a changeable human name (the handle). Everything in the network (follows, likes, replies, blocks) points to DIDs, never to handles or servers. That is what makes accounts portable.
DID methods. atproto supports two DID methods.
did:web: the DID is a domain, such asdid:web:alice.com, and its document is served athttps://alice.com/.well-known/did.json. Simple and fully self-controlled, but the identity is tied to owning that domain forever; losing the domain loses the identity.did:plc: a method created by Bluesky (PLC originally stood for "placeholder", later rebranded as "Public Ledger of Credentials"). The DID is derived from the hash of the account's first signed operation, such asdid:plc:ewvi7nxzyoun6zhxrhs64oiz. The PLC directory stores an append-only log of signed operations per DID, and serves the current DID document.
The DID document contains:
alsoKnownAs: the handle, asat://alice.com.verificationMethods: the signing key used to sign repo commits.services: the PDS endpoint URL.- For
did:plc, a list of rotation keys allowed to sign future operations, in priority order.
PLC operations and recovery. Every change to a did:plc document is an operation signed by one of the current rotation keys and linked to the previous operation's hash, forming a hash chain. The directory validates signatures and chain links before accepting. Typically the PDS holds a rotation key so it can update the document on the user's behalf, and the user can add their own higher-priority key (on a device or a recovery service). If a lower-priority key (say, a compromised PDS) makes an unwanted change, a higher-priority key can override it within a 72-hour recovery window. This gives users a real exit path, even from a hostile host.
Trust in the PLC directory. The directory is a central service run by Bluesky today, which is a known weak point. It cannot forge operations (they are signed by user keys), but it could refuse or delay operations, or show different histories to different clients. Mitigations: anyone can mirror and audit the full log (it is exported publicly), and the stated plan is to move governance to an independent organisation. A design review should name this dependency honestly.
Handles are domain names. A handle like alice.com is verified in both directions:
- Handle to DID. Resolve
_atproto.alice.comas a DNS TXT record containingdid=did:plc:..., or fetchhttps://alice.com/.well-known/atproto-did. - DID to handle. The DID document's
alsoKnownAsmust listat://alice.com.
Only when both agree is the handle shown. This stops someone from claiming a handle by editing their DID document, and stops a domain owner from hijacking a DID by pointing their domain at it. Domain handles also give organisation verification for free: @nytimes.com proves control of the domain. Large hosts give users subdomains (alice.bsky.social) by default.
Resolution and caching. Every service that shows handles or verifies commits resolves DIDs and handles. Resolutions are cached (minutes to hours), and refreshed when the firehose announces an identity event (the user changed handle or key). A DNS-based handle check depends on DNS TTLs; see DNS: The Domain Name System.
Key management choices.
| Key | Held by | Used for | If lost or stolen |
|---|---|---|---|
| Signing key | The PDS | Signing every repo commit | Rotate via a PLC operation; old commits stay valid as history |
| PDS rotation key | The PDS | Updating the DID document on the user's behalf | User's higher-priority key overrides within 72 hours |
| User rotation key (optional) | User device or recovery service | Recovery and migrating away from a hostile PDS | Without it, the user depends on the PDS's cooperation |
The PDS holds the signing key because users expect to log in from any device with a password; asking every user to manage private keys would cost most of them their accounts. This is a deliberate usability trade-off: custodial by default, self-custody optional. For background on key and token handling, see Authentication and Authorization.
4. Relays and the firehose#
A relay turns thousands of PDS streams into one. Without it, every App View and feed generator would maintain thousands of connections and handle every PDS's quirks.
Crawling. A PDS asks a relay to crawl it (requestCrawl), and the relay opens a WebSocket to the PDS's subscribeRepos endpoint. Each event from a PDS has a per-PDS sequence number, so after a reconnect the relay resumes with a cursor. A relay may also discover PDSes from DID documents seen in the stream.
Verification. For each commit event, the relay:
- Resolves the DID (cached) to find the expected PDS and signing key.
- Checks that the event came from the PDS listed in the DID document (an account cannot be spoken for by a random server).
- Verifies the commit signature.
- Checks the revision is newer than the last seen, and that the included tree blocks are consistent with the claimed operations.
Archival vs non-archival relays. The first relay design mirrored every repository, so it could verify each diff against the full previous state and serve any repo on request. That made a full relay expensive (tens of TB). A 2025 revision of the sync protocol had commits carry enough information (the previous data root plus the changed tree nodes) for a relay to verify each commit against the previous one alone. This let relays run without storing full repos, holding only recent events and per-account state (latest revision and root). Bluesky described this as making relays cheap enough for independent operators to run.
Sequencing. The relay assigns a global sequence number to each accepted event and appends it to its log. Consumers connect with cursor=N and receive every event after N. If a consumer falls too far behind (beyond the relay's retention, for example 72 hours), it must backfill by fetching full repos with getRepo.
Event types. The stream carries #commit (repo changes with blocks), #identity (DID document or handle changed), #account (activated, deactivated, taken down, deleted) and #sync (a full-state marker for resynchronisation). Consumers must handle all of them; ignoring #account takedowns, for example, keeps showing removed content.
Lightweight streams. Many consumers do not want CBOR and Merkle proofs; they want "new post by X with this text". Bluesky runs Jetstream, which converts the firehose into compact JSON events, lets consumers filter by collection or DID, and compresses the stream heavily. It is ideal for feed generators and bots that trust Jetstream's operator to have verified signatures. The trade-off: consumers no longer verify data themselves.
Failure modes.
- A noisy or malicious PDS floods events. Relays rate-limit per PDS and per account (events per second, new accounts per hour), and can ban a host.
- Out-of-order or duplicate events. Consumers deduplicate by (DID, revision) and drop revisions older than the last applied.
- Relay outage. Consumers can switch to another relay; global sequence numbers differ between relays, so a consumer switching relays resumes using the time or per-repo revisions and tolerates a short replay.
- Consumer lag. A slow App View indexer falls behind; it scales by partitioning events by DID across workers (keeping per-account order) and prioritising live events over backfill.
The relay is a classic log-based fan-out system: one ordered log, many independent readers with cursors, like a Kafka topic with a single partition per relay. See Apache Kafka in Practice and Delivery Guarantees: At-Most, At-Least and Exactly-Once.
5. The App View: indexing the network into a product#
The App View is where the decentralised network becomes a fast app. Architecturally it is a normal large social backend (like the one in the news feed case study), with one difference: its input is a public, untrusted, append-only stream, not its own application database.
The indexing pipeline.
- Consume the firehose with a durable cursor, partitioned by DID across many worker processes so each account's events stay in order.
- Decode and validate. Parse each record against its Lexicon schema; drop malformed records, oversized text and unknown collections (or store them raw for future use).
- Apply. For a create, insert into the right tables (post, like, follow). For a delete, remove the row and decrement counts. For an update (profiles, lists), replace.
- Derive. Update counts, thread indexes, notification entries ("Bob liked your post"), and timeline entries.
- Commit the cursor after the writes, so a crash replays events; writes must therefore be idempotent (insert keyed by URI, count changes guarded by the existence of the row).
Timelines. The home timeline (posts from people you follow, newest first) is built the same way as in any centralised network: fan-out on write for ordinary authors (append the post URI to each follower's timeline_entry partition) and fan-out on read for authors with huge follower counts (merge their recent posts at read time). The fan-out work for one post from an account with 50,000 followers is 50,000 small inserts, spread across shards; with 3 million posts a day and an average of 300 followers, that is about 900 million timeline inserts per day, or about 10,000 per second average. Old timeline entries are trimmed (for example, keep the newest 1,000 per user).
Threads. Every reply carries strong references to its parent and root. The App View indexes replies by root URI, so getPostThread reads one partition and builds the tree in memory, applying reply controls (who may reply), blocks between viewer and authors, and labels. A thread with 5,000 replies is loaded in pages, with the most relevant branches first.
Counts. Like, repost, reply and follower counts are derived from the indexed records. A viral post receives thousands of likes per minute, so counts are updated in batched increments (aggregate in memory for a second, then write) and cached. Counts are eventually consistent: a few seconds of lag is invisible. Because the App View sees every like on the network, the count is complete, unlike in server-to-server federation.
Hydration. Every view (timeline, feed, thread, search result) starts as a list of URIs (a skeleton) and is then hydrated: fetch post records, author profiles, counts, the viewer's state (did I like it, do I follow the author), embeds (quoted posts, link cards, images), labels from the viewer's labelers, and the block and mute relationships. A page of 30 posts needs hundreds of keyed reads, done as batched multi-gets against caches. This split (cheap skeleton, shared hydration) is what makes custom feeds cheap.
Trust and timestamps. The createdAt field is chosen by the author, so a spammer can backdate posts to make them appear old, or post-date them to pin them at the top. The App View records its own indexed_at and sorts by the earlier of the two (with bounds), so posts cannot jump ahead of honest ones.
Rebuilding. Because every view is derived from the firehose and repos, an App View can be rebuilt from scratch: crawl every repo (getRepo from each PDS), index it, then switch to the live firehose from a recorded cursor. For tens of millions of repos and billions of records, a full backfill takes days with high parallelism, bounded mostly by PDS fetch rates. This is the event-sourcing idea at network scale; see Event Sourcing and CQRS.
Storage choices. An early App View can run on sharded PostgreSQL. At tens of millions of users and billions of rows with heavy write rates, a wide-column store (Cassandra or ScyllaDB) is a natural fit for append-heavy, key-partitioned tables such as likes by subject and timelines by owner; Bluesky has described moving its App View from PostgreSQL to ScyllaDB as it grew. Read caching for hot posts and profiles uses Redis or Memcached. See Apache Cassandra in Practice and Pattern: Scaling Reads.
6. Custom feeds and feed generators#
Custom feeds are atproto's answer to "who controls the algorithm". Anyone can publish a feed, and any user can pin it as a tab. Thousands of custom feeds exist, from topic feeds ("Science", "Art") to social ones ("Mutuals", "Quiet posters", "Popular with friends").
The protocol. A feed is declared by an app.bsky.feed.generator record in the creator's repo, giving a display name, description, avatar and the service DID of the generator. The service DID's document names an HTTPS endpoint. To serve the feed, the App View calls getFeedSkeleton on that endpoint with the feed URI, a cursor and a limit, plus a JWT signed by the viewer's PDS identifying the viewer (for personalised feeds). The generator returns post URIs (and optional reasons such as "reposted by"), and the App View hydrates them.
Building a generator. A typical topic feed:
- Consume the firehose (often the JSON stream, filtered to posts).
- For each post, decide if it matches: keyword lists, language, a text classifier, image labels, author lists, or an embedding similarity to a topic.
- Store matching URIs with a score and timestamp in a small database (SQLite, PostgreSQL, Redis).
- On
getFeedSkeleton, return the top items after the cursor, sorted by score or time.
A popular feed with 300,000 users, each refreshing a few times per hour, sees maybe 200–500 requests per second at peak; with skeletons served from memory, a single modest server suffices.
handle getFeedSkeleton(feed, cursor, limit, viewerToken):
viewer = verifyJwt(viewerToken) -- optional, for personalisation
items = index.range(feed, before = decode(cursor), limit = limit)
if feedIsPersonal(feed):
follows = followsCache.get(viewer) -- e.g. "popular with my follows"
items = rerank(items, follows)
return feed = [item.uri for item in items],
cursor = encode(items.last.sortKey)Personalised feeds. Feeds such as "Popular with friends" need the viewer's follow graph and recent interactions. The generator can compute them from the firehose (follows and likes are public), at the cost of keeping a graph index. Some generators learn from interaction feedback: the protocol lets clients send "show more like this" or "show less" signals to the feed generator.
Why the skeleton split matters.
- The generator never stores or serves post content, so it is cheap and legally simpler.
- Moderation, blocks and takedowns are applied during hydration by the App View, so a feed generator cannot surface content the App View has removed or that the viewer has blocked.
- Clients render every feed with the same post views and counts.
Trade-offs and risks.
- Latency. The App View waits on a third-party service. It sets a tight timeout (hundreds of milliseconds), shows an error or cached page on failure, and may rank feeds by reliability.
- Privacy. The viewer's DID is revealed to the feed operator when personalisation is used. Users can be told which feeds receive their identity.
- Abuse. A feed may promote spam or harassment. Hydration still filters by the viewer's labelers and blocks, and the App View can stop serving a feed that violates its policy.
- Discoverability. With thousands of feeds, finding good ones becomes a search and ranking problem of its own (feed directories, "popular feeds" lists).
For the general ranking side, the recommendation system case study (Design a Recommendation System (Twitter For You)) shows candidate generation and ranking at scale; a sophisticated feed generator is a small version of it.
7. Labelers and stackable moderation#
In a centralised network one trust-and-safety team makes every call. atproto splits moderation into composable layers, so that no single policy is forced on everyone and so that new moderation services can be added without anyone's permission. Bluesky calls this stackable moderation.
What a label is. A label is a small signed object:
| Field | Meaning |
|---|---|
src | DID of the labeler that issued it |
uri | Subject: an account DID or a record AT URI |
cid | Optional: the specific version of the record |
val | Label value, such as spam, porn, graphic-media, !hide, or a custom value |
neg | True if this label removes an earlier one |
cts / exp | Creation time and optional expiry |
sig | Signature by the labeler's key |
Labels are not stored in user repos. They are published by the labeler service through subscribeLabels (a stream) and queryLabels. A labeler declares its label values, their definitions, default severity (inform, alert, hide) and whether they blur media or content in an app.bsky.labeler.service record.
How labels are applied.
- The user subscribes to labelers in their client (Bluesky's own labeler is applied by default and cannot be removed in its app; others are opt-in).
- For each label value, the user picks an action: hide, warn (blur behind a click) or show.
- The client sends its labeler list with each request (an HTTP header). The App View attaches labels from those labelers to every view it returns.
- The client applies the user's settings: hide the post, blur the image, show a badge.
Running a labeler. A labeler consumes the firehose and reports, runs automated classifiers (spam models, image classifiers, hash matching for known abusive images), queues items for human review, and emits labels. Bluesky open-sourced Ozone, its moderation review tool, so that communities can run labelers with queues, reports, actions and audit logs. Examples include labelers for specific harms (impersonation, AI-generated images), for community norms (spoiler tags for a TV show), and for verification ("this account belongs to a journalist").
Reports. When a user reports content, the client lets them choose which of their subscribed labelers receives the report. The report goes to that labeler's moderation queue. This routes reports to the services that care: a report about spoilers goes to the spoiler labeler, not to the main trust-and-safety team.
Lists as moderation. Users can create mute lists and block lists (app.bsky.graph.list records) and others can subscribe to them. A community can maintain a shared block list of harassers that thousands subscribe to. Subscribing is a soft form of delegating moderation.
Trade-offs.
- Composability vs consistency. Two users may see the same post very differently. That is the point, but it complicates support ("why is this hidden for me?") and requires clients to explain which labeler did what.
- Labeler abuse. A labeler could label people maliciously ("this account is a bot"). Because labels only affect subscribers, the damage is limited, and labels are signed so the source is always visible.
- Scale cost. Every view fetches labels from up to N labelers. App Views cap the number of labelers per user (Bluesky's app allows a limited number, around 20) and cache labels by subject.
- Speed. Automated labels arrive within seconds; human review takes minutes to hours. High-severity harms need the fast path at the infrastructure layer, not only at opt-in labelers.
8. Moderation in a decentralised network#
Labelers cover reach (what users see). But some content must be removed from the infrastructure entirely, and a decentralised network still has operators with legal obligations. Moderation therefore happens at every layer, with different powers.
| Layer | Power | Typical use |
|---|---|---|
| PDS host | Delete records, take down accounts, refuse to host | Illegal content, terms-of-service violations by hosted users |
| Relay | Stop relaying an account or a whole PDS; drop blobs | Illegal content, spam hosts, legal takedowns in its jurisdiction |
| App View | Refuse to index or show accounts and records; apply its policy to every view | Platform policy for its users |
| Labelers | Attach signed labels | Opt-in or default reach decisions |
| Feed generators | Exclude content from their feeds | Topic and community curation |
| User | Block, mute, mute words, reply controls | Personal boundaries |
Illegal content. Child sexual abuse material (CSAM) and terrorism content must be removed quickly, everywhere the operator controls. Large operators match images against known-hash databases (PhotoDNA is the common example) at upload and at ingestion, take down accounts with an #account event in the firehose, and report to the relevant authorities. Because images are blobs referenced by CID, a CID-level block list lets the relay and App View refuse to serve a known-bad blob even if it reappears in another account.
Takedowns propagate. When a PDS or relay takes down an account, it emits an #account event with status takendown. Well-behaved consumers stop showing that account and delete its indexed content. Consumers that ignore takedowns are a policy problem for their operators, not a protocol failure, much as a search engine that ignores removal requests is.
Harassment. Decentralised networks still need tools against pile-ons:
- Reply controls (threadgates): the author limits who can reply (followers, mentioned users, nobody), stored as a record the App View enforces.
- Quote controls (postgates): the author can detach their post from quote posts or disable quoting.
- Blocks are public. In atproto, blocks are records in the blocker's public repo, because every App View must enforce them consistently. The downside is that anyone can see who blocked whom, which can itself be used for harassment. The App View hides block lists in its UI and can rate-limit queries about blocks, but the data is in the public repo. This is a deliberate trade-off: enforceability over privacy, and a point interviewers like to probe.
- Mutes are private (stored on the PDS, outside the repo), because they only affect the muter's own views.
Spam. Account creation on the large host requires verification (email, phone or other checks) and is rate-limited. Relays and App Views score new accounts and hosts by behaviour (follow churn, mass mentions, link patterns), and labelers flag spam quickly. A PDS that hosts mostly spam can be cut off by relays, which is a strong incentive for hosts to police sign-ups.
Jurisdiction. Operators in different countries have different legal duties. A geographic labeler or App View rule can hide content in one country (for example, in response to a court order) without removing it globally, which matches how centralised platforms handle country-specific restrictions.
The open problem. If an independent App View chooses to show content that the main one removes, the content is still reachable, as it would be on the open web. The design goal is not universal removal of everything objectionable; it is fast removal of illegal content at the infrastructure Bluesky and other responsible operators run, and user choice for everything else. See Security Fundamentals for System Design for abuse-prevention basics and Rate Limiting and Throttling for spam control.
9. Comparison with ActivityPub (Mastodon)#
ActivityPub became a W3C Recommendation in January 2018 and powers the "fediverse": Mastodon, Pleroma, Misskey, PeerTube, Pixelfed and others. Comparing it with atproto clarifies what each design optimises.
How ActivityPub works. Each user lives on a server (an instance) and has an actor document with an inbox and an outbox. When Alice on a.social posts, her server wraps the post in a Create activity and pushes it with an HTTP POST to the inbox of every server that hosts at least one of her followers (shared inboxes reduce this to one delivery per server). Requests are signed with HTTP Signatures so the receiver can check they came from Alice's server. Discovery uses WebFinger (alice@a.social resolves to the actor URL). Each server stores the posts delivered to it and builds timelines for its own users.
Key differences.
| Aspect | ActivityPub (Mastodon) | atproto (Bluesky) |
|---|---|---|
| Identity | user@instance; the instance's domain is part of the identity | DID, independent of host; handle is any domain the user controls |
| Moving servers | Followers can be redirected with a Move activity; old posts stay behind | Whole signed repo moves; DID and all references stay valid |
| Data authenticity | Trust the sending server (HTTP Signatures on delivery) | Self-certifying data: records verifiable from the author's key, whoever serves them |
| Delivery | Push: author's server sends to each follower's server | Pull: relays crawl PDSes; indexers consume the firehose |
| View of the network | Each server sees what was delivered to it, so partial | Indexers see everything, so global |
| Reply threads and counts | Often incomplete (replies from servers you are not connected to are missing) | Complete, from the global index |
| Search | Limited, often by design (opt-in, local only) | Full-text search over the network in the App View |
| Feeds | Mostly chronological; ranking per server or client | Pluggable feed generators |
| Moderation | Instance admins moderate their users and defederate from bad servers | Layered: hosts, App Views, user-chosen labelers and lists |
| Cost model | Every server stores and processes everything it receives | PDSes are cheap; indexers are expensive and few |
| Who can shut you out | Your instance admin; other instances by defederating | Your PDS (but you can leave with your data); App Views and relays for reach |
Scaling behaviour. Push federation has costs that grow with the number of servers. A post from an account followed by users on 20,000 instances triggers 20,000 deliveries, and each receiving server then often fetches link previews and media, which can overwhelm the linked website (a known "thundering herd" effect in the fediverse). Small instances bear storage and moderation work for everything they receive. atproto concentrates that work in a few indexers, which is more efficient overall but raises the bar for running a full App View.
Community and moderation philosophy. ActivityPub's strength is community governance: each instance is a community with its own rules and moderators, and defederation lets communities cut off bad actors as a group. atproto's strength is individual choice: users choose labelers and feeds independently of their host. ActivityPub's weakness is that your experience depends heavily on your server choice and its relationships; atproto's weakness is that the main App View and relay are, in practice, run by one company today, so decentralisation depends on alternatives actually being built.
Interoperability. The two networks can be bridged. Bridgy Fed, an open-source bridge, mirrors accounts between the fediverse and Bluesky (and the web), translating posts, follows and replies. A bridge must map identities (an ActivityPub actor gets a DID and repo; an atproto account gets an actor) and accept that some features (labels, custom feeds, quote controls) do not translate.
Other designs worth knowing. Nostr uses key pairs as identities and simple relays that store and forward signed events; clients publish to and read from several relays. It is simple and censorship-resistant but leaves discovery, spam control and key recovery to users and clients. Farcaster anchors identity in smart contracts on Ethereum and syncs messages between "hubs" with a CRDT-like design. Both validate the same core idea as atproto: signed, self-certifying user data separates the author's identity from any server.
When to pick which. For community-run, smaller-world social spaces with local norms, ActivityPub fits. For a global, Twitter-like public square with complete views, search and algorithmic choice, atproto fits. For maximal censorship resistance with minimal infrastructure, Nostr-like designs fit.
10. Media: blobs, CDNs and abuse scanning#
Images and videos are blobs. They are uploaded to the user's PDS, referenced from records by CID, and served to viewers through the App View's CDN.
Upload. The client calls uploadBlob with the bytes. The PDS hashes them to a CID, stores them in object storage (or a local disk for a small PDS) and returns a blob reference (CID, MIME type, size). The client then creates a post record embedding that reference. Blobs not referenced by any record within a grace period (for example, a few hours) are garbage-collected. Size limits apply (for example, about 1 MB per image after client-side resizing, larger for video).
Serving. Viewers do not fetch from PDSes directly: a viral image would overload a self-hosted PDS. The App View exposes image URLs on its CDN; a CDN miss goes to an image service that fetches the blob from the author's PDS (getBlob with DID and CID), verifies the CID (the hash proves the bytes are what the author referenced), creates resized variants (thumbnail, feed size, full size) and caches them. Because blobs are immutable and content-addressed, cache entries never need invalidation; only takedowns remove them.
Video. Video needs transcoding into adaptive bitrate streams (HLS) at several resolutions. A PDS cannot reasonably do this for every user, so a video service run by the large host or App View processes uploads (the client may upload through it), stores the processed renditions, and serves them from a CDN, while the original blob stays in the user's repo for portability.
Abuse scanning. Every new blob seen by the App View or large host is hashed (cryptographic and perceptual hashes) and checked against known illegal-content databases, then passed through classifiers that produce labels (nudity, gore). Matches block the CID network-wide on that operator's infrastructure, take down the account and trigger legal reporting.
Cost. At the assumed 225 GB of new images per day, storage grows by about 80 TB a year before replication and variants. Egress through the CDN is the dominant cost for a popular network; image variants (WebP or AVIF at feed size) cut bytes per view by 5–10 times compared with originals. See Content Delivery Networks (CDN), Object Storage and Blob Storage and Pattern: Handling Large Files and Blobs.
11. Private data, direct messages, search and notifications#
atproto repos are public by design, which makes the public square simple and makes private features hard. A complete design must say where non-public data lives.
Private state on the PDS. Some data affects only the owner: mutes, muted words, saved feeds order, notification settings, drafts. These live in PDS-private preferences (app.bsky.actor.getPreferences and putPreferences), stored per account but outside the repo. They move with the account during migration because the user can export them, but they are never in the firehose.
Direct messages. Bluesky launched DMs in 2024 as a centralised service run alongside the App View, not as repo records, because DMs must not appear in the public firehose. The client talks to a chat service through its PDS proxy, and the chat service stores conversations keyed by participant DIDs. The stated direction is end-to-end encrypted messaging, for which the IETF Messaging Layer Security (MLS) protocol (RFC 9420, 2023) is the natural candidate. A design interview answer should say: DMs use a separate messaging system (as in the chat-system case study, Design a Chat System (WhatsApp)), identified by DIDs, with end-to-end encryption keys published per device; the decentralised part is identity, not storage.
Search. Full-text search is built from the firehose like any other view: an indexer tokenises posts (language detection matters, as the network is multilingual), writes them to Elasticsearch or OpenSearch, and serves searchPosts and searchActors. Deletes and takedowns from the firehose remove documents. Search ranks by text relevance plus engagement and recency, and respects blocks and labels at query time. Typeahead for handles uses a prefix index over handles and display names. See Elasticsearch and Search Systems.
Notifications. The App View indexes every record that mentions, replies to, quotes, likes, reposts or follows a user, keyed by the subject DID, giving listNotifications. Push notifications to phones are sent by a notification service that consumes the same derived events and calls APNs or FCM for users who registered a device token with their PDS. Grouping ("Alice and 52 others liked your post") is done at read time from the notification index.
Privacy implications of public data. Likes, follows and blocks are public. Users must be told this clearly, and the product should avoid features that encourage harassment based on that data (for example, the official app does not show who blocked whom, even though the data exists). Researchers and archivers can collect the full public dataset, which raises data-protection questions about deletion: a well-behaved consumer must honour deletes from the firehose, but the protocol cannot force every consumer to do so.
12. Scaling and operating the network#
The App View at scale. The App View is the single largest system and follows standard large-backend practice:
- Ingestion partitions firehose events by DID across hundreds of workers. Each worker applies events for its DIDs in order, with idempotent writes, so a restart replays safely.
- Storage shards by the main query key: posts by URI (and author index by author DID), likes by subject URI, follows by creator and by subject, timelines by owner. Hot partitions (a viral post's likes) use write batching and sharded counters.
- Caching of profiles, post records, counts and labels in Redis or Memcached absorbs most hydration reads; viral posts get request coalescing so a thousand concurrent views cause one storage read. See Distributed Caching with Redis and Memcached.
- Read path keeps views within a few batched round trips: one skeleton read (timeline partition or feed generator), one multi-get for records and profiles, one for counts and viewer state, one for labels.
Backfill and re-indexing. New views (a new index, a new count, a fixed bug) require reprocessing history. Options: replay a stored archive of the firehose, or crawl repos again. Keeping a full archive (about 75 GB a day at the assumed rates before compression) makes re-indexing a batch job rather than a network crawl. Re-indexing runs in a separate pipeline and swaps tables when caught up, so live traffic is unaffected.
Handling bursts. Major news or a mass migration of users from another platform can multiply sign-ups and events by 10 times within days. The PDS fleet scales horizontally (new instances take new accounts), relays and indexers must have headroom, and the App View can temporarily degrade non-critical work (delay notifications grouping, lower search freshness) to protect timelines.
Multi-region. Most reads are served from caches and replicas near users; ingestion and writes to the view database can stay in one primary region with asynchronous replicas, because the firehose is already eventually consistent. Read-your-writes for the author is handled by the client: after creating a post, the client inserts it into its own view immediately, and the App View can also read the author's PDS for very recent records. See Multi-Region and Global Data.
Independent operators. For the network to be genuinely decentralised, independent relays and App Views must be affordable. Design choices that help:
- Non-archival relays (Deep Dive 4) cut relay storage to recent events.
- App View scope can be narrow. A community App View can index only some collections, or only the accounts its users follow plus their interactions, using far less storage than a full index.
- Feed generators and labelers are small by design, because hydration and enforcement happen in the App View.
- Open-source reference implementations (PDS, relay, App View, Ozone) lower the barrier.
Governance risks to name in an interview. The main App View, relay and the PLC directory are run by one company at present. Its policies shape most users' experience. The protocol's answer is credible exit: because identity and data are portable and views are rebuildable, a competitor can offer an alternative without users' permission being needed from Bluesky. Whether that exit is practical depends on the cost of running a full-network App View, which is the metric to watch.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Main relay outage | Firehose stops; App Views, feeds and labelers go stale | Multiple relay instances behind failover; consumers resume from cursors; independent relays as alternatives |
| App View indexer lag | Posts appear late in timelines, counts stale | Partition by DID across workers, autoscale on lag, prioritise live events over backfill, degrade non-critical derivations |
| Viral post | Hot partitions for likes and counts, CDN surge for its image | Batched counters, request coalescing, cache hot post views, CDN with immutable blob URLs |
| Spam PDS or bot wave | Floods firehose with junk accounts and posts | Per-host and per-account rate limits at relays, host reputation, account scoring, labelers, cutting off abusive hosts |
| PLC directory unavailable | New accounts and identity changes fail; resolutions rely on caches | Aggressive DID document caching, read-only mirrors of the log, queued operations |
| Compromised PDS signing key | Forged posts in a user's name | Rotate keys with a PLC operation; higher-priority rotation key overrides within 72 hours; consumers re-verify after identity events |
| Hostile or vanished PDS | User loses access to their host | User rotation key updates the DID document; restore repo from a backup or an indexer's copy; migrate |
| Feed generator slow or down | Custom feed tab errors or hangs | Strict timeouts, cached last page, feed health ranking, graceful error UI |
| Labeler fan-out | Many labelers per user slow hydration | Cap labelers per user, cache labels by subject, subscribe to label streams instead of querying per view |
| Ignored takedowns by consumers | Removed content still visible elsewhere | Infrastructure-level removal by responsible operators; CID block lists; policy enforcement for API access |
| Backdated or future-dated posts | Spam pinned at the top, chronology manipulated | Sort by the earlier of claimed time and indexed time, bound clock skew |
| Full re-index required | Days of backfill, high load on PDSes | Keep a firehose archive, batch re-index in a separate pipeline, throttle repo crawls per host |
What Interviewers Expect#
Mid-level. Explain why users want data and identity portability and what federation means. Describe the main pieces: a server that hosts each user's data (PDS), a stream that aggregates all changes (relay and firehose), and an indexer that builds timelines and threads (App View). Show the post flow end to end and a basic data model for posts, follows and likes. Mention that records are signed so others can trust them.
Senior. Explain DIDs and handles, with bidirectional handle verification, and how migration works including the case of a dead host. Describe signed repositories with Merkle trees, CIDs and proofs, and why the tree shape being independent of history helps sync. Design the App View like a large feed system (fan-out, hydration, counts, caching) with idempotent ingestion from a cursor. Explain the feed generator skeleton and hydration split and the layered moderation model with labelers. Compare with ActivityPub on identity, delivery and global view.
Staff and above. Reason about the economics of decentralisation: which roles are cheap (PDS, feeds, labelers) and which are expensive (full App View), and how protocol choices (non-archival relays, lightweight streams, narrow App Views) lower the cost of alternatives. Discuss trust boundaries: the PLC directory as a central dependency and how to audit it, custodial keys versus self-custody, and what consumers must verify. Address moderation at every layer, including illegal content, jurisdictional takedowns and the public-blocks trade-off. Cover private data (DMs with MLS, preferences off-repo). Plan burst handling, re-indexing and multi-region serving, and name the governance risk of one dominant operator and the "credible exit" answer to it.
Deep Dive: Sizing every tierShow
The assumptions: 40 million accounts, 5 million DAU, 50 million repo events a day (580 per second average, 5,000 peak), 3 million posts a day, 225 GB of new images a day.
PDS fleet (large host). 39 million of the 40 million accounts sit on the main host. With 500,000 accounts per PDS instance, that is about 80 instances. Each holds about 500,000 × 1 MB of repo data (about 500 GB) on local SSD as per-account SQLite files, plus blobs in object storage. Write load per instance: 5,000 events per second peak spread over 80 instances is about 60 commits per second each, trivial for SQLite with one writer per account. Reads: each client request passes through its PDS (proxying to the App View), so the PDS tier handles the full API request rate, about 20,000 per second at peak, mostly cheap proxying: a few dozen instances with headroom.
Relay. Inbound 5,000 events per second at about 1.5 KB is 7.5 MB/s. Outbound with 500 full-firehose consumers is 3.75 GB/s, or 30 Gbit/s, so the relay fans out through several edge nodes, each serving a share of consumers from the same log. CPU for signature checks is about one core. Storage for 72 hours of events: about 225 GB. A non-archival relay needs per-account state (DID, latest revision, data root): 40 million × 200 bytes = 8 GB, in memory or a local key-value store.
JSON stream. Compact JSON events with compression (zstd with a shared dictionary) can be several times smaller than the CBOR firehose with blocks. With 5,000 bots and feed generators subscribed, each filtered to posts only (about 6% of events), the outbound bandwidth stays a few Gbit/s.
App View storage. 40 million repos with an average of 2,000 records is 80 billion records. Likes dominate (about two-thirds). With about 150 bytes per indexed like row plus indexes and three replicas, likes alone take roughly 53 billion × 150 × 2 × 3 ≈ 48 TB; posts (5 billion × 600 bytes × 2 indexes × 3 replicas) ≈ 18 TB; follows (8 billion × 120 × 2 directions × 3) ≈ 6 TB. Total about 75 TB, on a cluster of 40–60 wide-column nodes with 2–4 TB of NVMe each.
Timelines. 5 million active timelines × 1,000 entries × 60 bytes = 300 GB, small enough for memory-heavy nodes. Fan-out inserts at 10,000 per second average, 80,000 at peak.
App View reads. 20,000 API requests per second at peak, each about 20–40 keyed reads after the skeleton, so 400,000–800,000 cache reads per second, which a cache cluster of 20–40 nodes handles comfortably; with a 95% hit ratio, the database sees 20,000–40,000 reads per second.
Search. 5 billion posts at about 1 KB per indexed document is 5 TB per copy; with replicas and indexes, 15–20 TB across a search cluster of 30–50 nodes. Indexing at 3 million posts a day is about 35 per second, trivial; query load is a few thousand per second at peak.
Media. 225 GB of originals a day plus variants (about 50% more) is about 340 GB a day, 120 TB a year. CDN egress: 5 million DAU × 300 image views × 100 KB per feed-size image ≈ 150 TB a day, about 14 Gbit/s average, which is why CDN unit cost dominates the media budget.
Feed generators. A top feed with 300,000 users at 500 requests per second needs one or two small servers and a few GB of candidate storage. The whole ecosystem of thousands of feeds is cheap because hydration lives in the App View.
Identity. 40 million DIDs × 3 operations × 1 KB = 120 GB in the PLC log; resolutions mostly served from caches with TTLs of minutes to hours and refreshed on #identity events.
Takeaway. The App View (storage, caches, search) and media egress dominate cost. A full-network relay is now a modest bandwidth service. A PDS for thousands of users is a single small server.
Deep Dive: Real-world decentralised social systems comparedShow
| System | Identity | Data model | Distribution | Global view | Moderation |
|---|---|---|---|---|---|
| Bluesky (atproto) | DID (did:plc or did:web) plus domain handle | Signed Merkle repo per user | PDS to relay to App View (pull and aggregate) | Yes, via indexers | Layered: hosts, App Views, labelers, lists |
| Mastodon (ActivityPub) | user@instance via WebFinger | Activities stored by each instance | Server-to-server push to followers' inboxes | Partial per instance | Instance admins, defederation |
| Threads (Meta) | Meta account; ActivityPub federation added for some users | Centralised store | Centralised, with outbound ActivityPub sharing | Yes, internally | Centralised trust and safety |
| Nostr | Public key | Signed events | Clients publish to and read from multiple relays | Depends on relays queried | Relay policies and client filters |
| Farcaster | On-chain ID registry (Ethereum) | Signed messages | Hubs sync with each other | Yes, each hub aims at a full copy | Client and app-level filtering |
| Twitter / X | Company account | Centralised | Centralised | Yes | Centralised |
What each teaches.
- Bluesky: separating hosting from indexing gives a centralised-quality product on decentralised data; the cost is that indexers are big.
- Mastodon: push federation keeps each community independent, at the price of partial views and per-server costs that grow with the network.
- Threads: a centralised network can add federation as an export and import layer, which interoperates without making the core decentralised.
- Nostr: the minimum viable decentralised social protocol is signed events plus dumb relays; everything else (discovery, spam, recovery) becomes a client problem.
- Farcaster: a blockchain can anchor identity cheaply while message data stays off-chain.
Deep Dive: A 45-minute interview planShow
| Minutes | Focus | What to say and draw |
|---|---|---|
| 0–5 | Clarify | How decentralised? Must users be able to leave a hostile host? Public only, or DMs too? Global search and complete counts needed? Who builds feeds and moderates? |
| 5–10 | Estimate | Accounts, DAU, events per day and per second, event size, firehose bandwidth per consumer, App View storage; show that hosting is cheap and indexing is expensive |
| 10–20 | High-level design | Client, PDS with signed repo, DID and handle resolution, relay and firehose, App View, feed generators, labelers; walk one post from write to a follower's timeline |
| 20–35 | Deep dives | Pick two or three: signed repos and Merkle proofs; identity and migration with rotation keys; App View ingestion and hydration; feed skeletons; stackable moderation |
| 35–42 | Scale, failures, abuse | Relay outage, indexer lag, spam hosts, key compromise, takedowns, viral posts |
| 42–45 | Compare and wrap up | ActivityPub push federation versus atproto aggregation; centralised risks that remain (PLC directory, dominant App View); credible exit |
Opening line that works. "I will separate speech from reach: each user's data lives in a signed repository on a host they can leave, and all the expensive aggregation (timelines, search, counts, ranking, moderation) is done by replaceable services that read a public stream."
Where candidates lose time. Designing a blockchain; spending ten minutes on cryptography details; forgetting that a good product needs a global index; treating moderation as an afterthought; ignoring how a user recovers when their host disappears.
What to draw. Three columns: hosts (many small PDSes and one large fleet), the relay in the middle, and consumers (App View, feeds, labelers) on the right, with the DID directory above. Then draw the post's path in one colour and the migration path in another.
Deep Dive: Follow-up questions and strong answersShow
"Why not just use ActivityPub?" ActivityPub ties identity to a server, so moving loses the identity and history; it delivers by push, so each server has a partial view, with incomplete threads, counts and search; and data is trusted per server rather than self-certifying. atproto makes identity portable, data verifiable from anyone, and global views possible through aggregation. ActivityPub is better at community-level governance and does not need large indexers.
"Isn't the relay a central point of control?" The relay only aggregates public, signed data; it cannot forge or alter records. Anyone can run another relay that crawls the same PDSes, and consumers can connect to several. The real centralising force is cost, so the protocol keeps relays cheap (non-archival operation, verification per commit).
"How does a user recover if their PDS deletes their account?" If they hold a higher-priority rotation key, they sign a PLC operation pointing their DID at a new PDS within the recovery window, or at any time if the old PDS made no conflicting change. They restore their repo from a backup CAR file, or from a copy held by an App View or archive, which is safe because the repo is signed and its root can be checked. Followers keep following the DID.
"What stops a PDS from forging posts for its users?" Nothing cryptographic, if the PDS holds the signing key, which it usually does. The defences are reputation, the user's ability to leave with their data, and optional user-held rotation keys to revoke the PDS's authority. Users who need stronger guarantees can self-host or use a host that lets them hold keys.
"How are like counts accurate in a decentralised network?" Every like is a public record in the liker's repo, and the App View sees the whole firehose, so it counts every like on the network. Counts are eventually consistent by a few seconds. A competing App View computes the same counts from the same data.
"How do custom feeds avoid becoming a spam channel?" The feed generator returns only URIs; the App View hydrates them and applies takedowns, blocks, mutes and the viewer's labelers. A malicious feed can only reorder content the viewer could already see. Abusive feeds can be delisted or blocked by the App View.
"How would you add direct messages?" Keep them out of the public repo. Run a separate messaging service keyed by DIDs, with device keys published for end-to-end encryption using MLS, so the server stores only ciphertext. Federation for DMs can come later by letting each PDS route messages for its users.
"What happens when a celebrity with 5 million followers posts?" Their PDS commits one record; the relay emits one event; the App View does not fan out to 5 million timelines but merges that author's recent posts at read time for their followers (fan-out on read for big accounts). Their likes then hit a hot partition, handled with batched counters and caching.
"How would you rebuild the App View from scratch?" Record the current firehose cursor, crawl every repo with getRepo in parallel (rate-limited per host), index all records, then replay the firehose from the recorded cursor to catch up, applying idempotent writes. With a firehose archive the crawl can be replaced by replay.
"Why are blocks public?" Every App View, feed and service must enforce blocks between two accounts, including services the blocker does not use. Public block records make that possible without a central authority. The cost is that block relationships are visible; the trade-off is enforceability over privacy, and clients avoid exposing it.
Deep Dive: Merkle Search Trees, proofs and sync in detailShow
Building the tree. For each key, compute SHA-256 of the key string and count leading zero bits in 2-bit chunks: the key's layer is that count. Key app.bsky.feed.post/3kq2abc might hash to a value starting with binary 0000 01..., giving 2 chunks of zeros and layer 2. About 75% of keys are at layer 0, 19% at layer 1, 5% at layer 2, and so on, each layer 4 times rarer than the one below. Each node holds the keys of one layer within a key range, in sorted order, with left subtree pointers between them pointing to nodes of the layer below. Nodes compress keys by sharing prefixes with the previous key, which matters because keys in a collection share long prefixes.
History independence. Insert keys in any order and you get the same tree, because each key's layer and the sort order fully determine the structure. That property is the reason for choosing an MST over a B-tree, whose shape depends on insertion order and split history. Two replicas compare root CIDs; if they differ, they compare child CIDs and descend only into differing subtrees, so finding a single changed record in a 100,000-record repo takes about log base 4 of 100,000 ≈ 8 node comparisons.
Worked example: a like. Alice likes a post. Her PDS inserts app.bsky.feed.like/3kr9xyz (layer 0). The leaf node for that key range changes, so its CID changes; its parent's pointer changes, so the parent's CID changes; and so on up to the root. For a repo of 20,000 records (depth about 7), the commit produces about 7 new tree nodes (each 100–400 bytes), 1 record block (about 150 bytes) and 1 signed commit block (about 300 bytes): roughly 2 KB of new blocks, matching the firehose event size assumed in the estimates.
Proofs. To prove "this record with this CID is in Alice's repo at revision R", send the signed commit, the root node and each node on the path to the key. The verifier checks the signature against Alice's key in her DID document, hashes each node to check it matches the pointer above, and finds the record CID in the leaf. Proving absence works the same way: show the path to where the key would be and that it is not there. getRecord returns exactly this proof, so a consumer can fetch a single record from an untrusted mirror and verify it.
Commit inversion for relays. A firehose #commit event includes the operations (create, update, delete with paths and CIDs), the new blocks, the previous revision and the previous data root (prevData). A relay that keeps only the latest root per account can invert the operations on the partial tree in the event: undo each operation and check that the resulting root equals prevData, and that prevData equals the root it saw last time. If both hold, the commit is a valid, complete successor of the previous state, verified without the full repo. If the chain breaks (a missed event, a host bug), the consumer marks the repo as out of sync and fetches the full CAR export.
Garbage and history. Because only the current tree is kept, old nodes become garbage after each commit and are deleted. This keeps repos small but means the protocol has no built-in edit history or "undelete". A service wanting history must archive the firehose.
Comparison with Git. Git also content-addresses blobs and trees and signs commits optionally. The differences: Git keeps full history and its trees mirror directory structure, while the MST keeps current state only and is a balanced search tree over flat keys, built for key-range operations and cheap proofs.
| Operation | Cost for a repo of n records |
|---|---|
| Insert, update or delete a record | O(log₄ n) node rewrites, one signature |
| Prove presence or absence | O(log₄ n) nodes |
| Diff two versions with k changes | O(k log₄ n) nodes |
| Full export | O(n) blocks in a CAR file |
Deep Dive: Ordering and consistency without a central databaseShow
A decentralised network has no single clock and no global transaction log. The design accepts eventual consistency across services and gives strong ordering only within each repository.
Per-repo order. Each commit has a revision (a TID) strictly greater than the previous one. The PDS is the single writer for a repo, so a repo's history is linear. Consumers apply a repo's events in revision order and drop anything older than what they have. This is the same per-key ordering idea as partitioning a Kafka topic by key.
No cross-repo order. Alice's reply and Bob's original post live in different repos and may reach an App View in either order, or through different relays. The App View must handle a reply whose parent it has not seen yet: store the reply, mark the thread as incomplete, and attach it when the parent arrives. Likes of unknown posts are stored and counted once the post appears. Deletes of unknown records are recorded as tombstones so a late create does not resurrect them.
Timestamps are claims. createdAt is set by the author's client and can lie. The App View's own indexedAt is trustworthy only for that App View. Sorting uses a bounded combination: the claimed time, unless it is later than the indexed time (future-dated) or far earlier (backdated beyond a window), in which case indexed time wins. See Time, Clocks and Ordering.
Duplicates and uniqueness. Nothing in the protocol stops Alice's PDS from writing two like records for the same post. The App View enforces "one like per user per post" with a unique key (subject URI, creator DID), so the second like is ignored for counting. Follows are deduplicated the same way. This is an example of constraints enforced at the view, not at the source: the source is a free-form log of the user's statements, and each view decides how to interpret them.
Read-your-writes. After posting, a user expects to see their post immediately. The PDS returns the new record's URI and CID, and the client inserts the post into its local view. For a page refresh within seconds, the PDS can merge the user's own recent records (which it has locally) into App View responses, which atproto's PDS does for some views. This gives read-your-writes for the author without making the global pipeline synchronous.
Divergent views. Two App Views may show different counts or threads for a few seconds, or permanently if their policies differ (one hides an account). This is acceptable because there is no single truth for views, only for repos. The CAP framing: the system chooses availability and partition tolerance for views, and gets consistency per repo from a single writer. See CAP Theorem and PACELC and Consistency Models.
Identity changes in flight. If Alice rotates her signing key, events signed with the old key may still be in transit. Consumers that fail to verify a signature should refresh the DID document before rejecting, and accept the commit if the new document's key matches. A key rotation followed by a takedown or migration produces #identity and #account events that consumers must apply before further commits from that DID.
Deep Dive: Inside a PDS hosting millions of accountsShow
One database per account. The reference PDS stores each account's repo and records in its own SQLite file, plus a small shared database for account metadata (DID, email, password hash, status). Benefits: an account's data can be moved, backed up or deleted as one file; there is no lock contention between users; a corrupt file affects one user; and queries never span accounts. The cost: many open files and per-file overhead, handled by caching open handles for active accounts and keeping inactive ones closed.
Sharding the host. A large host runs many PDS instances, each with hundreds of thousands of accounts. An entryway service handles sign-up and login, knows which instance hosts each account, and directs the client to its PDS. Because each account's DID document names its PDS instance URL, the rest of the network talks to the right instance directly. Moving an account between instances of the same host is a migration like any other.
Authentication. Clients authenticate to their PDS. atproto adopted OAuth 2.0 with modern security profiles (PKCE, DPoP-bound tokens, pushed authorisation requests), so third-party apps never see the user's password; older clients used app passwords, scoped revocable passwords per app. For calls to other services (App View, feed generators, chat), the PDS issues service-auth JWTs signed with the account's key, with the target service DID as audience and a short expiry. The receiving service verifies the JWT against the user's DID document. See Authentication and Authorization.
Event stream. Each PDS exposes subscribeRepos with its own sequence numbers. It keeps a window of recent events (hours to days) so relays can resume after a disconnect, and emits #identity and #account events when users change handles, migrate or are taken down.
Account lifecycle.
| State | Meaning | Firehose event |
|---|---|---|
| Active | Normal operation | #account active |
| Deactivated | User paused the account; data kept, not served | #account inactive, deactivated |
| Taken down | Host removed the account for policy reasons | #account inactive, takendown |
| Deleted | User deleted; repo and blobs removed | #account inactive, deleted |
| Migrated away | DID document points elsewhere; old PDS stops serving | #identity from the new host |
Small PDS operation. A self-hoster runs the same software on a 1–2 vCPU virtual machine with a few GB of disk, behind TLS with a domain name, and asks the relay to crawl it. Back-ups are copies of the SQLite files and blobs. The operator is responsible for their users' content and for complying with takedown requests, as any web host is.
Rate limits and quotas. Per-account write limits (for example, thousands of records per hour, with lower limits for new accounts), blob size and total storage quotas, and login attempt limits protect the PDS and the wider network. Relays apply their own limits per host, so a PDS that does not police its users risks being cut off.
Deep Dive: Lexicon schemas and XRPC for an open ecosystemShow
In a centralised system, one team owns the schema and changes it with a migration. In an open network, thousands of independent programs read and write the same records, so schemas must be globally named, versioned by compatibility rules, and machine-readable. atproto's answer is Lexicon.
Namespaced IDs. Every record type and API method has an NSID, a reversed domain name plus a name: app.bsky.feed.post, app.bsky.graph.follow, com.atproto.repo.createRecord. Whoever controls the domain bsky.app controls the app.bsky.* namespace. A third-party app can define its own types (for example, a long-form blogging app defining com.example.blog.entry) and store them in the same user repos, so one identity and one repo serve many apps.
Schema documents. A Lexicon file describes a record (its fields, types, required fields, string formats such as datetime, did, at-uri, length limits in bytes and in graphemes) or a method (parameters, input and output schemas, error names). The reference implementations generate types and validators from these files, so a post that exceeds the text limit is rejected by the PDS and ignored by App Views.
Evolution rules. Once published, a Lexicon may only change in backwards-compatible ways: add optional fields, never remove or retype existing ones, never make an optional field required. Breaking changes need a new NSID. Consumers must ignore unknown fields, and open unions (fields that can hold one of several types, such as a post's embed being an image, a link card, a quote or a video) must tolerate types they do not recognise. This is the same discipline as Protocol Buffers' field rules, applied to an ecosystem with no central deployment.
Strong references. Fields that point to other records use a strongRef (URI plus CID), so a reference names both the record and the exact version, and a client can verify that it received the version that was referenced.
XRPC. API methods map to HTTP: queries are GET /xrpc/<nsid>?params and procedures are POST /xrpc/<nsid> with a JSON or binary body. Streams (subscribeRepos, subscribeLabels) are WebSockets carrying CBOR frames. The method's NSID tells a PDS where to proxy a request: app.bsky.* methods go to the user's chosen App View, chat methods to the chat service, and so on, with the target selectable by a request header naming the service DID.
Why this matters for design. The ecosystem has no flag day. A new feature (say, video posts) ships by adding a new embed type to the open union; old clients show a fallback ("unsupported content") and keep working; new App Views index it. Getting this right early avoids the "everyone must upgrade at once" problem that kills open protocols. For the general API side, see API Design Best Practices.
Deep Dive: Economics and governance of decentralised infrastructureShow
A decentralised protocol is only as decentralised as the cost of running an alternative. A rough cost picture at the assumed scale (cloud list prices, order of magnitude only):
| Role | Typical size | Rough monthly cost | Who can run it |
|---|---|---|---|
| Self-hosted PDS (1–1,000 users) | 1 small VM, tens of GB | Tens of dollars | Individuals, communities |
| Large PDS fleet (40 million users) | About 100 instances plus object storage | Tens of thousands of dollars before media egress | Companies, large communities |
| Non-archival relay (full network) | A few servers, high bandwidth | Hundreds to low thousands of dollars, mostly egress | Small companies, enthusiasts |
| Full App View | 50–100 TB database, caches, search, CDN | Hundreds of thousands of dollars including media egress | Well-funded organisations |
| Feed generator | 1 small server | Tens of dollars | Anyone |
| Labeler | 1–3 servers plus human moderators | Mostly moderator time | Communities, NGOs, companies |
Implications.
- Hosting and curation are open to almost anyone, so the long tail of feeds and labelers is real.
- The App View is the concentration point. Options to reduce it: App Views that index a subset (one community, one language), shared infrastructure (one indexer serving several front-end apps with different moderation and feeds), and protocol work that makes partial indexing correct (for example, fetching missing thread parents on demand).
- Media egress dominates costs at scale, so an alternative App View can point to the main CDN for images if allowed, or proxy only thumbnails.
Business models. The main operator must fund the expensive pieces without the lock-in a centralised network uses. Options discussed for networks like this include paid features that do not touch the protocol (custom domains, higher upload limits, premium client features), marketplace or payment features for creators, and services for organisations (verified domains, moderation services). Advertising is possible but conflicts with algorithmic choice, because users can switch to a feed without ads.
Governance. Three pieces benefit from neutral governance: the PLC directory (move it to an independent organisation with a public audit log), the protocol specification (open standardisation, for example through the IETF; Bluesky has said it intends to take atproto to a standards body), and default moderation (transparent policies and appeals). An interviewer at staff level may ask: "What would make you trust this network more than Twitter?" A good answer lists verifiable data, portable identity, open alternatives that actually exist, and published, auditable infrastructure logs.
Failure scenario to discuss. If the main operator went out of business, users with their own rotation keys could repoint DIDs; PDSes run by others would keep working; relays and App Views would need to be stood up by someone else from the public data. The design's promise is not that nothing breaks, but that nothing is lost and anyone can rebuild.
Deep Dive: Worked example: building a Science feed end to endShow
Suppose a developer wants a "Science" feed: posts from working scientists and posts about research papers, ranked by a mix of recency and engagement, for about 100,000 subscribers.
Step 1: declare the feed. The developer creates a service DID (often did:web:feeds.example.org) whose document lists an HTTPS endpoint, and writes an app.bsky.feed.generator record in their own repo with the display name, description, avatar and that service DID. The feed's identity is the AT URI of that record, so it survives a change of servers: only the service DID document needs updating.
Step 2: ingest candidates. A small worker connects to the JSON stream filtered to app.bsky.feed.post and app.bsky.feed.like. Posts arrive at about 35 per second on average (3 million a day). For each post, a classifier decides relevance: an allow-list of 20,000 scientist accounts (curated, plus users who apply), keyword and link rules (links to arXiv, journal domains, DOIs), and a small text model scoring "is this about research". About 1% of posts pass, roughly 30,000 per day, stored with their author, time and a base score.
Step 3: track engagement. Likes and reposts on candidate posts update a counter per URI in memory with periodic flushes to SQLite or PostgreSQL. With 30,000 new candidates a day and a 3-day window, the working set is under 100,000 rows: a few tens of MB.
Step 4: rank. A simple and robust score is engagement decayed by age, similar to the "hot" formulas used by link aggregators: score equals the logarithm of one plus weighted engagement, minus age in hours divided by a half-life constant, plus a bonus for allow-listed authors. Re-rank every minute into a sorted list of the top 2,000 URIs. Cursors encode the score and URI of the last item returned, so pagination is stable while ranking updates.
Step 5: serve. getFeedSkeleton returns 30 URIs per page from the in-memory list in under a millisecond. With 100,000 subscribers opening the feed a few times a day, peak load is perhaps 100–300 requests per second, which a single small server handles with ease. If personalisation is wanted ("hide posts from people I already follow", "boost my field"), the generator verifies the viewer JWT and uses the viewer's follows, which it can cache from the stream.
Step 6: operate. The developer monitors the skeleton latency (the App View gives up after a short timeout), stream lag, and complaints. Moderation is mostly handled by the App View's hydration, but the developer can drop accounts or posts from their own feed. Abuse (spammers posting arXiv links) is handled by requiring a minimum account age and by excluding accounts labelled spam by a trusted labeler.
What this shows. A feed that would be an internal ranking project at a centralised company is, here, a weekend project for one developer costing a few dollars a month, because the hard parts (storage, hydration, media, moderation, clients) are shared infrastructure. That is the core economic bet of the design: make the parts where diversity matters (ranking, moderation) cheap, and share the parts where scale matters.
Deep Dive: Threat model for a decentralised social protocolShow
A useful exercise in an advanced interview is to list who can attack the system and what each can do.
A malicious PDS. It controls its users' signing keys, so it can forge posts in their names, delete their data or refuse to serve them. It cannot forge posts for users on other hosts, because their keys are elsewhere. Defences: users can hold a higher-priority rotation key and leave within the recovery window, consumers can keep copies of repos and detect history rewrites (a commit that removes records without delete operations shows up as a broken chain), and reputation pressure on hosts. Users who cannot accept this risk self-host.
A malicious relay. It can drop events (censorship by omission), delay them or reorder them across repos. It cannot forge or modify records, because consumers verify signatures and tree proofs. Defences: consumers subscribe to more than one relay, or compare a sample of repos directly against PDSes, and detect gaps through per-repo revision chains.
A malicious App View. It can hide content, rank unfairly, show wrong counts or block accounts from its users. It cannot change records. Defences: the user can switch clients or App Views, and an independent App View can show the difference. This is the same trust relationship as a user has with a search engine.
A malicious feed generator. It learns the viewer's DID for personalised feeds and can rank manipulatively, but cannot inject content the viewer could not otherwise see. Defences: the App View hydrates and filters, and clients disclose which feeds receive identity.
A malicious labeler. It can attach false labels, but only subscribers apply them, and every label is signed with its source, so misuse is attributable. Defences: unsubscribe, reputation, App View limits on which labelers can be set as defaults.
A compromised PLC directory. It cannot forge operations without user rotation keys, but it could refuse new operations, present a stale view or show different histories to different clients (an equivocation attack). Defences: public mirrors of the operation log, auditors that compare log heads across observers (the same idea as certificate transparency logs), and migration of governance to an independent body.
Sybil attackers. Mass account creation for spam or manipulation of counts and feeds. Defences: sign-up verification and rate limits at hosts, host-level reputation at relays, behaviour scoring and spam labelers, and feed generators that weight engagement by account age and trust.
Network attackers. Traffic between services runs over TLS. DNS-based handle verification is only as strong as DNS, so handle resolution should use DNS-over-HTTPS or DNSSEC-validated resolvers where possible, and handles are re-verified periodically. A hijacked domain can move the handle to another DID, but it cannot take over the original DID, so followers, posts and history stay with the rightful owner.
The pattern across all of these: signatures make forgery detectable, portability makes abuse escapable, and multiplicity of operators makes censorship visible. None of them makes abuse impossible, which is why the moderation layers are still needed. See Security Fundamentals for System Design.
Key Takeaways#
- Separate speech from reach: users' data lives in signed repositories on hosts they can leave, while aggregation, ranking and moderation run in replaceable services that read a public stream.
- Identity is a DID, not a server. Handles are domain names verified in both directions, and rotation keys with a recovery window give a credible exit even from a hostile host.
- Signed Merkle Search Tree repositories make data self-certifying: anyone can serve it, and everyone can verify it. History-independent tree shape gives cheap proofs, diffs and sync.
- Relays turn thousands of PDS streams into one verified, sequenced firehose with cursors. Commit inversion lets relays verify without storing full repos, keeping them cheap.
- The App View is a normal large feed backend whose input is an untrusted public stream: idempotent ingestion partitioned by DID, fan-out timelines, hydration, batched counts and heavy caching. It can be rebuilt from the network's data.
- Custom feeds use a skeleton plus hydration split: generators return post URIs, the App View fills in content and enforces moderation, so feeds are cheap and safe.
- Moderation is layered: hosts and relays remove illegal content, App Views enforce policy, and users stack labelers, lists, mutes and reply controls. Blocks are public so every service can enforce them.
- Compared with ActivityPub's push federation, atproto trades many independent full servers for a few large indexers, gaining portable identity, verifiable data and a global view.
- Private data (DMs, mutes, preferences) stays out of the public repo, in PDS-private storage or separate services.
- The main risks are economic and governance-related: if only one company can afford a full App View and runs the identity directory, decentralisation depends on keeping alternatives affordable.