Learning the Effem AppView #
A guided tour of effem/AppView for someone who knows Swift well but has not built an HTTP service or used Hummingbird before. It explains what the program is, the handful of server ideas it rests on, how Hummingbird expresses them, how the code is laid out, and how a request and a record each travel through it. Read it next to the code. File paths are relative to effem/AppView.
There is a glossary of AT Protocol and server terms at the end (Appendix A). Skim it first if words like DID, rkey, strongRef, XRPC or CORS are new.
1. What this program is #
In AT Protocol, every user's data lives in their own repository on a PDS (Personal Data Server). The data is a set of typed JSON records in named collections, for example xyz.effem.feed.comment. A user's PDS can answer "what did this user write", but it cannot answer "what did everyone write about this episode". An AppView is the service that can: it listens to the network's event stream, stores the records it cares about in its own database, and serves queries across all users.
This AppView does seven things:
- Indexes twelve
xyz.effem.*collections from Jetstream (a JSON feed of every record change on the network) into Postgres. - Serves read routes under
/xrpc/in the XRPC convention (GET /xrpc/<lexicon id>?params, JSON out). - Serves podcast search and metadata to the Effem apps from its own cache of Podcast Index data, with a server-side API key and spending limits, because the Podcast Index terms forbid shipping the key in a client and forbid handing their responses on as they came.
- Sends push notifications through APNs for replies, mentions and likes.
- Streams live comment updates over a WebSocket, one per open episode view.
- Owns the catalog: canonical episode and podcast records that every social record points at.
- Takes reports and gives moderators the tools to act on them: a private report route, a report queue, takedowns, labels, account bans and account purges.
It replaced the Go service that now lives in effem/AppView-go. The JSON on the wire and the names of the effem_* metrics were kept, and the migration ledger is the Go runner's, continued.
It runs as a resident process: on Railway in production, in Docker or on your Mac otherwise. It keeps a Jetstream connection open for as long as it lives. A second mode, cron, exists for hosts that only run a process while it serves a request; there Jetstream is read in bounded slices triggered by a route. Section 11 covers both. The cron mode is not used in production, but it explains most of the design choices that look unusual at first.
2. From app developer to server developer #
The Swift is the same. What changes is the shape of the program and where state is allowed to live.
There is no main thread and no UI. The process is a tree of long-running tasks. App.main() builds an Application and calls runService(), which does not return until the process receives SIGTERM or SIGINT. Everything that happens after that happens inside tasks the framework spawns: one per request, one per background service.
A request is a value and a response is a value. A route handler is a function (Request, Context) async throws -> some ResponseGenerator. If you squint, it is a SwiftUI body: pure-ish, computes an output from inputs, and anything it needs comes in through its parameters or through the context (which plays the role of @Environment).
Many things happen at once. Each request runs in its own task on a SwiftNIO event loop, and hundreds can be in flight. So every shared object must be Sendable, and shared mutable state goes in an actor (RateLimiter, PodcastIndexGateway, IdentityCache) or behind a Mutex (IngestProgress, ConsumerStatus). You will not find a class with a var and no lock anywhere in this code.
Memory is not where state lives. More than one copy of the process may run against the same database (during every deploy two do, for a few seconds), and a copy can be replaced by a new deploy a minute after it started. Anything that must survive goes in a table. Comments on types like BackfillQueue and IngestLease spell out "this is a table because..." for exactly this reason.
Errors are HTTP responses. A handler throws AppError.notFound("comment not found") and the client receives a 404 with {"error":"NotFound","message":"comment not found"}. The throw site and the wire format are decoupled through a protocol (section 3.7).
Configuration comes from the environment. Not from code, not from a plist. The process reads EFFEM_* variables once at startup, validates them, and refuses to start if they are wrong (section 12). This is called failing fast and is the right behaviour for a server: a misconfigured process should never answer requests.
Observability is part of the product. Every request is logged with structured metadata, counters and gauges are exported for Prometheus, /_live tells the host whether a new copy is fit to take traffic, and /_health tells a monitor whether ingestion is keeping up (section 13).
3. Hummingbird in one sitting #
Hummingbird 2 is a small HTTP framework on SwiftNIO built around Swift structured concurrency. Below are the eight ideas you need, each with the place it shows up in this codebase.
3.1 Application and the service group #
Application is the HTTP server plus a list of background services. It conforms to Service from swift-service-lifecycle, and runService() puts it and every service you added into a ServiceGroup, installs signal handlers, and runs them all concurrently until shutdown.
The whole assembly is in Sources/EffemAppView/Application.swift:
var app = Application(
router: try buildRouter(config: config, components: components, logger: logger),
server: .http1WebSocketUpgrade(webSocketRouter: buildWebSocketRouter(...)),
configuration: .init(address: .hostname(config.bind.host, port: config.bind.port), serverName: "effem-appview"),
logger: logger
)
let gate = StartupGate()
app.addServices(postgres) // the connection pool is itself a Service
app.addServices(components.services.map { GatedService(gate: gate, base: $0) })
app.beforeServerStarts {
let applied = try await migrator.run() // migrations, before the socket opens
try await components.knownDIDs.load()
await gate.open() // now the background loops may start
}
return app
beforeServerStarts is for work that needs a running service (the pool) but must finish before the first request arrives. Migrations are the textbook case.
3.2 Service: the long-lived task protocol #
public protocol Service: Sendable {
func run() async throws
}
That is the whole protocol. The group calls run() on every service at once; returning or throwing ends that service, and by default the group then shuts everything else down. On SIGTERM the group triggers a graceful shutdown, which is a signal distinct from task cancellation; cancelWhenGracefulShutdown { ... } turns it into cancellation of the closure's task. Every loop in this repo follows the same idiom (Indexer/WatchdogService.swift):
func run() async throws {
try await cancelWhenGracefulShutdown {
while !Task.isCancelled {
_ = await sweep()
try await Task.sleep(for: Self.interval)
}
}
}
The pass comes before the sleep on purpose. The watchdog's interval is an hour and the cache cleanup's is a day, and a service that is redeployed more often than that would never reach a pass that waited for its first sleep. When shutdown arrives during the sleep, Task.sleep throws CancellationError, which propagates out of run(). Support/StartupGate.swift has GatedService, which wraps every service for two reasons: it holds the service until the gate opens (otherwise the Jetstream reader would ask for its cursor before the table exists, because the group starts everything simultaneously), and it catches that CancellationError so a clean shutdown is not reported as a failure.
One service uses the library's other tool. ReportWebhook (Indexer/ReportWebhook.swift) reads notices from an AsyncStream with for await, so it has no sleep to cancel. It wraps the loop in withGracefulShutdownHandler, whose handler finishes the stream; the loop then ends by itself and run() returns.
Services in this app: PostgresClient, IdentityRefreshService, PushDispatcherService and ReportWebhook always; JetstreamConsumerService, BackfillWorkerService, WatchdogService, CacheCleanupService only in service mode (section 11).
3.3 Router, groups, RouteCollection #
Router(context: AppRequestContext.self) is a trie router: paths are split on / and matched segment by segment. Routes are added with router.get(path) { request, context in ... } or router.on(path, method:).
router.group("/xrpc") returns a group: a path prefix plus its own middleware stack, applied only to routes registered through the group. Groups nest.
RouteCollection<Context> is a detached list of routes with their own middleware that you build anywhere and attach later with addRoutes. This repo uses it for every route family: each *Routes struct in API/Routes holds its dependencies and exposes var routes: RouteCollection<...>, and Application.swift attaches them. Handlers are plain methods passed with use::
struct CommentRoutes: Sendable {
let database: Database
let hydrator: Hydrator
var routes: RouteCollection<AuthenticatedRequestContext> {
let routes = RouteCollection(context: AuthenticatedRequestContext.self)
routes.get("xyz.effem.feed.getComments", use: comments)
routes.get("xyz.effem.feed.getCommentThread", use: thread)
routes.get("xyz.effem.feed.getBoosts", use: boosts)
return routes
}
@Sendable func comments(_ request: Request, context: AuthenticatedRequestContext) async throws -> JSON<CommentsResponse> { ... }
}
The @Sendable on handlers is required because the router stores and calls them from arbitrary tasks.
3.4 RequestContext: the per-request state, and why it is a generic parameter #
Every router, group, middleware and handler is generic over a Context: RequestContext. A context is a struct created fresh for each request from the connection (channel, logger). It always carries coreContext (logger, matched path parameters, endpoint path) and can carry whatever else you declare. The framework asks it for requestDecoder, responseEncoder and maxUploadSize, with JSON and 2 MB as the defaults.
The reason it is a type parameter rather than a dictionary is the same reason you would not pass [String: Any] through a SwiftUI view hierarchy: the compiler should guarantee that a handler which needs an authenticated principal receives one. API/Context/RequestContexts.swift defines four:
| Context | Adds | Created |
|---|---|---|
AppRequestContext |
identity: Principal?, peerAddress, clientAddress; snake_case coders |
per request, by the framework |
AuthenticatedRequestContext |
non-optional principal, clientAddress, callerDID, viewerDID(in:), budgetKey; 64 KB body limit |
from the parent; the init throws 401/403 if there is no read-scope identity |
AdminRequestContext |
nothing new: the same principal and body limit | from the authenticated one; throws 403 unless admin |
WebSocketAppRequestContext |
webSocket handler slot, identity |
per request on the WebSocket router |
The last three use ChildRequestContext:
public protocol ChildRequestContext<ParentContext>: RequestContext where Source == Never {
associatedtype ParentContext: RequestContext
init(context: ParentContext) throws
}
and router.group("", context: AuthenticatedRequestContext.self) runs that throwing init before any route in the group. That is a typed gate: the 401 and 403 live in one initializer, and no handler under /xrpc ever unwraps an optional principal. In app terms it is a child view that only exists once a non-optional model is available.
A middleware can also change the context for everything downstream by copying it, setting a field, and passing the copy to next. Contexts are structs, so this is ordinary value semantics; ClientAddressMiddleware does exactly this with clientAddress.
3.5 Middleware #
public protocol RouterMiddleware<Context>: MiddlewareProtocol where Input == Request, Output == Response {}
// which means implementing:
func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response
A middleware sees the request before the handler, the response after it, and decides whether to call next at all. Think of ViewModifier composition, or a URLProtocol, but with one function. Order matters: router.addMiddleware { A; B; C } runs A, then B, then C, then the route, then unwinds through C, B and A with the response.
The stack in buildRouter, top to bottom:
CORSAllowlistMiddleware browser cross-origin rules
ClientAddressMiddleware resolves the real client ip behind the proxies
RequestLogMiddleware one line per request: method, path, status, client ip, ms
MetricsMiddleware Hummingbird's own: request counts, durations, errors
/_live, /_health no further middleware
/.well-known/did.json no further middleware
/metrics TokenAuthenticator → RequireScopeMiddleware(.admin)
/_cron/* CronSecretMiddleware
/xrpc/* TokenAuthenticator → RateLimitMiddleware → AuthenticatedRequestContext
user-scoped reads RequireQueryDIDMiddleware (the did parameter must be your own)
xyz.effem.admin.* AdminRequestContext
The order of the first three is a lesson in itself. A middleware only sees what the ones before it put on the context, so ClientAddressMiddleware has to run before RequestLogMiddleware for the log line's ip= field to be the resolved client. With the two the other way round the log printed the socket peer, which behind a proxy is the proxy.
The custom ones are in API/Middleware/Middlewares.swift, with CronSecretMiddleware in its own file next to it, and all are short; read them in order and you will have seen every middleware pattern the framework supports.
3.6 Handlers, decoding and ResponseGenerator #
A handler returns anything conforming to
public protocol ResponseGenerator {
func response(from request: Request, context: some RequestContext) throws -> Response
}
String, ByteBuffer, Response, HTTPResponse.Status and Optional conform out of the box. API/Routes/Responses.swift adds the three this service needs:
JSON<T>encodes with the context's encoder (snake_case keys, which is what EffemKit decodes) and lets a handler set a status or headers..publicCache(seconds:)lets the caller keep a response and.privateCache()keeps it out of every shared cache. Neither setss-maxage: a copy stored by a CDN in front of the service would be served to anyone asking for the same URL, past the token check and the rate limiter.CanonicalJSON<T>encodes with camelCase keys, for AT Protocol records whose bytes must match the CID they were hashed into.RawJSONwrites pre-serialised bytes, for the lexicon files.
Reading input: query parameters are request.uri.queryParameters["did"] (a Substring?, hence the .map(String.init) everywhere), and JSON bodies are try await request.decode(as: T.self, context: context), which uses the context's decoder and enforces maxUploadSize. decodeBody in NotificationRoutes.swift wraps that and gives the two things a client can get wrong their own answers: malformed JSON is 400 InvalidRequest, and a body over the 64 KB limit is 413 PayloadTooLarge. The size error arrives in two forms, so it is caught twice: as Hummingbird's HTTPError with status 413, and as NIO's NIOTooManyBytesError, which is what collecting the body throws once it passes the limit. Without those two catches the catch-all would report an oversized body as malformed JSON.
3.7 Errors #
Throw anything conforming to HTTPResponseError and the framework renders it. Support/AppError.swift is the one error type the routes throw; it carries a status, a short code and a message and renders {"error":"<code>","message":"<text>"}, the Go service's format. Any other error becomes a bare 500 with an empty body.
RequestLogMiddleware catches both kinds, then rethrows. For an HTTPResponseError it logs the usual request line with the error's status. For anything else it is the only place that can say what went wrong, because the caller is told nothing: it logs request failed at error level with an error= field. That field comes from Support/ErrorSummary.swift, which turns an error into one bounded line. A PSQLError gets special care. PostgresNIO replaces its description with a fixed sentence, and its full reflection includes the values bound to the failed query, which can be what a user typed. The summary keeps what the server said (code, SQLSTATE, message, table, column, constraint, routine) and nothing that was bound. It leaves out detail for the same reason: a constraint failure quotes the whole row there. A URLError is cut down to its code (URLError -1001) on the same principle: its reflection quotes the URL it failed on, and a URL can carry what someone searched for. A line looks like this:
error effem-appview: error=postgres error code=server sqlstate=22021 message=invalid byte sequence for encoding "UTF8": 0x00 routine=report_invalid_encoding_int ip=203.0.113.7 method=GET ms=0 path=/xrpc/xyz.effem.actor.getProfile status=500 [EffemAppView] request failed
3.8 HummingbirdAuth #
The auth library is tiny. AuthRequestContext<Identity> is a RequestContext with one extra field, identity: Identity?. AuthenticatorMiddleware is a RouterMiddleware whose authenticate(request:context:) returns an identity (stored on the context), nil (continue anonymously), or throws (reject now). TokenAuthenticator in Middlewares.swift implements it over the static token maps from configuration. Authorization (scopes) is done with the child contexts and RequireScopeMiddleware, not with the library's policy types.
3.9 HummingbirdWebSocket #
WebSockets get their own router, Router<WebSocketAppRequestContext>, handed to the server with .http1WebSocketUpgrade(webSocketRouter:). A route is registered with router.ws(path, shouldUpgrade:onUpgrade:): shouldUpgrade is an ordinary handler that returns .upgrade(headers) or throws, and onUpgrade receives inbound (an async sequence of frames) and outbound (a writer). API/WebSocket/CommentStreamRoute.swift subscribes to the comment bus and writes one text frame per event; a task group with one task draining inbound and one writing outbound ends the stream when either side closes. Before a frame is written it passes StreamVisibility (API/WebSocket/StreamVisibility.swift), which leaves out a new comment from either side of a block with the stream's viewer, the way appendVisibility does for getComments. It reads the viewer's blocks with the first new comment and again once they are a minute old, takes its clock as a parameter, and is handed the lookup as a closure, so its tests need neither a socket nor a database.
3.10 HummingbirdTesting #
try await app.test(.router) { client in
try await client.execute(uri: "/xrpc/xyz.effem.feed.getComments?subject=...", method: .get, headers: [.authorization: "Bearer user-token"]) { response in
#expect(response.status == .ok)
}
}
.router drives the middleware and routes in memory with no socket, which is what every test here uses. .live opens a real port, needed for WebSocket tests.
4. Map of the code #
Sources/App/App.swift executable: logging bootstrap, config providers, run, exit status
Sources/EffemAppView/
Application.swift composition root: Components, buildRouter, buildWebSocketRouter
Config/ AppConfig, DatabaseURL environment → validated value; postgres:// URL → PostgresNIO config
Database/ Database, DBRow, SQLBuilder, Migrator, MigrationFile, SQLStatementSplitter
API/
Context/ Principal, TokenAuthorizer, the four request contexts, WireCoding
Middleware/ the custom middleware, CronSecretMiddleware, IPAddress/CIDR/ClientAddressResolver, RateLimiter
Routes/ one struct per route family, Hydrator, the response types, the did:web documents
WebSocket/ CommentStreamRoute
Indexer/ Indexer (+Collections, Stats, Notifications), RecordFields, Backfill, WatchdogService,
CommentEventBus/Publisher/Listener, AccountStatusStore, AccountPurge, ReportWebhook
Jetstream/ JetstreamIngester, JetstreamConsumerService, IngestRunner, IngestLease, CursorStore,
ReconnectPolicy, IngestProgress
Catalog/ CatalogRecords (rkeys and CIDs), CatalogService (the tables), PodcastIndexResolver
Identity/ IdentityCache (DID → PDS, DID → handle), KnownDIDs
PodcastIndex/ PodcastIndexGateway, PodcastIndexClient, PersonSearch, Budgets, CacheKeys, CacheCleanupService
Push/ APNsClients, PushDispatcherService
Observability/ HealthStatus/LivenessStatus/HealthMonitor, AppMetrics, ConsumerStatus
Support/ AppError, ErrorSummary, QueryValues/Page, TokenBucket, StartupGate/GatedService, withDeadline
Resources/ Migrations/*.sql, Lexicons/xyz/effem/**.json, categories.json
Tests/EffemAppViewTests/ Swift Testing suites (section 14)
The executable target is about thirty lines on purpose: everything testable is in the EffemAppView library, and the tests build routers and components from it directly.
Packages and what each one is for
| Package | Role here |
|---|---|
hummingbird, hummingbird-auth, hummingbird-websocket |
server, router, middleware, auth context, WebSocket router, testing |
swift-websocket (WSClient) |
the WebSocket client that reads Jetstream |
postgres-nio |
Postgres driver and connection pool |
swift-service-lifecycle |
Service, ServiceGroup, graceful shutdown |
swift-configuration |
reads flags, environment and .env into one reader |
swift-log, swift-metrics, swift-prometheus |
logging API, metrics API, Prometheus exporter |
APNSwift |
push delivery with JWT auth from the .p8 key |
CBOR, swift-crypto |
DAG-CBOR encoding and SHA-256 for CIDs and record keys |
CoreATProtocol (yours) |
DID resolution, AT URI/rkey/CID syntax, Jetstream frame types, repo reads |
PodcastIndexKit (yours) |
the Podcast Index HTTP client |
EffemKit → EffemModels (yours) |
the wire types shared with the iOS and web clients |
Package.swift names the three SparrowTek packages by URL on their main branches, and Package.resolved pins the revisions; the local path: forms sit commented out next to them. The image Railway builds resolves the pinned revisions from the remotes, so push a package change and update the pin before deploying code that needs it. scripts/linux-test.sh goes the other way: it builds a copy of the manifest that points at the local checkouts, so unpushed package changes can be tested on Linux first.
Where to start reading: Application.swift (the whole shape of the service in under 300 lines), then RequestContexts.swift, Middlewares.swift, Responses.swift and AppError.swift (the request pipeline), then SocialRoutes.swift (the simplest handlers), then Database.swift.
5. Life of a request #
Follow GET /xrpc/xyz.effem.feed.getComments?subject=at://did:web:catalog.effem.xyz/xyz.effem.feed.episode/abc&limit=20 with Authorization: Bearer <token>, sent by the iOS app through Railway's edge.
- Accept and parse. NIO accepts the connection and parses HTTP/1.1. Hummingbird creates an
AppRequestContext; its init records the socket peer's address, which here is Railway's edge. - Global middleware, inbound.
CORSAllowlistMiddlewaresees noOriginheader (native clients do not send one) and passes through.ClientAddressMiddlewarefinds the peer inside a trusted range, reads the caller's address from the header the edge set (X-Real-IP), and stores it asclientAddress; section 8 has the full rule.RequestLogMiddlewarestarts a clock.MetricsMiddlewareincrements the active-request meter. - Route match. The trie finds
/xrpc/xyz.effem.feed.getCommentsfor GET. - Group middleware.
TokenAuthenticatorreads the bearer token, finds it in the read-token map, and setscontext.identity = Principal(subject: "*", scopes: [.read]): the app ships one token for everyone, a service token with no user behind it.RateLimitMiddlewarepicks the key (the client address, because every copy of the app presents that same token), takes a token from that bucket, and would answer 429 withRetry-After: 1if the bucket were empty. - Context transform.
AuthenticatedRequestContext(context:)succeeds: there is an identity and it has read scope. - Handler.
CommentRoutes.commentsparsessubject, clampslimit, asks the context who is looking (context.viewerDID(in: request)), and builds the query withSQLBuilder: subject,removed = FALSE, an optional cursor (rkey < ?), andappendVisibility, which hides rows from accounts the relay marked inactive or an operator banned, and from either side of a block with the viewer. It fetcheslimit + 1rows soPagecan tell whether there is a next page and derive the cursor from the last kept row. - Hydration.
Hydrator.authorsjoinsprofilesanddid_pdsfor the distinct DIDs (handle, display name, avatar URL built from the PDS endpoint and blob CID).Hydrator.likescounts likes per comment, leaving out likes from hidden accounts, and finds the viewer's own like.Hydrator.labelsloads labels from the service's labeler plus any labelers the viewer subscribed to; rows with a hide label are dropped. The viewer comes fromAuthenticatedRequestContext.viewerDID(in:). A token whose subject is a DID is its own viewer. The app's shared token has no user behind it, so the app names the viewer in theviewerquery parameter, and the service takes that DID as given as long as it has the form of a DID. With no viewer, the block filter, the viewer's own like and the viewer's labelers are skipped. Section 8 says why a claimed viewer is acceptable here. - Response.
JSON(CommentsResponse(comments:cursor:))is encoded by the context's snake_case encoder into aResponsewithContent-Type: application/json. - Unwind.
RequestLogMiddlewarelogsmethod path status ip ms;MetricsMiddlewarerecords the duration.
The error path is the same pipeline in reverse: a malformed cursor on an admin route makes the handler throw AppError.invalidRequest("cursor must be a positive integer"), which renders as a 400 with the JSON body, and the log line records 400.
6. Life of a record #
Follow a comment from the app to a push notification and a live frame. The app writes an xyz.effem.feed.comment record to the user's PDS; the PDS tells the relay; Jetstream turns the commit into one JSON event. From there:
Jetstream ──ws──▶ JetstreamIngester ──▶ Indexer.index ──▶ Collections.indexComment
│ upsert comments, refresh episode_stats
├─▶ pg_notify('effem_comments') ──▶ CommentEventListener ──▶ CommentEventBus ──▶ WebSocket frame
└─▶ notify(): notifications + push_outbox ──▶ PushDispatcherService ──▶ APNs
- Connect.
JetstreamIngester.connectOnceloads the saved cursor, builds the subscription URL (the twelve collections, all four event kinds, the cursor), and opens the socket withWebSocketClient.connect. Inside the connection it runs three tasks in a group: one reads frames, one saves the cursor every second and renews the lease every five, one waits for the deadline (cron mode only). Whichever finishes first cancels the others. - Decode.
handle(frameText:)decodes aJetstreamFramefrom CoreATProtocol. Commits for other collections never arrive (the subscription filters them), but account, identity and sync events arrive for the whole network and are dropped unless the DID is one this service has records for (KnownDIDs). - Validate and dispatch.
Indexer.indexchecks the DID, record key and CID syntax, queues the DID for an identity refresh, marks it known, looks the account up inaccount_status, and switches on the collection. A record from a banned account carries on with its source changed to.suppressed: it is indexed like any other, so lifting the ban brings it back, but step 5 skips it. - Index.
indexCommentvalidates the strongRef subject, the text length, the datetime, the optional reply refs and facets, and upserts intocomments. The upsert returns(xmax = 0) AS inserted, a Postgres trick that says whether the row was new.refreshEpisodeStatsthen recomputes every counter for that episode from the source tables rather than incrementing, so a replayed or out-of-order event cannot drift them. The counters inIndexer/Stats.swiftcount what a reader can see: removed comments and recommendations are left out, and so is every row from an inactive or banned account. - Fan out, live events only. If the row was new and the source was
.live(not a backfill, a watchdog retry or a banned account's record):CommentEventPublisher.publishsendspg_notifywith the subject and the comment's URI;notifyReplyfinds the parent comment's author andnotifyinserts anotificationsrow and apush_outboxrow in one transaction, with a unique index making a replay a no-op; mentions in facets do the same with reasonmention. - Deliver to streams. On every instance that has an open stream for that episode,
CommentEventListenerholds one dedicatedLISTENconnection. It decodes the payload, reads the comment back from the table (the payload carries identifiers only, to stay under the 8000-byte notification limit and to send exactly what the read routes would), hydrates the author, andCommentEventBus.broadcastyields it into each subscriber'sAsyncStream.CommentStreamRoutewrites it as a text frame. - Deliver to devices.
PushDispatcherService.drainOnceruns every five seconds (and at the end of every cron ingest run): it reads unsentpush_outboxrows, finds the recipient's device tokens, sends through APNSwift, marks rows sent or failed, and stamps tokens APNs reports as dead so they are never tried again. - Failure. Anything thrown in step 4 lands in
indexer_errorsthroughrecordError.WatchdogServicere-fetches such records from the user's PDS when the service starts and then hourly, up to five attempts for each record. The usual cause is ordering: a threadgate that arrives before its comment is rejected, then succeeds once the comment is indexed.
A delete follows the same path through Indexer.delete: the row goes, the stats are recomputed, and a deleted frame is published. delete makes the same substitution as index for a banned account, so there the row still goes and no frame is sent. A backfill (BackfillRunner) pages through a user's repo with listRecords and indexes each record with source: .backfill, which writes rows and stats but never notifies anyone. A backfill only adds and updates: it does not remove rows for records that were deleted while nobody was listening.
An #account event is the relay's verdict on a whole account rather than on one record. For an account this service knows, AccountStatusStore.upsert records it, and an inactive account is hidden from reads from then on. The counters leave hidden accounts out, so the same event calls Indexer.refreshStats(touchedBy:), which finds every podcast and episode the account subscribed to, commented on, recommended, bookmarked, boosted or liked a comment under, and recomputes each one's counters. A ban and an unban make the same call. One state goes further. active=false with the status deleted means the account is gone for good, so AccountPurge (Indexer/AccountPurge.swift) removes what the service holds about it: the rows indexed from its records, its profile and identity cache entry, the notifications to and from it, its notification settings and device tokens. It then recomputes the counters those rows fed. A deactivated, suspended or taken-down account can come back, so it is only hidden. The purge keeps the account_status row, so the account stays hidden if its records are ever replayed, and it keeps reports (the ones the account filed and the ones about it), labels and the audit log, which are the moderation history.
One thing a user sends is not a record at all. A report goes straight to POST /xrpc/xyz.effem.moderation.createReport, lands in the reports table with source = 'private', and never touches the reporter's repository. Section 8 follows it.
7. Postgres from Swift #
PostgresNIO is the only database layer; there is no ORM. Four things to know, then the patterns you will recognise in the queries.
PostgresQuery is string interpolation with bind parameters. "SELECT * FROM comments WHERE did = \(did)" does not splice did into the text. Each \(value) becomes a numbered $n placeholder and the value travels separately, so SQL injection is impossible by construction. The one escape hatch is \(unescaped: text), which does splice raw SQL; it is used for column lists such as CommentRow.columns and must only ever receive constants.
One statement per query. The extended protocol that PostgresNIO uses allows exactly one statement per query, which is why Database/SQLStatementSplitter.swift exists: migration files hold many statements and have to be split, understanding comments, quoted strings and $tag$ quoting.
Database is the one door. rows, first, execute, scalar and withTransaction wrap PostgresClient. DBRow reads columns by name with a typed decode and names the missing column in its error instead of crashing. Inside withTransaction you use the raw connection.query and must iterate the returned sequence (for try await _ in ...) or the statement does not run.
SQLBuilder is for optional filters. When the WHERE clause depends on which query parameters were sent, append("?", value) numbers the binds for you and query produces a PostgresQuery(unsafeSQL:binds:). The "unsafe" refers to the SQL text being yours; the values are still bound.
Patterns worth recognising:
| Pattern | Where | What it buys |
|---|---|---|
INSERT … ON CONFLICT (did, rkey) DO UPDATE SET col = EXCLUDED.col |
every indexer write | a record delivered twice lands once (Jetstream is at-least-once, backfills re-read whole repos) |
RETURNING (xmax = 0) AS inserted |
comments, comment likes, reports indexed from records | whether the upsert inserted or updated, so notifications and the report notice fire only for new rows |
single-row tables with CHECK (id = 1) |
jetstream_cursor, ingest_lease, pi_service_budget |
one well-known row for process-wide state |
UPDATE … WHERE did = (SELECT … FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING |
BackfillQueue.claimNext |
a work queue where two workers never take the same job |
refill and charge in one statement with a WHERE guard |
DatabaseServiceBudget.allow |
a token bucket shared by every instance with no lost update |
conditional upsert with RETURNING, success = a row came back |
IngestLease.acquire, ModerationRoutes.createReport, AccountStatusStore.ban |
a lease with expiry and no advisory lock to leak; a report that is stored once and reopened only when it was closed; a ban that says whether it changed anything |
WITH gone AS (DELETE … RETURNING subject_uri) SELECT … |
AccountPurge.purge |
deletes from several tables in one statement and returns the subjects whose counters must be recomputed |
pg_notify / connection.listen(on:) |
comment events | cross-process pub/sub without another service |
col = ANY(\(array)) |
hydration | bind a Swift array as a Postgres array for IN lists |
col::text AS col and \(json)::jsonb |
JSON columns | read JSONB as text and decode in Swift; write text and cast |
make_interval(secs => \(seconds)) |
leases, queues, watchdog | bind a duration as a number instead of building interval text |
Record keys carry part of the uniqueness. The record tables are unique on (did, rkey), so what a key is decides what counts as the same record. Comments, recommendations, lists, bookmarks and boosts use a TID, which is a timestamp, and every write is a new record. Four kinds of record are meant to exist once per subject, and their lexicons ("key": "any") say how the key is derived. A subscription's key is the record key of the podcast's catalog record. A comment like's key is the first 16 bytes of the SHA-256 of the liked comment's AT URI, in base32, and a block's key is the same digest of the blocked DID. An episode state's key is derived from the episode's catalog key. A client writes these with putRecord, so subscribing twice overwrites one record instead of creating a second. The indexer does not check the shape of a key; it upserts whatever valid key arrives. comment_likes and blocks also have a unique index on the pair itself, (did, subject_uri) and (did, subject_did), so a second record for the same pair under another key is refused and becomes a row in indexer_errors. subscriptions has no such index: there the key is the only guard, and the same account subscribing under two different keys is counted twice (section 16). One read had to change with the keys. Every subscription to one podcast now has the same key, so getSubscribers pages by DID (did > cursor ORDER BY did ASC), and its cursor is the last DID of the page. The other lists still page by key, highest key first. That works wherever the keys differ: inside one account (getSubscriptions, getBlocks, getEpisodeStates), and across accounts for records keyed by TID (getComments, getRecommendations, getBoosts), where two accounts sharing a key is next to impossible. Where the key is derived, the order is no longer the order in time.
Timestamps come in two kinds. created_at and updated_at on record tables are VARCHAR holding the record's own RFC 3339 string, because that is the user's claim and it is compared as text; indexed_at, resolved_at, expires_at and the like are TIMESTAMPTZ, server time. ATDatetimeFormatting exists to produce the same text the Go service produced.
Migrations run on every start, inside beforeServerStarts. Migrator keeps a schema_migrations table with version, file name, SHA-256 of the file and applied time; takes pg_advisory_lock(838001447) so two instances never migrate at once; refuses to start if an applied file's checksum changed (edit a migration that already ran and the service will not boot, by design: write a new one); and honours a -- migrate:no-transaction directive for CREATE INDEX CONCURRENTLY, which Postgres forbids inside a transaction. The bookkeeping matches the Go runner byte for byte, including the checksum of 0001_initial.sql, so a database the Go service migrated would come up with only 0011, 0012 and 0013 to apply. There is a test for that checksum. The checksum covers the whole file, comments included, so even a typo fix in an applied migration stops the service from starting.
Read the thirteen files in Resources/Migrations in order: they are the history of the data model and the comments explain each change. The newest, 0013_private_reports_bans.sql, adds reports.source and the ban columns on account_status.
8. Who is calling: auth, scopes, rate limits, addresses, CORS, and moderation #
Principal. API/Context/Principal.swift. A caller is a subject (a DID, or * for a service token with no user behind it) and a set of scopes (read, admin). Tokens are static token=subject maps from configuration; there is no OAuth yet. DIDs listed in EFFEM_ADMIN_DIDS promote a read token to admin so a moderator keeps their normal app token. TokenAuthenticator accepts the token as Authorization: Bearer or X-API-Key.
The iOS app ships one read token for everyone, and its subject is *. It has to be written <token>=*. A subject such as did:plc:* is not a wildcard: it would be taken for one user's DID, and RequireQueryDIDMiddleware would answer 403 on every per-user route. The app's token must never be listed as an admin token, because everyone who has the app has the token.
The viewer. Some reads depend on who is looking: which comments the reader liked, whose content they blocked, which labelers their profile subscribes to. Viewer.did(of:in:) answers that in one place, and AuthenticatedRequestContext.viewerDID(in:) is the read routes' way to it. A token whose subject is a DID is its own viewer, and nothing in the request can change that. The app's shared token has no user behind it, so the app passes viewer=<DID>, and the service takes it as given once DID.isValid accepts its form; anything else counts as no viewer. getComments, getCommentThread, getRecommendations, getSubscribers and getBoosts call it, and so does the comment stream, so that a comment the list leaves out for a viewer cannot reach the same viewer live. Taking a claimed DID is acceptable here for one reason: what it unlocks is public already. Likes and blocks are public records in the claimed account's repository, so a caller who lies about the viewer learns nothing the network would not tell them. That reasoning does not stretch to private data or to writes, which is why the notification routes insist on a token with a DID. An admin token whose subject is a DID is a viewer as well: a moderator who reads comments with it sees them through their own blocks. admin.getReportedContent applies no filter and is the route for looking at reported content.
Scopes. Everything under /xrpc needs read. /metrics and xyz.effem.admin.* need admin, enforced by RequireScopeMiddleware and AdminRequestContext. RequireQueryDIDMiddleware wraps the user-scoped reads (subscriptions, lists, bookmarks, episode states, blocks): the did query parameter must equal the caller's own DID unless the caller is an admin or a service token. The routes that act on the caller's own account (notifications, device tokens, backfillSelf) need a DID and answer 401 to a service token, which is why server push waits for per-user authentication.
Rate limiting. Support/TokenBucket.swift is the algorithm: a bucket holds up to burst tokens and refills at rate per second; a request takes one or is refused. It is a value type and lives inside the RateLimiter actor, keyed per caller, with two tiers: by client address for read callers (they all share one app token, so the token is not a useful key) and by subject for admin tokens. Refusals are 429 with Retry-After: 1 and a metric. Buckets unseen for five minutes are swept. This limiter is per instance, which is fine for its purpose (stopping one client from hammering one process). ModerationRoutes owns a second, much smaller RateLimiter for reports alone (below).
Client address. Behind a proxy the socket peer is the proxy, and the caller is named in a header the proxy wrote. Any client can send such a header too, so the question is always which header to believe, and when. ClientAddressResolver in API/Middleware/ClientAddress.swift believes a header only when the socket peer is inside a trusted range: loopback, link-local and private ranges always, plus EFFEM_TRUSTED_PROXY_CIDRS. An untrusted peer is the client whatever any header says, so a forged header that reaches the server directly is ignored. With a trusted peer there are two kinds of header:
X-Forwarded-Foris a list every hop appends to, and the caller can start it with anything. The resolver walks it from the right, skips every address inside a trusted range, and takes the first one that is not.- Some edges instead set one header to the caller's address and replace whatever the caller sent under that name. When
EFFEM_CLIENT_ADDRESS_HEADERnames such a header and the request carries it, its value is the client and the list is not consulted.
On Railway both settings are used: EFFEM_TRUSTED_PROXY_CIDRS=100.64.0.0/10 and EFFEM_CLIENT_ADDRESS_HEADER=X-Real-IP. This is what was measured against the deployed service on 2026-11-09:
- Railway's edge connects to the service from
100.64.0.0/10and setsX-Real-IPto the caller's address. It replaces anX-Real-IPthe caller sent. A forgedX-Real-IP,X-Forwarded-For,CF-Connecting-IPorTrue-Client-IPsent straight to the*.up.railway.appdomain did not change the resolved address. appview.effem.xyzis proxied by Cloudflare. Railway detects Cloudflare in front of a custom domain and still reports the real caller inX-Real-IP(IPv4 and IPv6 both checked), and forged headers sent through Cloudflare did not change it either. So the Cloudflare proxy can stay on.- Requests that do not come through the edge (Railway's deploy health check) carry no
X-Real-IP; the resolver then falls back to the forwarded list and finally the peer.
IPAddress and CIDR are hand-written parsers because Foundation has none that is portable to Linux. The rate limiter, the Podcast Index budget and the request log all use this address, so getting it right is not cosmetic: with the edge's range left untrusted, every caller would look like the edge and share one bucket.
CORS. Only browsers care (the web player). CORSAllowlistMiddleware echoes the Origin back if it is in the allowlist, answers preflight OPTIONS with 204, and otherwise adds nothing. A * origin is refused at configuration time.
Reports. API/Routes/ModerationRoutes.swift. POST xyz.effem.moderation.createReport takes {did, subject, reason_type, reason} and stores a row in reports with source = 'private'. Nothing is written to the reporter's repository, and only the admin routes can read the row. Who is reporting follows from the token (reporter(claimed:principal:)): a user's token speaks for its own DID and nothing else; the app's shared token has no user behind it, so the DID in the body is taken as given, checked for form and not for truth, until the service can authenticate individual users. The subject is the AT-URI of a record or the DID of an account. The row's key is private- plus a digest of the subject, so one account reporting the same thing twice lands on one row: a repeat of a pending report changes nothing, and a repeat of a closed one opens it again, because the reporter is saying it happened again. The route's own limiter allows ten reports at once and then one every thirty seconds, per reporter and per client address. A banned account's reports are accepted and dropped, so the answer does not tell it that it was banned. Reports published as xyz.effem.moderation.report records are still indexed, with source = 'record', for clients that write them.
The report webhook. Indexer/ReportWebhook.swift. A stored report is no use if nobody hears about it. When EFFEM_REPORT_WEBHOOK_URL is set, each new report from either source is queued as a Notice and posted as {"text", "content", "report": {"id", "subject", "reason_type", "source"}}; text is the field a Slack incoming webhook reads and content the one Discord reads. The notice never carries the reporter or their free text, so the channel it lands in does not become a second copy of the report queue. Three details are worth copying. enqueue returns at once and a service posts the notices one at a time, so a slow or failing webhook never holds up the request or the indexer that raised one. The buffer keeps the newest hundred, so a flood cannot grow memory. And a failure is logged with the report number and the status or error code only, because the URL is a secret and an error's description can quote it.
Bans. Indexer/AccountStatusStore.swift and the routes xyz.effem.admin.banAccount, unbanAccount and listBans. account_status already held the relay's verdict on an account (active, from #account events). A ban is a second flag on the same row, kept apart so that the relay's events cannot overwrite it. hiddenAccountsSQL is the one subquery for "inactive or banned", and it is part of everything other people read. SQLFragments.visibility adds it, together with the viewer's blocks, to every read that calls appendVisibility: comments, thread roots, boosts, recommendations and the subscriber list. The queries that are not built with SQLBuilder interpolate it themselves: thread replies and the reply count, the subscriber count, getList by URI and the like counts in Hydrator.likes; getPopular puts it in the text its builder starts from. A profile read asks isHidden and answers 404. The stored counters follow the same rule, because Indexer/Stats.swift counts visible rows only, so banAccount and unbanAccount end with refreshStats(touchedBy:) whenever the flag really changed. On the write side Indexer.index and Indexer.delete turn a banned account's events into .suppressed ones (section 6): its records are stored and removed as usual and announce nothing. Lifting the ban is one UPDATE and one recount, and everything reappears.
One group of reads is not filtered: the ones that take an account's own DID (getSubscriptions, getLists, getBookmarks, getEpisodeStates, getBlocks). The reason is plain. The service cannot tell who is asking. Everyone presents the same app token, so a request for a banned account's subscriptions looks the same whether that account's own app sent it or a stranger did. Those reads answer for any DID until the service authenticates users.
Takedowns and labels are the finer tools next to a ban: removeContent sets removed on one comment or recommendation and recounts that episode with refreshEpisodeStats, and a !hide label from the service's labeler drops one comment from the read routes.
Purges. A ban hides and keeps; a purge deletes. xyz.effem.admin.purgeAccount runs the same AccountPurge the relay's deleted event triggers (section 6), for a deletion request that arrives by email. It answers with the number of rows removed and writes a purge_account audit row. The purge cannot reach the account's repository: the records there are the account's own, and if they are still there a later backfill indexes them again. So the person deletes their Effem data in the app first, and the purge then removes what is left on this side.
9. Podcast Index: the cache and the budgets #
The Podcast Index terms require the key to stay on the server, forbid re-serving raw responses, and set rate limits. So this service is Effem's own backend and nothing more: it answers the Effem apps from its own cache, rebuilds every response as its own types, limits each caller, and keeps a ceiling on what the whole service sends upstream. PodcastIndex/ is where that lives, and it is also the most instructive concurrency code in the repo.
Every call the routes make goes through PodcastIndexGateway.fetch(endpoint:key:ttl:client:upstream:):
- Cache. Look up
pi_cacheby key; a fresh row is returned at once. - Single-flight. If another task is already fetching the same key, await its
Taskinstead of calling upstream twice. (inFlight: [String: Task<Data, Error>]inside the actor.) The table is looked at twice, here and again after step 3, and the second look is the lesson. An actor runs one piece of code at a time, but only between suspension points. Charging the budget is a database round trip, and while it is in flight the actor serves other callers, so two callers for the same uncached key can both find nothing in flight at this step. Whichever returns from the budget second finds the first one's task in the table and joins it. The test "Callers asking for the same thing at the same moment share one upstream request" starts eight callers at once and counts one upstream call. A caller that joined waits injoin. When the shared request fails, it gets what the caller that started the request gets: the stale copy if there is one, otherwise the sameGatewayError.upstreamwith the same summary, and never the upstream error itself. Only the caller that started the request logs the failure and counts it. - Budgets.
UpstreamBudget.chargetakes a token from the caller's bucket (in memory, per instance, keyed by client address) and then from the service-wide bucket, which is thepi_service_budgetrow so every instance draws from one allowance. Over budget: serve the expired cached copy if there is one, otherwise 429 for the client tier or 503 for the service tier. A database error fails closed, because the ceiling is a promise to Podcast Index. - Upstream. Call PodcastIndexKit, store the bytes with the TTL, return them. If upstream fails, serve the stale copy or answer 502. The failure is logged by kind only, through
PodcastIndexGateway.summary: aURLError's code, or the error's type and case with a short value such as the HTTP status. The HTTP layer's own errors describe the request they belong to, and a search request's URL carries what the person searched for, so the raw error is never logged or passed on.
Each step has a metric (effem_pi_cache_hits_total, ..._misses_total, ..._upstream_calls_total, ..._budget_rejections_total, ..._stale_served_total).
"Not found" is an answer, not a failure. One call can come back saying that Podcast Index holds no such thing: a podcast asked for by the address of its feed, which the app offers to someone who has the feed and cannot find the show (xyz.effem.podcast.getPodcast?feedUrl=). Podcast Index says so in two ways, a 400 and a 200 whose feed is empty; by the time it left step 4 the first would look like any other failed call and the second would have been stored. So the upstream closure in PodcastIndexClient.podcast(feedURL:client:) turns both into GatewayError.notFound, except a 400 that reads Invalid parameters., which means the request itself was wrong and stays a failure. The gateway treats notFound apart: it is passed on as it is, to the caller that started the request and to the ones that joined it; no expired copy stands in for it, and one that exists is deleted, since it is no longer true; and nothing is stored, so the next request asks again and a feed that was added in the meantime is found. The route answers 404, the one status the app reads as "not in the index, offer to get it added"; every real failure stays a 502. The address itself is a FeedAddress (EffemKit's EffemModels), which brings it to the one spelling Podcast Index compares against and refuses text that is no address before any call is made, an address with a password in it included. Only an address that was found is ever cached, which keeps the addresses of private feeds, pasted in the hope of finding them, out of pi_cache, and its key is a SHA-256 digest of the address: cache_key holds 512 characters and an address can run to 2,048 bytes.
Many feeds in one request. xyz.effem.podcast.getNewEpisodes answers what up to 200 shows have published since a moment in time, so that an app refreshes a library with one request instead of one per subscription. It goes through a second door, PodcastIndexGateway.fetchEach(endpoint:keys:ttl:client:plan:upstream:), which is fetch for many keys: each feed has its own row in pi_cache (episodes:since:<start of day>:<feed>, fifteen minutes), and the feeds without a fresh row go to Podcast Index ten to a call, six calls side by side, each call charged to the budgets, all of them cancelled eight seconds in (BatchPlan.newEpisodes). The numbers come from measuring Podcast Index on 2026-11-24: it takes a fifth to a third of a second over each feed in a call, one after the other, unless it was asked about that feed within the last few minutes, and a call of its own is cut off after ten seconds. fetchEach differs from fetch in three ways, and its comment says why. Feeds whose call is not back in time are named in the response's unanswered instead of failing the request; the app asks again, and the second question is quick because the first one started the work. An expired row never stands in for an answer, because the app keeps track of when it last asked and an old answer handed over as today's would lose it whatever came in between. And callers do not share calls in flight. The moment asked from is moved back to the start of its day (NewEpisodesWindow), which is what lets callers who last looked at different times share rows; asked from more than 30 days back, the answer starts 30 days back and says so in since. Podcast Index's own answer is cut at 1000 episodes across all the feeds in a call, and not at the oldest ones, so a full answer is thrown away and asked for again in halves (BatchAnswer.tooMuch). PodcastIndexClient.episodeLists regroups Podcast Index's JSON by feed without decoding it, so each stored row reads like an answer about one feed. CacheCleanupService deletes these rows an hour after they expire, since nothing serves them.
PodcastIndexClient lists the ten calls and their cache keys and TTLs (CacheKeys: searches one hour, a podcast a day, episode lists fifteen minutes). Searches are normalised (trimmed, lowercased, spaces collapsed) and episode lists always fetch 100 upstream and trim locally, so one cached copy serves every page size.
PodcastRoutes never returns Podcast Index's JSON as it came: each item is rebuilt into Effem's own PodcastResult or EpisodeResult with the social counts overlaid by SocialCounts, which joins the catalog's cross-reference IDs to the stats tables. A search by person (searchType=person) is the odd one out. Podcast Index answers it with episodes, not shows, so PodcastIndex/PersonSearch.swift folds the episodes into the shows they belong to, in the order Podcast Index ranked them, and the route returns shows like every other search. The category list is served from the bundled categories.json. CacheCleanupService deletes rows that expired more than thirty days ago, once when the service starts and then once a day, so stale copies stay useful for a while and then stop taking disk.
These routes are only registered when EFFEM_AUTH_REQUIRED is true. With auth off, anyone could reach Podcast Index through them, so buildRouter leaves them out and logs a warning instead.
10. The catalog #
Social records need something stable to point at. Podcast Index integer IDs are a third party's and can be reissued, so instead every subject-bearing record (comment, subscription, bookmark, boost, recommendation, episode state) carries a strongRef {uri, cid} to a catalog record under the catalog DID (did:web:catalog.effem.xyz).
Catalog/CatalogRecords.swift makes those references deterministic:
- The record key is
base32(sha256("episode" + 0 + podcastGuid + 0 + episodeGuid))[0..<16](and"podcast" + 0 + podcastGuidfor podcasts), so two clients that resolve the same episode on different days produce the same AT URI without coordinating. - The CID is the hash of the record's canonical DAG-CBOR encoding, computed by CoreATProtocol over the exact field set the Go service used (empty optionals omitted,
$typefirst).
CatalogService is the table side: lookups by URI, by GUIDs, by Podcast Index IDs, and ensureEpisode / ensurePodcast, which upsert on the GUIDs so writing the same episode twice is a no-op. CatalogRoutes.resolveEpisode is the path the app takes: IDs it got from a Podcast Index search, a catalog lookup, and on a miss PodcastIndexResolver fetches the episode through the gateway and the catalog stores it. getEpisodeRecord serves the record with CanonicalJSON because the bytes have to match what the CID was computed over.
Tests/EffemAppViewTests/Fixtures/catalog-cids.json holds records with the CIDs and record keys the Go service produced, and CatalogRecordTests checks the Swift code reproduces them. If that test ever fails, the record keys or CIDs this service computes have changed, and the references users have already written would no longer match the records they point at, so treat it as the most important test in the repo.
The identities behind it. The catalog DID is did:web:catalog.effem.xyz and the service's labels are stamped did:web:labeler.effem.xyz (EFFEM_CATALOG_DID, EFFEM_LABELER_DID). Every record a user writes names the catalog DID, so it cannot change once real users have written records. A did:web resolves to https://<host>/.well-known/did.json, and API/Routes/WellKnownRoutes.swift serves that path. DIDDocuments builds one document per configured did:web and answers a request only when its Host is that identity's host name; a default port the client spelled out is ignored, and any other host gets a 404. The documents are deliberately bare, @context and id and nothing else: neither identity has a repository on a PDS or a signing key, and a document should not claim either. A did:web that carries a path lives at <path>/did.json, not under .well-known, so it is skipped. For the two DIDs to resolve, their host names have to reach this service with the name intact; as of 2026-11-09 neither name exists in DNS.
11. Two ingest modes #
How records get from Jetstream into the database is a setting, EFFEM_INGEST_MODE. The default, service, is how the service runs in production on Railway: one process that stays up and reads the stream for as long as it lives. cron is opt-in, for a host that only runs a process while it serves a request; no platform selects it automatically.
service |
cron |
|
|---|---|---|
| Jetstream reader | JetstreamConsumerService runs for the life of the process |
GET /_cron/ingest runs IngestRunner.runOnce: one bounded session |
| Watchdog, cache cleanup | services | GET /_cron/watchdog, GET /_cron/cache-cleanup |
| Backfill queue | BackfillWorkerService drains it continuously |
each ingest run drains it after its session, within the time left |
| Identity refresh, push outbox, report webhook | services | the same services, plus a drain of the first two at the end of each ingest run |
| Who calls the cron routes | nobody needs to; without CRON_SECRET they answer 503 |
any scheduler that sends Authorization: Bearer <CRON_SECRET> |
Why keep a mode production does not use? Because building for it forced every piece of state out of process memory and into a table, and a resident process benefits from exactly the same property each time a deploy replaces it. The pieces that make both modes safe, each a short file in Jetstream/:
The lease (IngestLease). Jetstream sends every event to every connection, so two readers on one database would index everything twice and fight over the cursor. A reader takes the row in ingest_lease before connecting, renews it every five seconds while reading, and releases it when it stops. A lease not renewed for thirty seconds is expired and the next reader takes it. It is a row with an expiry rather than an advisory lock because the holder may be frozen or killed without warning. A deploy shows the lease at work: for a few seconds the old and the new copy both run, the new one finds the lease taken and retries every five seconds, the old one receives SIGTERM and hands the lease back, and the new one connects from the saved cursor a few seconds after that. In a local run that was seven seconds after the SIGTERM; on Railway the new copy connected 10, 14 and 14 seconds after it went live on three deploys of 2026-11-09. The resident reader and the cron route use the same lease, so you can run both: the cron route reports skipped while the resident process holds it.
The cursor (CursorStore, jetstream_cursor). Jetstream sequence numbers are local to each host, so the saved position is a seq plus the host it came from plus the event's witnessed time. A reconnect to the same host resumes by seq; a failover to the other host resumes by timestamp, rewound five seconds. A cursor can also be too old for the host to honour, in two ways. If the host refuses the connection twice in a row while the reader is resuming, the cursor is dropped, the reader restarts live, and every known account is queued for a backfill. If the host accepts the connection but says it had to move the cursor forward (an OutdatedCursor info frame), the reader carries on from where the host put it and queues the same full backfill.
Reconnects (ReconnectPolicy). Doubling backoff from one second to a minute, reset after a connection that lasted thirty seconds, and a switch to the next host after three consecutive failures.
The run (IngestRunner), cron mode only. Acquire the lease; read until the budget (fifty seconds) is spent; release; then drain the identity queue, the backfill queue (until a hard stop forty-five seconds after the budget) and the push outbox; answer with a report (events, commits, errors, last seq, lag, backfills run and pending, duration). Closing the connection takes about five more seconds, so one call can last a little over a minute and a half, and whatever calls the route has to wait that long. Called every minute, the socket is open about fifty seconds of every minute, so a record indexed while it is open shows up within a second and one that lands in the gap waits for the next run.
What stays per instance on purpose. The request rate limiter, the report limiter, the per-client Podcast Index bucket, the gateway's in-flight table, the identity refresh set, the report webhook's buffer, /metrics. Each is either a local concern or harmless to duplicate. Everything else that used to be process memory became a table: the backfill queue, the service-wide budget, the lease, the cursor. KnownDIDs is the in-between case: it is a cache of a set the tables define, so a miss against a copy older than five minutes reloads it before answering.
Liveness and health. Two routes answer two different questions, and pointing a platform at the wrong one is a classic way to make an outage worse. GET /_live is liveness: the process is up and the database answers (Database.ping). Railway's deploy check calls it, and it says nothing about Jetstream on purpose, so a Jetstream outage can never block the deploy that would fix it. GET /_health is health, for the uptime monitor. It reads the cursor age and whether the lease is held from the database (HealthMonitor), so an instance that never read Jetstream answers the same as one that did. It is degraded when the database does not answer within three seconds or the newest event is more than 300 seconds old, starting before the first cursor is saved, and ok otherwise; anything but ok is a 503. An idle lease between cron runs is not degraded.
Both routes give the database three seconds, and Support/Deadline.swift is how. A health check that waits a minute for a database that has stopped answering tells a monitor nothing, so the check has to answer even when its query never does. The obvious tool, a task group that races the query against a sleep, does not work here. A group returns only when all of its children have finished, and a query that PostgresNIO has already sent does not finish when its task is cancelled. withDeadline therefore runs the work in a task of its own and waits on a continuation, which is resumed by whichever finishes first, the work or a timer. At the deadline the caller gets nil, the work is cancelled and left to wind down, and whatever it produces later is dropped. Database.ping wraps SELECT 1 in it and logs database ping timed out when the timer wins. HealthMonitor.evaluate wraps its two queries in it (HealthMonitor.timeout) and reports degraded with db false. The price is that a query given up on keeps its pooled connection until the database answers it or the connection drops. With a local database frozen for 41 seconds, both routes answered 503 between 3.0 and 3.5 seconds after every request, the first one included, and 200 again as soon as the database resumed.
Building the image. Dockerfile builds the server as an image, and Railway builds from it on every railway up. Two things in it are worth knowing. Every swift build call carries --build-system native, because on Swift 6.4 the default build system cannot link Foundation statically for this package and names resource bundles .bundle, which the copy step would not find. And the resource bundle (migrations, lexicons, categories) must sit next to the binary: without it Bundle.module traps as soon as the server starts, so a RUN test -d line fails the image build instead. README.md has the deployment itself.
12. Configuration #
Config/AppConfig.swift is the only place configuration is read. swift-configuration gives a ConfigReader over an ordered list of providers; App.swift lists command-line flags, the environment, and a .env file, in that precedence. reader.scoped(to: "effem") maps camelCase keys to prefixed names, so reader.string(forKey: "databaseUrl") reads EFFEM_DATABASE_URL from the environment and --effem-database-url from the command line.
Three things are worth copying into any service you write:
- Fallbacks for platform names.
PORT,DATABASE_URL_UNPOOLED,DATABASE_URLandCRON_SECRETare read unscoped, so a host that provides them needs no renaming; an explicitEFFEM_name always wins. On Railway the service setsEFFEM_BINDandEFFEM_DATABASE_URLitself, so none of the fallbacks decides anything there. - Secrets are marked.
AppConfig.secretEnvironmentVariablesis handed to the environment providers so the reader redacts those values in any debug output. The report webhook URL is on the list: anyone holding it can post to the channel. - Validate once, then refuse to start.
validate()ports the Go service's rules (ports, URLs, CORS wildcards refused, token maps required when auth is on, pool sizes, CIDRs, DIDs, the ingest budget range) and throws aValidationErrorwhose text names the problem. The two newest settings are checked as they are read:EFFEM_REPORT_WEBHOOK_URLmust be anhttporhttpsURL andEFFEM_CLIENT_ADDRESS_HEADERmust be a valid header name.App.maincatches whateverbuildorrunServicethrows, logs onecriticalline with the reason (throughAppViewServer.describe, the same summary as section 3.7) and exits with status 1, so a bad setting reads as one clear line in the host's log instead of a trap and a crash report. A bad configuration is a failed start, never a wrong answer at runtime.
An unreachable database takes the same path, a minute later. PostgresNIO retries the connection while beforeServerStarts waits for the migrator, and the server is not listening yet. After about seventy seconds the connection pool gives up, its connectionCreationCircuitBreakerTripped error reaches the same catch, and the process exits with status 1. On Railway either failure shows up as a deploy that never answers its health check while the previous deployment keeps serving.
DatabaseURL parses postgres://user:password@host:port/db?sslmode=… because PostgresNIO has no URL initialiser, maps sslmode onto NIO's TLS options the way libpq does, and only allows sslmode=disable for local and .internal hosts. GoDuration and TokenMap are the other two parsers.
13. Observability #
Logging is swift-log. One Logger(label: "effem-appview") is created in makeLogger and passed by value into every component (loggers are structs). Every line carries structured metadata rather than string formatting, for example logger.info("request", metadata: ["method": ..., "path": ..., "status": ..., "ip": ..., "ms": ...]). The query string is deliberately never logged because tokens can travel in it. The backend is swift-log's own StreamLogHandler on standard output, bootstrapped first thing in App.swift. It prints one line per event:
2026-11-10T00:45:25+0000 info effem-appview: ip=203.0.113.7 method=GET ms=4 path=/_live status=200 [EffemAppView] request
That is the time, the level, the logger's label, the metadata as key=value pairs sorted by key, the module that logged, and the message last. Railway collects standard output. It files every line that arrives there as info, whatever level the line itself names, so its level filter does not find this service's errors: search for the message text (request failed, jetstream disconnected) instead. An unexpected error in a request is logged once, by RequestLogMiddleware, with the summary from section 3.7.
Metrics are swift-metrics with the Prometheus backend. Observability/Metrics.swift is every custom metric in one place, and the effem_* names are the Go service's, kept so dashboards and alert rules written against them carry over; ALERTS.md lists them. AppMetricsRegistry.bootstrapOnce exists because MetricsSystem.bootstrap may be called once per process and the tests build several applications. HTTP request metrics come from Hummingbird's MetricsMiddleware under its own names (hb.requests, hb.request.errors, http.server.request.duration, http.server.active_requests); the Prometheus factory turns the dots into underscores, so they are scraped as hb_requests, hb_request_errors, http_server_request_duration and http_server_active_requests. A counter appears in the output only after its first increment, so a missing series means "has not happened yet", which matters when you write an alert on it. GET /metrics needs the admin scope and reports this process only.
Health and liveness are Observability/Health.swift, described in section 11. The field names of /_health (status, db, firehose_up, firehose_seq, firehose_age_s) are the Go service's, from when it read the relay's firehose; clients and monitors read them, so they stay. /_live answers status and db only.
14. Tests #
Eighteen Swift Testing suites, 104 tests, in Tests/EffemAppViewTests:
| File | Suites | Needs Postgres |
|---|---|---|
ConfigTests.swift |
Configuration, Principals | no |
AddressTests.swift |
Client addresses | no |
CatalogRecordTests.swift |
Catalog records (the Go fixtures) | no |
DatabaseSupportTests.swift |
SQL statement splitting, Migration files | no |
SupportTests.swift |
Token buckets and limiters, Query helpers, Health, Ingest progress, Deadlines | no |
MiddlewareTests.swift |
Request pipeline | no |
ModerationTests.swift |
Moderation and identity | no |
StreamVisibilityTests.swift |
Comment stream visibility, Viewer | no |
EpisodeTranscriptTests.swift |
Episode transcripts | no |
FeedLookupTests.swift |
Feed lookup, and twelve tests that extend Database | no for the suite of its own, yes for the twelve |
DatabaseTests.swift |
Database | yes, EFFEM_TEST_DATABASE_URL |
Patterns to notice:
- Time is a parameter.
TokenBucket.allow(now:),RateLimiter.allow(_:now:),HealthStatus.evaluate(..., now:)take the clock as an argument, so the tests never sleep. The health test passes a fixednowon a whole second: the cursor's time goes through microseconds and the age through whole seconds, and withDate()that round trip sometimes lost a second. - Seams are protocols or closures.
ServiceBudgethas an in-memory and a database implementation;CommentEventBustakes its listener as a closure; the gateway takes the upstream call as a closure, sogateway()tests count calls with an actor instead of hitting Podcast Index.gatewaySingleFlight()uses the same seam to start eight callers at once and check that one call went out. - A deadline is tested against work that ignores cancellation.
DeadlineTests.givesUphandswithDeadlinea closure that resumes a second later from a dispatch queue and never looks at cancellation, which is how a query the database has stopped answering behaves. The test passes when the caller is released at the deadline, long before the work ends. - The probe router.
MiddlewareTestsbuilds the real middleware stack with throwaway routes (/open,/xrpc/whoami,/xrpc/mine) and drives it withapp.test(.router), so authentication, scopes, rate limiting, CORS, client addresses (the forwarded list and the edge's own header) and the cron secret are tested without a database. - Pure functions carry the rules.
ModerationTestsneeds no server and no database because the decisions were written as static functions: who a report is from (ModerationRoutes.reporter), what may be reported, the row key of a private report, the body of the webhook notice (ReportWebhook.request), which host adid:webdocument belongs to, how a person search folds into shows, which account events mean a purge (AccountPurge.isDeletion), and what may be logged about a failed Podcast Index call (PodcastIndexGateway.summary). - A stand-in for Podcast Index. PodcastIndexKit takes its transport as a parameter, so
PodcastIndexStubinFeedLookupTests.swiftanswers in its place and keeps what it was asked. The lookup by feed address is tested through the router with it: the address reaches Podcast Index in one spelling and with every character intact, "not found" (either way Podcast Index says it) is a 404 that is asked for again each time and never stored, an address too long for the key column is still cached, and an outage or a refused request is a 502 or an expired copy, never a 404. The transport is set process-wide, which is one more reason these tests live in the serialized database suite. - The database suite is serialized and destructive.
TestDatabase.runopens a small pool inside a task group, drops and recreates thepublicschema, runs the migrator, runs the test, then cancels the pool. Point it at a throwaway database only. It is where private reports, bans, purges, subscriber paging and/_liveare tested end to end through the router.
Commands, from README.md:
docker compose up -d # Postgres on localhost:5433
swift test # 104 tests; the 32 in the Database suite are skipped
EFFEM_TEST_DATABASE_URL='postgres://effem:effem@localhost:5433/effem?sslmode=disable' swift test
scripts/linux-test.sh # the same inside the swift:6.4-noble image
15. Recipes #
Add a read route #
- Pick the route family in
API/Routes(or add a struct with the same shape: dependencies aslets,var routes: RouteCollection<AuthenticatedRequestContext>). - Register it:
routes.get("xyz.effem.feed.getThing", use: thing). If the route is user-scoped, put it under the group that carriesRequireQueryDIDMiddleware. - Write the handler:
@Sendable func thing(_ request: Request, context: AuthenticatedRequestContext) async throws -> JSON<ThingResponse>. Read parameters withQueryValues.trimmed/QueryValues.limit, build the query withSQLBuilder, applyappendVisibility(viewer: context.viewerDID(in: request))for anything public (it is what hides inactive and banned accounts and applies the viewer's blocks, so a public read without it shows them), fetchlimit + 1rows and wrap them inPage. A count or an aggregate beside the list is a separate query and needsAccountStatusStore.hiddenAccountsSQLin its ownWHERE, as the subscriber count inSocialRoutes.subscribersshows. Page by a column that differs from row to row among the rows the route returns. The record key does inside one account. Across accounts it may not, which is whySocialRoutes.subscriberspages by DID. - Add the response type to EffemKit's
EffemModelsso the clients decode the same shape, and remember the encoder writes snake_case. - If it is a new route family, attach it in
buildRouterand write a lexicon JSON file underResources/LexiconssodescribeLexiconslists it (and bump the count in thedescribeLexiconstest). - Test it through
app.test(.router)inDatabaseTests, or through a probe router if it needs no data.
Add a mutation route #
Same as above, but routes.post, decode the body with decodeBody(RequestType.self, request, context), do the writes inside database.withTransaction when there is more than one, answer JSON(OKResponse()), and on admin routes call audit(...) after the write.
Index a new collection #
- Add the lexicon file under
Resources/Lexicons. - Write a migration
0014_<name>.sqlwith the table, a unique index on(did, rkey), and any subject index. - Add the collection ID to
Indexer.collections(this is what the Jetstream subscription filters on and what backfills walk). - Add
indexThing(did:rkey:cid:record:)inIndexer/Collections.swift: validate withRecordFields, upsert withON CONFLICT (did, rkey) DO UPDATE, refresh whichever stats depend on it. Add thecaseinIndexer.indexand the deletecaseinIndexer.delete. If the new rows feed a counter, count them the wayStats.swiftdoes, without hidden accounts, and add the table to theUNIONinrefreshStats(touchedBy:); otherwise a ban will not recount it. - If it should notify someone or appear on a stream, only do so when
source == .live. That one check also keeps a banned account's records quiet, becauseIndexer.indexhands them over as.suppressed. - Test it in
DatabaseTests.indexingAndReadsstyle: index, read the row, delete, check the counters.
Add a background job #
- Write a
struct ThingService: Servicewith thecancelWhenGracefulShutdownloop and arunOnce()that does one pass and returns a count. Run the pass before the sleep, so a service that is redeployed more often than the interval still gets its turn. - Add it to
Components.servicesinApplication.swift, in the service-mode list if a resident process should run it on a timer. - Add a route in
CronRoutesthat callsrunOnce(), so thatcronmode can drive it too.
Add a configuration key #
- Add the property with its default to
AppConfig. - Read it in
load(from:)through the scoped reader (reader.string(forKey: "thingName", ...)readsEFFEM_THING_NAME). - Validate it in
validate()and, if it is a secret, add its environment name tosecretEnvironmentVariables. - Document it in the table in
README.md, add a line toConfigTests.loading, and set it on the Railway service if production needs a value other than the default.
Add a migration #
Number it next in sequence, never edit a file that has already been applied anywhere, not even a comment in it (the checksum check will refuse to start), use -- migrate:no-transaction as the first comment only for CREATE INDEX CONCURRENTLY, and remember the file runs on every instance's start under the advisory lock.
16. Things I noticed while reading #
Most of these are observations from reading the code, not verified failures; the ones marked "run" were checked against a running server on 2026-11-09. The service runs on Railway and the tests pass, so none of them is urgent; they are the places I would look at first.
- Graceful shutdown skips the code after the loop in
PushDispatcherService.run.cancelWhenGracefulShutdownrethrows whatever the closure throws, and on shutdownTask.sleepthrowsCancellationError, soawait clients.shutdown()on the next line never runs and the two AsyncHTTPClient instances inside the APNs clients are not shut down. In a release build the process exits anyway; in a debug build AsyncHTTPClient'sdeinithas a precondition about un-shut-down clients that could fire if the client were deallocated before exit.JetstreamConsumerServicehas the same shape withlease.releaseafter the loop. There the common case is fine, becauseingester.runcatches cancellation while it is connected and returns.cancelled(a stop during normal reading hands the lease back; the next reader connected seven seconds later when I tried it). A shutdown that lands in the reconnect backoff sleep insideJetstreamIngester.runthrows past the release while the lease is still held, and the next reader then waits out the thirty-second expiry. CatchingCancellationErrorinside the closure, or moving the cleanup into adefer, fixes both. Migrator.run(on:)unlocks twice and once from an unstructured task. Thedefer { Task { ... pg_advisory_unlock ... } }fires on the success path too, after the explicit unlock, and on the failure path the detached task runs a query on a connection thatwithConnectionis returning to the pool. It is harmless (advisory locks are per session, and a second unlock only warns), but ado/catchwith one unlock in each path would say what is meant.RateLimitMiddleware.key(for:)and its comment disagree about service tokens. The comment says admin and service callers are keyed by subject; the code keys a service token by client address whenever an address is known, and by subject only when none is. That may be intended (several web-player instances sharing one token should not share one bucket), but one of the two should change.AdminRoutes.auditis best effort. A failed audit insert is logged and the mutation still succeeds. Reasonable for now, but anyone relying on the audit table as a complete record should know.SocialRoutes.profileruns fourCOUNT(*)queries serially. Fine at this scale; if profiles get hot, one query or the stats tables would do.- A start against an unreachable database takes over a minute to fail (run). A bad setting ends the process at once. An unreachable database ends it only when PostgresNIO's pool gives up, 73 seconds in when I tried it. During that time the server is not listening, and SIGTERM does not stop the process either, because graceful shutdown waits for
beforeServerStarts. - The watchdog cannot retry a failed delete. A delete that fails becomes a row in
indexer_errorslike any other failure.WatchdogService.retryknows one move: fetch the record from the PDS and index it. For a delete the record is gone, so the fetch fails five times and the row is left alone, with the deleted record still indexed. The table does not say whether a row came from a create or a delete; recording the operation would let the watchdog repeat it. - A backfill never removes rows.
BackfillRunnerlists what is in the repository and indexes it. A record that was deleted while the service was not listening is not in the list, and nothing compares the list with what is indexed, so its row stays. The full backfill that follows a lost cursor therefore repairs missing records and not missing deletes. - A short database outage can drop the records that arrive during it. This one is read, not run.
JetstreamIngester.handle(frameText:)notes an event's position before it handles the event, andpersistCursorsaves the newest position whether or not the event was indexed. Normally a failure is safe, because it becomes a row inindexer_errorsand the watchdog retries it. While the database is down that row cannot be written either (the log saysindexer_errors upsert failed), and once the database is back the saved cursor is already past the event. An outage longer than the lease's thirty seconds repairs itself, because the reader loses the lease and replays from the last position it managed to save. A shorter one does not. - A host that closes every connection cleanly is never abandoned.
ReconnectPolicyswitches host after three failures in a row.JetstreamIngester.runcallspolicy.connected()wheneverconnectOncereturns without throwing, which resets that count, and a clean close is such a return. A host that accepts the connection and then closes it politely, over and over, is retried for good, and the other host is never tried. effem_firehose_lag_secondsmeasures silence, not lag.persistCursorsets it to the time since this process last received an event, stamped with the wall clock on arrival (ConsumerStatus.lastEventTime). While the reader replays an hour of backlog the gauge stays near zero, because events are arriving quickly, although the data is an hour behind.firehose_age_sin/_healthis computed from the event's own time and is the number that means lag.ALERTS.mddescribes the gauge as what it is.subscriptionshas no unique index on(did, subject_uri).comment_likesandblockshave one on their pair, so a second record for the same pair is refused. For subscriptions the record key is the only guard (section 7). An account that holds two subscription records to one podcast under different keys, for example one written under a TID key before the key was derived and one written after, is two rows: it counts twice in the subscriber count and appears twice ingetSubscribers. That list pages by DID, so if a page ends between the two rows the second one is skipped, which happens to hide the duplicate rather than a subscriber.
17. Reading order and references #
Suggested order through the code, each step building on the last:
Application.swift: the whole service in one file.API/Context/RequestContexts.swift,API/Middleware/Middlewares.swift,API/Routes/Responses.swift,Support/AppError.swift,Support/ErrorSummary.swift: the request pipeline.API/Routes/SocialRoutes.swift, thenCommentRoutes.swiftandHydration.swift: handlers, from simple to layered.ModerationRoutes.swiftis a small mutation route with its own limiter, andWellKnownRoutes.swiftis a route that depends on theHostheader.Database/Database.swift,Migrator.swift,Resources/Migrations/*.sql: the data layer and its history.Indexer/Indexer.swift,Collections.swift,Stats.swift,Notifications.swift,RecordFields.swift,AccountStatusStore.swift,AccountPurge.swift,ReportWebhook.swift: records to rows, who gets told, and how an account's rows are hidden or removed.Jetstream/JetstreamIngester.swift, thenIngestLease.swift,CursorStore.swift,IngestRunner.swift,JetstreamConsumerService.swift: the reader and its two drivers.Indexer/CommentEventBus.swift,CommentEventPublisher.swift,CommentEventListener.swift,API/WebSocket/CommentStreamRoute.swift: the live path.PodcastIndex/PodcastIndexGateway.swiftandBudgets.swift: the actor and single-flight patterns.Catalog/*,Identity/*,Push/*,Indexer/Backfill.swift,WatchdogService.swift.- The tests, which double as usage examples for everything above.
References:
- Hummingbird 2 documentation: https://docs.hummingbird.codes/2.0/documentation/index/ (start with the Router, Request Context, Middleware and Service Lifecycle articles)
- Hummingbird examples repository: https://github.com/hummingbird-project/hummingbird-examples
- PostgresNIO: https://github.com/vapor/postgres-nio (the README covers
PostgresClient, queries andlisten) - swift-service-lifecycle: https://github.com/swift-server/swift-service-lifecycle
- swift-configuration: https://github.com/apple/swift-configuration
- Jetstream: https://github.com/bluesky-social/jetstream
- AT Protocol glossary (AppView, PDS, relay, lexicon): https://atproto.com/guides/glossary
- Railway documentation: https://docs.railway.com (health checks, deployment teardown, private networking, backups)
- In this repository:
README.md(configuration, routes, deployment),RUNBOOK.md(operations and moderation),ALERTS.md(monitoring) andBACKUPS.md(backups and the restore drill) - The project's own plan and status, one directory up in the
effemfolder:nov9.md(the production plan and the findings behind it),summary.md(where things stand) andswift-appview.md(the design decisions and their reasoning; its hosting sections describe an earlier plan and no longer apply)
Appendix A: Glossary #
| Term | Meaning here |
|---|---|
| AT Protocol | The open social networking protocol behind Bluesky. Users own their data in repositories; services index it. |
| DID | Decentralized identifier, a user's permanent ID, for example did:plc:abc123. Resolved through the PLC directory to a document naming the user's PDS and handle. |
| PDS | Personal Data Server, where a user's repository lives. The AppView reads from it during backfills and watchdog retries. |
| Relay, firehose | The relay aggregates every PDS's changes into one stream, the firehose. |
| Jetstream | A JSON version of the firehose, filterable by collection, served over WebSocket. What this service reads. |
| Lexicon | A JSON schema for a record or an XRPC method, named like xyz.effem.feed.comment. The files under Resources/Lexicons. |
| Collection | The set of records of one lexicon type in a repository. |
| rkey | Record key, the last path segment of a record's URI. Comments, recommendations, lists, bookmarks and boosts use a TID (timestamp-based, so ordering by rkey is ordering by time). Subscriptions, comment likes, blocks and episode states use a key derived from their subject, so writing the same one twice lands on one record. Most pagination cursors are rkeys; getSubscribers uses the DID, because all subscriptions to one podcast share a key. |
| AT URI | at://<did>/<collection>/<rkey>, the address of a record. |
| CID | Content identifier, a hash of a record's canonical bytes. Changes when the record changes. |
| strongRef | {uri, cid}: a reference to a specific version of a specific record. |
| DAG-CBOR | The canonical binary encoding AT Protocol hashes records in. |
| XRPC | AT Protocol's HTTP convention: GET /xrpc/<lexicon id>?params for queries, POST for procedures, JSON bodies. |
| AppView | This service: an index over records from many repositories, serving queries a single PDS cannot. |
did:web |
A DID whose document is served by a web host at https://<host>/.well-known/did.json. The catalog and the labeler are did:web identities. |
| Labeler, label | A moderation authority and the tags it attaches to records (src_did, subject_uri, val). !hide removes a comment from reads; !warn asks the client to put it behind a warning. |
| Report | A user's complaint about a record or an account. Sent privately to this service, or published as an xyz.effem.moderation.report record. |
| Ban | An operator's decision to hide an account's content, leave it out of the counters and silence its new records. Separate from the relay's own active flag. |
| Purge | Deleting what this service holds about one account. Automatic when the relay reports the account deleted; by hand for a deletion request. The account's repository is not touched. |
| Threadgate | A record restricting who may reply to a root comment. |
| Middleware | A function that wraps request handling: runs before and after the handler, may short-circuit. |
| Request context | The per-request struct carrying logger, parameters, identity and anything else handlers need. |
| Reverse proxy | A server in front of this one: Railway's edge, and Cloudflare in front of that for appview.effem.xyz. It is the socket peer; the real client is named in a header it sets (X-Real-IP on Railway). |
| Service token | A token whose subject is *: it has read scope but no user behind it. The token shipped in the app is one. A DID sent with it (did, viewer) is taken as given. |
| Viewer | The account a read is answered for: the token's DID, or with the service token the DID in the viewer parameter. It decides whose blocks apply and whose like is returned. |
| Liveness, health | Liveness: can this process do any work at all (/_live). Health: is the whole service doing its job (/_health). A platform's deploy check wants the first, a monitor the second. |
| Webhook | A URL another system gives you to post messages to. Here: where a notice goes when a report arrives. |
| CIDR | An address range written 10.0.0.0/8: the address plus how many leading bits must match. |
| CORS | Browser rules for cross-origin requests; the server opts origins in through response headers. |
| Token bucket | A rate limiter: a bucket refills at a steady rate, each request takes a token. |
| Connection pool | A set of open database connections reused across requests. PostgresClient. |
| Transaction pooler | A proxy that lends a connection per transaction. Breaks LISTEN and advisory locks, hence the separate listen URL. |
| Migration | A numbered SQL file that moves the schema forward once, recorded so it never runs twice. |
| Upsert | INSERT … ON CONFLICT DO UPDATE: insert or update in one statement. |
| LISTEN / NOTIFY | Postgres' built-in pub/sub between connections. |
| Advisory lock | A Postgres lock on a number you choose, used to serialize the migrator across instances. |
| Lease | A claim on shared work with an expiry, so a dead holder is replaced automatically. |
| Cursor (pagination) | The key of the last row returned, sent back to get the next page. |
| Cursor (Jetstream) | The position in the stream to resume from. |
| Backfill | Re-reading a user's whole repository from their PDS to rebuild their rows. |
| APNs | Apple Push Notification service. |
| TTL | Time to live: how long a cached copy counts as fresh. |
| Prometheus | A metrics system that scrapes /metrics in a text format. |