PublicTxt Aggregator - Elixir Design Log

Context

A design for a hosted aggregation service for PublicTxt Web (publictext.net), built in Elixir on the BEAM ([[../../../Computer-Science/Languages/Erlang]]/OTP). It’s also a learning vehicle for OTP. The [[PublicTxt]] stack stays free; the hosted service adds convenience (aggregation, discovery, optional paid hosting) - see PublicTxt Web Hosting

Why Elixir

  • Same VM as Erlang, so every OTP benefit carries over:
    • One lightweight process per followed repo; thousands are cheap.
    • Failure isolation: a broken, slow or deleted repo crashes only its own follower; the supervisor restarts it.
    • Built-in timers (Process.send_after/3) and mailboxes replace job queues and schedulers.
    • Per-tenant supervision trees isolate paying users from each other.
    • Clustering for growth.
  • Over plain Erlang:
    • Phoenix (Channels, LiveView, Phoenix.PubSub) for the web-facing product and live push.
    • Better text handling: String, binaries pattern matching, NimbleParsec, YAML front matter via yaml_elixir, Markdown via Earmark/MDEx.
    • Tooling: mix, Hex, ExUnit, releases.
    • Full interop: any Erlang library or module is callable directly (:ets, :gen_server etc.).
  • Weaknesses:
    • No mature libgit2 binding; shell out to git via System.cmd/3 or a Port. Avoid a libgit2 NIF (a native crash takes down the whole VM).
    • Hot code upgrades are possible but rarely used in Elixir; plan for rolling restarts with state rebuilt from the index repo.
    • Smaller ecosystem than .NET.
    • LLM Coding Agents have less Elixir code to train on, and so are less competent.

Architecture

  1. Application supervisor (PublicTxt.Aggregator.Application): starts and restarts the components below.
  2. Inputs: opt-in registrations, plus a trust list of already-public repos.
  3. Repo supervisor: a DynamicSupervisor (DynamicSupervisor.start_child/2) with one Follower GenServer per repo, named via Registry keyed by repo URL. Each follower checks the opt-out flag, polls on a timer, fetches, parses changes and sends updates on.
  4. Index (GenServer): sole writer to an in-memory ETS index for fast queries.
  5. Committer (GenServer): periodically pushes an index snapshot to a dedicated public git index repo.
  6. API / feed layer (Phoenix): answers queries and pushes live updates via Phoenix.PubSub / Channels.

Restarts and backoff

  • Supervisors don’t do backoff. They restart immediately and give up (crashing upward) after max_restarts in max_seconds.
  • A dead repo restarting in a tight loop can therefore take down the repo supervisor and every healthy follower with it.
  • Backoff lives in the follower: track consecutive failures in state and schedule the next poll with exponential delay, rather than crashing on expected errors (404, timeout, deleted repo). Crash only on the unexpected.
  • Set restart: :transient for followers that should stop permanently (e.g. repo opted out).

Index design

  • Single writer. All writes go through the Index GenServer mailbox, one at a time, so updates are consistent without locks.
  • Process ownership. ETS tables die with their owner, so the stable Index process owns the table, never a crash-prone follower. Optionally set :heir so a supervisor-held process inherits the table if Index crashes.
  • Access: :protected (owner writes, anyone reads) with read_concurrency: true. Not :public - that lets any process write and breaks the single-writer guarantee.
  • Deduplication. Key on resource_id (hash of the normalized URL). Repeated updates overwrite, so writes are idempotent. Entries from multiple repos merge into one resource listing its repos and tags, which is also the source of co-occurrence data.
  • Reads bypass the process. Queries read ETS directly; only writes queue.
  • ETS is memory-only. On restart, rebuild from the committed index repo, then let followers catch up.

Mailbox growth and backpressure

  • Risk: followers send faster than the Index processes, the unbounded mailbox grows, memory runs out, and the node crashes.
  • Backpressure (the real bound): followers use GenServer.call/3, not cast. Each follower blocks until it gets a reply, so it has at most one message in flight; the mailbox is bounded by the follower count.
  • Batching: one message per fetch, not per file. Reduces volume but doesn’t bound it.
  • Call timeout: default 5000 ms; on timeout the caller exits. Set an explicit timeout and let the follower’s supervisor handle the restart.

Discovery: the index repo as a node

  • The committed index repo is a free, persistent discovery layer, so communities can find PublicTxt repos without the server.
  • Each server is one node publishing its own index repo.
  • Committing into other people’s repos is ruled out: it needs write access and breaks single-author-per-repo.
  • Batch commits on a timer to limit churn; a single Committer process avoids conflicts.
  • Relates to reconsidering ADR-0003 (committed derived data with staleness stamps).
  • Opt-in registration, plus aggregation of a trusted list of already-public repos.
  • Public doesn’t mean consent to aggregate: honour an opt-out flag (front matter field or file, like robots.txt) and check licences before republishing content; indexing links and tags is lower risk than copying full text.
  • The trust list is a file in git, so other nodes can follow the curation. It’s effectively CuratedCommons for repos.
  • Federation: nodes follow each other’s index repos and trust lists. Limit transitive following to 1–2 hops; each node chooses whether to inherit trust.

Next step

Build the simplest piece: mix new publictxt_aggregator --sup, then a single Follower GenServer that polls one repo on a timer.

defmodule PublicTxt.Aggregator.Follower do
  use GenServer

  @poll_ms :timer.minutes(5)

  def start_link(repo_url),
    do: GenServer.start_link(__MODULE__, repo_url)

  @impl true
  def init(repo_url) do
    {:ok, %{repo: repo_url, failures: 0}, {:continue, :poll}}
  end

  @impl true
  def handle_continue(:poll, state), do: poll(state)

  @impl true
  def handle_info(:poll, state), do: poll(state)

  defp poll(state) do
    case fetch(state.repo) do
      {:ok, _changes} ->
        schedule(@poll_ms)
        {:noreply, %{state | failures: 0}}

      {:error, _reason} ->
        failures = state.failures + 1
        schedule(min(@poll_ms * 2 ** failures, :timer.hours(6)))
        {:noreply, %{state | failures: failures}}
    end
  end

  defp schedule(ms), do: Process.send_after(self(), :poll, ms)

  defp fetch(_repo), do: {:ok, []} # TODO: git ls-remote / fetch via System.cmd
end