Chapter 7
Sync
The data perimeter of a space is dynamic and may extend past a single PDS to many. Each writer’s records sit in a space repo on that writer’s own PDS, so the perimeter reaches a new PDS whenever an account hosted there writes for the first time. The space host keeps a list of who has written, without the records themselves spec. The space comes together in one place, the copy a syncer builds, and every view your users see is drawn from that copy. Public atproto has relays that gather everyone’s records into one firehose. Spaces have no relay spec, so each app that reads a space does the gathering itself. A syncer uses everything the earlier chapters set up: the credential that lets it in (Chapter 6), the MAC that tells it who answered (Chapter 5), and the commit digest that tells it its copy is complete (Chapter 4).
A syncer learns who has written to the space from the space host and fetches what they wrote from each writer’s own repo host. A syncer’s copy is correct when its set hash matches the one in the repo host’s commit. Notifications only tell the syncer when to check. Missing one delays an update, but the next check still catches up.
Getting a copy of a space#
Your app can’t show anything from a space until it holds its own copy of the records. There’s no relay to subscribe to, so the syncer builds that copy one writer at a time. It asks the space host who has written, then goes to each writer’s PDS for their records. The copy is ready to trust once it matches the commit each repo host hands back, and the sections below cover how a syncer gets there and how it checks.
First contact: the writer set#
The writer set is the list of accounts that have written at least one record into the space under the policy spec. An account the policy allows to write joins it only after its first write. A syncer starting calls listWriters on the space host, with a credential whose audience is the authority:
Reference
listWriters spec#
SpaceNotFoundRepoTakendownRepoDeactivatedThe family app’s call to Marcus’s space host at 15:35, after Ruth’s change and Jake’s removal, so the response shows what a syncer starting at that moment would see.
The response lists the latest update to each repo, ordered by spaceRev ascending. Each entry in repos is a union member carrying a $type, one of two shared definitions in com
Clients should branch on $type for every entry. The response leaves prevSpaceRev unset. A #repoRemoved entry means the authority took that repo out of the writer set (see Removing a writer, below), so stop treating it as part of the space. Pass cursor to resume, and the host returns repos updated after that space revision. limit runs from 1 to 1000 and defaults to 100. The declared errors are SpaceNotFound, RepoTakendown, and RepoDeactivated. The last two mean the authority’s account is taken down or deactivated spec.
Treat the list as the authority’s claim, current as far as its notifications have kept it. Inclusion is necessary but not sufficient: an app may still exclude a listed repo on its own grounds. Each repo’s host is the source of truth for its contents spec. For each listed writer, the syncer resolves the DID document, finds #atproto_pds and #atproto_kem, and pulls the repo.
Incremental sync with listRepoOps#
Reference
listRepoOps spec#
InvalidCursor+ the five repo errors and InvalidSpaceMacThe family app asks Ruth’s PDS what changed since her first RSVP.
Each entry is a com#opEntry spec.
prev: nullis a create.cid: nullis a delete.With both set, it’s an update.
Entries that share a
revcame from one atomic batch.valueholds the record. It’s left out for deletes, whenexcludeValues=true, and when the record has changed since, so any value you get is current for its path.
The request’s since is a TID, and limit runs from 1 to 1000 with a default of 100 spec.
Every page carries the repo’s current commit and its MAC spec. The syncer works through the pages like this:
For each op, it updates its copy of the repo and its running LtHash, subtracting the
prevelement and adding thecidelement.It keeps requesting pages until one comes back without a
cursor. A full page always has acursor, so the last page may be empty.It compares
sha256(state)with the last page’s commitdata. If they match, it’s in sync. If not, the repo has diverged and the syncer recovers withgetRepo.
The op log speeds up transport, but it isn’t committed data. A host may compact it to a backfill window, and it starts fresh after account migration spec. listRepoOps answers RepoNotFound for a repo that has never been written.
In atproto-pds, a request can send both since and cursor. Both apply, and whichever points later in the log decides where the page starts. A resume point older than the retained log returns the remaining ops and the commit. The fold then won’t match, so the syncer falls back to recovery crates.
Full-state recovery with getRepo#
getRepo streams the whole repo as a STAR archive with Content-Type: application/:
Reference
The STAR archive layout spec#
Anatomy of a STAR archive. Read from top to bottom. This is the order the bytes arrive in.
Header, read once at the start.
2A 6C 01 00is the magic: four fixed bytes that open every STAR archive.B4 02is a length, written as a varint. Here it says 308.A2 65 24 74 79 70 65 …is the metadata: 308 bytes of DRISL holding$typeand the commit. The spec caps it at 64 KiB.
Record, opened by a marker byte.
01says a record follows.20is a length. Here it says 32.forumis the path: 32 bytes of UTF-8 in the form.example .post/ 3mfx2k7qd5c2a {collection}/{rkey}. The spec caps it at 4 KiB.5Dis a length. Here it says 93.A3 64 62 6F 64 79 …is the record: 93 bytes of canonical DRISL. The spec caps it at 1 MiB.
Record, the same shape again, as many times as needed.
01says a record follows.20is a length of 32.forumis the path..example .post/ 3mfx2m4wz7s2b 4Ais a length of 74.A3 64 62 6F 64 79 …is the record.
End
00says the archive is complete. The stream stops here.
The metadata, every path, and every record are preceded by their length in bytes, so the reader always knows how far to read next.
An empty repo has no records, so the end marker follows the metadata directly.
The metadata is a DRISL map with $type: "atproto-space-repo" and every commit field. Records come in strict bytewise order of path spec. The commit’s MAC rides in the response’s HTTP signature, not in the metadata.
Reference
Verifying a STAR archive as it streams spec#
Check the metadata’s
$type,ver,repo, andspace.Verify the commit MAC, and check that
Atproto-Space-Commitmatches the metadata.Fold each record’s
{collection}/into a fresh LtHash, refusing any out-of-order or duplicate key.{rkey}/ {cid} After the
0x00end byte, compare the digest todata.On a match, replace the local copy, deleting records absent from the archive.
Refuse the whole archive on any parse error, non-canonical metadata, ordering problem, MAC mismatch, or digest mismatch.
For a copy that has drifted only slightly, getLatestCommit plus listRecords?excludeValues=true gives the path-to-CID map. Diff it against the local copy, then getRecord just the differing paths spec. This trades one large transfer for several small ones.
The read surface#
Every read a repo host offers takes space and repo, and accepts either the repo owner’s OAuth session or a space credential spec. Besides getLatestCommit, listRepoOps, and getRepo, a syncer can fetch one record with getRecord, list records with listRecords, and find and fetch blobs with listBlobs and getBlob. Only the reads that return a commit or a single record carry a MAC: getLatestCommit, getRecord, listRepoOps, and getRepo. Those are the answers a syncer can tie to the host that gave them. Parameters, limits, and errors for each read are in Appendix A.
Staying current#
Once your app has a copy, the question becomes how soon it hears about changes. It can poll on a schedule and live with some delay, or register for notifications and learn about a write moments after it lands. Notifications ask more of the app in return. It needs an endpoint the space host can reach, it has to answer a challenge to confirm the registration, and it has to renew the registration before it lapses.
Write notifications#
Notifications carry no record data spec.
When Ruth writes, her PDS sends comlxm=com). It is skipped when the repo belongs to the authority spec.
Reference
notifyRepoUpdate spec#
SpaceNotFoundFutureRevRuth’s PDS tells Marcus’s space host that her repo advanced.
POST /xrpc/com.atproto.space.notifyRepoUpdate
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJFUz...
Content-Type: application/json
{
"space": "at:space/did:plc:ejjl2znzqp3ci25dqaslpkk2/com.example.familyUpdates/our-family",
"repo": "did:plc:p4256dosynj6j6tkypz2q2l3",
"repoRev": "3n2gtxdkr232p",
"data": {
"$bytes": "eVD7vKgDQrLKfOvN3VZJHYX0HGz158ocKa5oRd3kaYw"
}
}The repo host retries network failures and transient statuses with exponential backoff and stops on permanent errors. The space host rejects notifications for repos not authorized to write, ignores a repoRev that doesn’t increase, and never verifies data. It answers a repoRev too far in the future with FutureRev, and an unknown space with SpaceNotFound spec.
The space host records the repo’s new state, assigns a new space-wide spaceRev, and sends com
Registering for notifications#
A syncer registers by including notify in authorizeSpaceSync spec:
Reference
The notify object spec#
| Field | Meaning |
|---|---|
endpoint | A base HTTPS URL the space host calls XRPC methods against |
token | An opaque secret of at most 512 characters, such as 32 random bytes in base64 |
Use a different token for each space and keep it stable across authorizations. A registration is identified by endpoint and token together; the same pair renews it, a different token creates another registration.
Before creating a new registration, the space host calls com
.atproto on the endpoint with.space .confirmRegistration {space, token, challenge}. The syncer checks that it issued that token for that space and answers{challenge}. OtherwiseauthorizeSpaceSyncfails withRegistrationNotConfirmed.Each half stops something different. The token check protects a real syncer: if someone registers its endpoint with a token it never issued, it declines. The echo protects every other service on the internet. Plenty of URLs answer any POST with a 200, but only an endpoint that read the request can send back a fresh challenge, so a space host only delivers notifications to a service that asked for them. * A registration stays active while the credential from its latest authorization is valid. To receive notifications continuously, keep reauthorizing with the same
notify.
Only a new registration triggers confirmRegistration. Reauthorizing with the same endpoint and token renews the registration without another challenge.
Reference
confirmRegistration spec#
Marcus’s space host checks the family app’s endpoint the first time the app registers.
The family app recognizes the token as the one it issued for this space and echoes the challenge.
The reference PDS sends 16 random bytes in base32 as the challenge and gives the endpoint 10 seconds to answer. atproto-pds sends 32 random bytes in hex and allows the same 10 seconds crates.
Handling an update#
The space host calls the syncer at POST {endpoint}/ with {space, token, update}. These calls carry no service auth. The token in the body is the only thing that authenticates them spec. A token can leak, so the syncer treats each notification as a reason to go and check, and never deletes anything because of a notification alone.
Reference
notifySpaceUpdate spec#
Marcus’s space host tells the family app that Ruth’s repo advanced.
POST /xrpc/com.atproto.space.notifySpaceUpdate
Host: family.example
Content-Type: application/json
{
"space": "at:space/did:plc:ejjl2znzqp3ci25dqaslpkk2/com.example.familyUpdates/our-family",
"token": "xIFHpilmY0Wlfxq62sqovyfp66i08zazz2dgpsT_38E",
"update": {
"$type": "com.atproto.space.defs#repoWrite",
"repo": "did:plc:p4256dosynj6j6tkypz2q2l3",
"repoRev": "3n2gtxdkr232p",
"data": {
"$bytes": "eVD7vKgDQrLKfOvN3VZJHYX0HGz158ocKa5oRd3kaYw"
},
"spaceRev": "3n2gtxdkr222e",
"prevSpaceRev": "3n2gtrxvls22e"
}
}The family app answers with an empty 200 and pulls Ruth’s repo afterward.
Reference
Update types spec#
update.$type | Meaning | Syncer action |
|---|---|---|
com#repoWrite | A repo advanced: repo, repoRev, data, spaceRev, prevSpaceRev? | Pull that repo from its host |
com#repoRemoved | A repo left the writer set: repo, spaceRev, prevSpaceRev? | Stop treating it as part of the space |
com#spaceDeleted | The space was deleted | Reauthorize; drop data only on a SpaceDeleted answer |
com#registrationExpired | The registration lapsed: spaceRev | Reauthorize with notify and catch up |
The syncer’s notifySpaceUpdate handler works in this order:
Check the
tokenand reject one the syncer didn’t issue for that space.Match the update’s
$typein full, and ignore any type it doesn’t recognize.Answer quickly, and do the work afterward.
Delivery of #repoWrite and #repoRemoved is best effort spec. The reference PDS gives each call 10 seconds and never retries it, so a slow handler loses updates. atproto-pds queues each update in its notify outbox and retries a delivery that fails in a way that might clear, which covers a transport error, a timeout, and the statuses 408, 425, 429, and 5xx other than 501 crates.
A #repoWrite says a repo advanced, but the space host never verifies data. If its repoRev is no newer than the syncer’s copy, there is nothing to do. Otherwise the syncer pulls the repo from its own host with listRepoOps from its last repoRev, checks the commit MAC, and folds the ops into its LtHash, as in incremental sync above. The new state counts only once that digest matches the host’s commit. After a successful pull, the syncer saves the notification’s spaceRev as its checkpoint. If prevSpaceRev is present and differs from the last spaceRev it saw, it missed an update and catches up as described below.
A #repoRemoved says the authority took a repo out of the writer set. Removal is destructive, so the syncer confirms it with listWriters before acting, then stops pulling that repo and stops serving its records as part of the space. Nothing changes on the repo’s own host. If its author writes again under the policy, the repo rejoins the writer set and arrives as a #repoWrite.
A #spaceDeleted says the space is gone. The syncer reauthorizes, and deletes its copy only if authorizeSpaceSync answers SpaceDeleted. Deletion notices are retried, so the same one can arrive more than once, and handling it twice must be harmless.
A #registrationExpired arrives in place of the first update after the syncer’s registration lapsed, and carries that update’s spaceRev. Until the syncer reauthorizes, the space host sends it nothing except a deletion notice spec. The syncer reauthorizes with the same notify, then catches up from its checkpoint with listWriters. The host retries expiry and deletion notices with exponential backoff for at least 72 hours, and may drop a registration it still can’t reach spec. In the reference PDS, an expiry notice is skipped if the syncer renewed in the meantime, and a pending deletion notice replaces a pending expiry notice.
A syncer that wants to stop receiving notifications stops reauthorizing and answers the expiry notice with a non-retryable error spec. An authorization that denies the syncer access also withdraws the registration it carries.
atproto-pds keeps one registration per (space, endpoint, token) until its credential expires. It retries expiry and deletion notices after 1 minute, 10 minutes, 1 hour, and 6 hours, then every 12 hours with 50 to 100 percent jitter, for at least 72 hours. It unregisters a syncer that refuses its expiry notice, and keeps a registration in place while the managing app is undecided or the authority is suspended crates.
On the syncer side, atproto-space-client makes one design choice worth copying crates. Rather than generating a random notify token for each space and storing it, notify_token(app_secret, &space) derives the token as an HMAC-SHA256 of the space URI under a single app secret. That gives every space its own token, keeps each token stable across reauthorizations, and lets verify_notify_token recognize an incoming token by recomputing it, so the webhook handler needs no token table. The rest of the client maps directly onto the protocol. SpaceSubscription takes a NotifyRegistration { endpoint, token }, ConfirmRegistrationInput::confirm() answers the registration challenge, and SpaceUpdate models the update union with an Unknown arm, so new update types are ignored rather than rejected. The crate also recommends letting a registration lapse and reauthorizing on #registrationExpired, which costs less than reauthorizing every few minutes to keep it alive.
Catching up#
A syncer detects a missed notification from a gap between prevSpaceRev and the last spaceRev it saw, or by comparing the spaceRev returned by authorizeSpaceSync with its checkpoint. It catches up by calling listWriters with cursor set to that checkpoint spec. If its last seen spaceRev is more than 72 hours old, removed repos it missed may have been collected, so it lists the whole writer set instead and drops any repo that is missing or removed spec.
In atproto-space-client, SpaceCheckpoint::observe tracks revisions, catch_up returns CatchUp { entries, complete } (with complete meaning drop every repo not named), and REMOVAL_RETENTION is 72 hours. pull_repo brings one repo up to date, applying the op log and checking the last page’s commit, falling back to the archive on a mismatch, and treating RepoNotFound as empty. It returns RepoPull::{Changes, Snapshot, Empty} crates.
Removing a writer#
The authority drops an account from the writer set with removeWriter (manage=update, input repo). A removal also happens when removeMembers removes a member or putMembers revokes write access. Removals are sequenced like writes: the space host advances spaceRev, sends #repoRemoved, and lists the repo as #repoRemoved until it writes again. A later authorized write re-adds it with a #repoWrite spec. The repo’s records stay on its host. The space host may drop empty and removed repos from the writer set after at least 72 hours, with no notification spec.
What an app does with its copy of a removed writer’s records is its own decision, and it shapes how the app behaves for its users. The spec asks only that the app stop treating the repo as part of the space. The safest choice is to hard delete that writer’s records once the removal is confirmed. A better alternative is to soft delete them, so they disappear from view at once, and garbage collect them after a set period. While they wait, the app can show a tombstone in their place, so readers can see that something was there even though it is no longer available.
Blobs#
Blobs stay on the author’s repo host, next to the records that reference them, and are fetched separately by CID spec.
STAR archives don’t include blobs, so a syncer that recovers a repo with getRepo still fetches its blobs one at a time spec.
Uploading#
The reference PDS takes space blobs through the same com
In atproto-pds, a blob that no public or space record references is deleted after a grace period, 24 hours by default crates.
Listing blobs#
listBlobs returns the CIDs that a repo’s records in the space reference, each once spec.
Reference
listBlobs spec#
The family app asks Elena’s PDS which blobs her records in the family space reference, with Elena as the credential’s audience.
limit runs from 1 to 1000 and defaults to 500. The reference PDS sorts the CIDs in ascending order and returns a cursor, the last CID on the page, only when the page is full. Instead of listing, a syncer can collect the blob refs from the records it already holds spec.
Fetching a blob#
getBlob takes space, repo, and cid, and returns the blob as originally uploaded spec. The credential signature from the listing works here too, since it covers only the credential and the audience.
Reference
getBlob spec#
BlobNotFound+ the five repo errorsThe family app fetches one of Elena’s two photos.
GET /xrpc/com.atproto.space.getBlob
?space=at:space/did:plc:ejjl2znzqp3ci25dqaslpkk2/com.example.familyUpdates/our-family
&repo=did:plc:53ni6w7okqrxvjxezmopejoo
&cid=bafkreigne4u5q3h5hdcbhusc5osdwybrlkdpdl7222ufbklgo7swix4ore
Authorization: Atproto-Space-Credential eyJhbGciOiJFUzI1NksiLCJ0eXAiOi…
Atproto-Space-Audience: did:plc:53ni6w7okqrxvjxezmopejoo
Signature-Input: sig=("authorization"
"atproto-space-audience");tag="atproto-space-credential"
Signature: sig=:Q/Ya6HSYi45IB5C1Of0GGLVVUAflbU…:HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Length: 1702
Content-Disposition: attachment; filename="bafkreigne4u5q3h5hdcbhusc5osdwybrlkdpdl7222ufbklgo7swix4ore"
Content-Security-Policy: default-src 'none'; sandbox
X-Content-Type-Options: nosniffA blob response carries no MAC. Verify it by hashing the body with SHA-256 and comparing the digest with the CID, which uses the raw codec. The reference PDS serves the body as untrusted content, as the headers show, and an app that re-serves a blob should do the same. It answers BlobNotFound for a missing blob, and also for one the account stores but no record in that space references, so a credential for one space can’t probe for blobs from another.
Why this scales#
Sync is lighter than public sync. The public event stream carries every published record along with the MST nodes and signatures that prove cryptographically that its author wrote it. A space repo has none of that proof material to move. Load grows with the number of syncing applications, not the number of users, since each app pulls each repo once and fans out from its own copy. And because every sync call requires a credential, a host can rate-limit by credential holder spec.
The cost lands on the apps. With no relay to share, every app runs its own syncer, and a first sync touches every writer’s PDS.
A third app adds three pull paths, one per repo host, and a fourth repo host adds two, one per app. A thousand more users of App 1 add none.
Common questions#
- Is registering for notifications required?#
Registering is optional. An app that can tolerate delay can call
listWritersandlistRepoOpson its own schedule. Notifications only make updates arrive sooner.- What if my app misses a notification?#
It catches up. Each notification carries the previous space revision, so a gap is easy to spot, and
listWriterswith your last checkpoint returns everything that changed since. If the checkpoint is more than 72 hours old, list the whole writer set instead.- Does the space host send record data?#
It sends only metadata, such as which repo advanced and its new revision. Records always come from each writer’s own PDS, checked against that PDS’s commit.
Chapter 7 of 11 · AT Protocol Spaces: A Field Guide