notes · · 5 min · updated 2026-10-27

Mastodon Under the Microscope: What 67 Remote AST Tools Found Inside the Federated ActivityPub Engine

Analysis of the federated ActivityPub engine developed by Eugen Rochko and the Mastodon community with prod-code: 189,749 lines across 3,278 files, ActivityPub verification, and 8,191 RSpec expectation matches.

On this page · 5 sections
  1. Subsystem Architecture: Decoupled Federation & Ingestion Pipeline
  2. The ActivityPub Ingestion Core: JSON-LD Compaction and Actor Verification
  3. Clone Analysis and API Test Sequences
  4. Semantic Invariants: 8,191 Expectation Matches and 344 raise Matches
  5. Remote AST Operations on Cluster Nodes

First published on 2026-10-04. The measurements reported in this article are historical and have not been re-run for this revision.

As centralized social media platforms face increasing user scrutiny, Mastodon has emerged as the definitive standard for decentralized, federated communication. Created by Eugen Rochko in 2016, Mastodon connects thousands of independently operated servers into a cohesive global network via the W3C ActivityPub protocol.

Behind its responsive web client and REST API lies a demanding backend architecture: high-throughput asynchronous background workers (Sidekiq), Redis-backed pub/sub fanout pipelines, streaming WebSocket clusters, and rigorous cryptographic verification of Linked Data Signatures.

To examine how Mastodon structures its federation protocols, isolates background ingestion, and enforces security invariants across hundreds of thousands of lines of Ruby on Rails code, we deployed operations from prod-code’s 67-tool suite against a checkout mirrored to a remote 32-core cluster node (node-b:9400).

$ git ls-files '*.rb' | wc -l
3278
$ git ls-files -z '*.rb' | xargs -0 wc -l | tail -n 1
189749 total
$ git ls-files | awk -F. '{if (NF>1) print $NF}' | sort | uniq -c | sort -nr | head -n 6 
 4278 svg
 3278 rb
  594 yml
  500 tsx
  311 haml
  286 ts

The captured inventory shows 189,749 lines of Ruby across 3,278 source files:

  • Application Core (app/): 65,137 lines across 1,259 files. Domain models, ActivityPub services (app/services/activitypub/), Sidekiq background workers (app/workers/), and REST/OAuth controllers.
  • RSpec Test Harnesses (spec/): 100,844 lines across 1,245 files. Unit, service, and federation request specifications.
  • Federation Libraries & CLI (lib/): 7,562 lines across 74 files. ActivityPub protocol models, cryptographic signature verifiers, and CLI administrative tools (tootctl).

Subsystem Architecture: Decoupled Federation & Ingestion Pipeline

Mastodon structures its business logic into focused service objects under app/services/ rather than bloating controller actions:

  1. ActivityPub Processing (app/services/activitypub/): Ingests remote activities (Create, Update, Delete, Follow, Announce, Like), validates actor identities, and manages public key fetching.
  2. Federation Delivery (app/workers/activitypub/delivery_worker.rb): Dispatches outgoing HTTP POST requests signed with HTTP Signatures across external instance inboxes.
  3. Local Distribution & Fanout (app/services/fan_out_on_write_service.rb): Distributes newly published statuses to local followers, lists, hashtag feeds, and Redis streams. Remote inbox deliveries are queued separately by PostStatusService and handled by ActivityPub::DistributionWorker.
  4. Moderation & Domain Control (app/services/resolve_account_service.rb, DomainBlock): Enforces IP blocks, domain-level mutes, suspension cascades, and content sanitization.

We ran prod-code dependencies across the monorepo:

$ prod-code dependencies --scope modules
⚡ prod-code Architecture & Dependency Graph Report
────────────────────────────────────────────────────
Scope: modules | Nodes: 372 | Dependencies: 16

✓ Zero circular dependencies detected. Architecture graph is a clean DAG.

As reported, the extracted graph has 372 module nodes and 16 dependency edges and contains no cycles. With that few edges it describes only the references the extractor resolved, not the whole application, and it says nothing about how federation traffic is handled. That is in the request path: the inbox controller accepts the signed POST and queues ActivityPub::ProcessingWorker, which runs the processing service in the background, so the inbound request does not wait for the activity itself to be processed.

Correction, 2026-10-27. As published on 2026-10-04, this paragraph inferred from the acyclic graph that federation services run independently of the frontend and that incoming traffic is accepted, verified and enqueued without blocking user-facing HTTP endpoints. A 16-edge graph over 372 nodes cannot establish that; the queuing behaviour comes from the inbox controller and processing worker, which the review read in Mastodon’s source. The inference from the graph and the absolute non-blocking guarantee are withdrawn.

The ActivityPub Ingestion Core: JSON-LD Compaction and Actor Verification

A central service in Mastodon’s federation path is ActivityPub::ProcessActivityService (app/services/activitypub/process_activity_service.rb, 107 lines). It is not where HTTP ingress begins: ActivityPub::InboxesController receives the POST and queues ActivityPub::ProcessingWorker, which calls this service.

When an external instance pushes a payload to an inbox, Mastodon unpacks and verifies the message:

def call(body, actor, **options)
  @account = actor
  @json    = original_json = JSON.parse(body)
  @options = options

  return unless @json.is_a?(Hash)

  begin
    @json = compact(@json) if @json['signature'].is_a?(Hash)
    check_jsonld_limits!(@json)
  rescue Mastodon::InvalidJsonLdError, JSON::LD::JsonLdError => e
    @json = original_json.without('signature')
  end

  return unless supported_context?(@json)

  if different_actor?
    @account = actor_from_verified_ld_signature
    @account ||= actor_from_verified_object_integrity_proof(original_json)
  end
  return if !@account.is_a?(Account) || different_actor? || suspended_actor? || @account.local?

  activity = ActivityPub::Activity.factory(@json, @account, **@options)
  activity&.perform
end

Key architectural guarantees in this pipeline:

  • JSON-LD Normalization & Compaction: To prevent semantic injection attacks where external context URLs modify field interpretations, payloads with signatures are compacted into predictable structures using compact(@json).
  • Cryptographic Signature Verification: Payloads relayed across intermediate instances verify Linked Data Signatures (actor_from_verified_ld_signature) against public keys retrieved and cached from the originating actor’s URI.
  • Polymorphic Activity Dispatch: ActivityPub::Activity.factory maps activity types to concrete handlers such as ActivityPub::Activity::Create, ActivityPub::Activity::Announce, and ActivityPub::Activity::Follow based on @json['type'].

Clone Analysis and API Test Sequences

We executed prod-code duplicates to detect structural cloning:

$ prod-code duplicates --min-lines 6 --max-groups 5
⚡ prod-code Clone & Duplication Harvester Report
────────────────────────────────────────────────────
Files Scanned: 3650 | Lines: 224427 | Clone Groups: 5 | Duplication: 0.8%

Discovered Clone Groups:

[Clone Group #6719] 6 lines | 82 occurrences (Type-2 (Parameterized))
  • Occurrence 1: spec/requests/api/v1/media_spec.rb:51-56
  • Occurrence 2: spec/requests/api/v1/media_spec.rb:63-68
  • Occurrence 3: spec/requests/api/v1/media_spec.rb:165-170
  • Occurrence 4: spec/requests/api/v1/media_spec.rb:185-190
  • Occurrence 5: spec/requests/api/v1/polls_spec.rb:66-71
  Preview:
    │         subject
    │
    │         expect(response).to have_http_status(404)
    │         expect(response.content_type)
    │           .to start_with('application/json')

Across 3,650 files and 224,427 scanned lines, the report gives a duplication figure of 0.8% under these options; the output does not define the percentage or say whether it counts only the five groups displayed. The one group shown, Clone Group #6719, sits in API request specs (spec/requests/api/), where endpoints verify standardized JSON error responses (the preview shows the 404 case).

The shown clone report (capped at five groups, one of them shown) does not assess app/services/ and app/models/; the article’s naming of reusable concerns there (AccountCounters, StatusThreading, Attachmentable) is a source-level description, not a duplication measurement.

Correction, 2026-10-27. As published on 2026-10-04, this section said duplication is constrained at 0.8% and that core backend logic in app/services/ and app/models/ is rigorously factored. The report shown has --max-groups 5, displays one group in request specs and does not define its percentage; it does not measure those directories. The 0.8% figure is kept as reported, and the factoring conclusion is withdrawn.

Semantic Invariants: 8,191 Expectation Matches and 344 raise Matches

Two lexical counts give the scale of Mastodon’s specs and explicit raises:

$ grep -rnE "expect\(" spec/ | wc -l
8191
$ grep -rnE "raise " app/ lib/ | wc -l
344

The commands count matching lines: 8,191 lines under spec/ contain expect(, and 344 lines under app/ and lib/ contain raise (the article names Mastodon::HostValidationError, ActivityPub::ActionError and Mastodon::SyntaxError among the raised classes). They do not show which specs cover SSRF, DNS rebinding or malformed federation envelopes, or that those specs pass.

Correction, 2026-10-27. As published on 2026-10-04, this section said Mastodon ensures network security and database consistency through exhaustive specifications and, from these counts, that it guards against SSRF attempts, DNS rebinding attacks on remote inboxes and malformed federation envelopes. The commands shown count matching lines; the article cites no spec or source case for those attacks and no test run. The exhaustiveness and attack-coverage claims are withdrawn.

Remote AST Operations on Cluster Nodes

To evaluate AST refactoring on complex Rails codebases, we tested prod-code extract-function on username normalization and Webfinger lookups in app/models/account.rb.

The article reports that the remote cluster node resolved Active Record association scopes, extracted acct parsing helpers, and found zero analyzer regressions in 12 milliseconds with 0% local laptop CPU utilization. No command, selection, preview, analyzer output or CPU measurement is shown, so the extraction, its outcome, its timing and the CPU figure are author-reported and execution-unverified.

Mastodon shows how a mature Ruby on Rails architecture organizes a complex, decentralized, and adversarial communications protocol around background worker pipelines and cryptographic contract verification.

Correction, 2026-10-27. As published on 2026-10-04, this sentence said the architecture can scale the protocol to tens of millions of users worldwide. The article cites no dated user count and does not say whether registered or active accounts are meant, and the source it examined cannot establish capacity at any scale. The population figure and the causal scaling claim are withdrawn.

Editorial note, 2026-10-11: the host names, addresses and home-directory paths of our build nodes in this post were replaced with the placeholders node-a, node-b and <user>. No other part of the quoted output was changed.

Cite this article
Citation
Alexander Panasenko (2026-10-04). Mastodon Under the Microscope: What 67 Remote AST Tools Found Inside the Federated ActivityPub Engine. https://prod.codes/blog/mastodon-under-the-microscope-67-ast-tools/