Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 13 — Data, Jobs & Pipelines

Persistence and declarative modeling got their own chapters (Ch 11 Ecto, Ch 12 Ash). This chapter covers the rest of the Data domain: background work, backpressured dataflow, and dataframes. Every piece here is a composable library — the “pluggable” style from Ch 06 — each one an OTP application you start in your supervision tree.

13.1 Oban — Background Jobs as Supervised Processes

Where Erlang shops roll their own job queues on top of a table + poller, Oban provides it with OTP semantics built in:

  • Jobs are rows in Postgres → durable, transactional with your data writes
  • Workers are supervised processes → crash isolation per Ch 01
  • Retries/backoff configured per worker — fault isolation applied to jobs
  • No Redis required
flowchart LR
    CODE["your write path"] -->|"same transaction"| INS["Oban.insert!<br/>job row = user row"]
    INS --> PG[("Postgres<br/>oban_jobs table")]
    PG -->|"poll / LISTEN"| P["Oban queue<br/>producers"]
    P --> W["Worker process<br/>supervised"]
    W -->|"crash!"| SUP["Supervisor<br/>restarts"]
    P -->|"attempt 2, backoff ×2"| RET["retry per<br/>max_attempts"]
    W --> OK[":ok → done"]
defmodule MyApp.Workers.SummaryWorker do
  use Oban.Worker, queue: :default, max_attempts: 5

  @impl true
  def perform(%Oban.Job{args: %{"doc_id" => id}}) do
    case Summaries.generate(id) do
      {:ok, _} -> :ok                    # success → remove job
      {:error, _} = e -> {:error, e}     # error → retry with backoff
    end
  end
end

# enqueue — atomically with your business writes when inside Repo.transaction:
%{doc_id: 42}
|> MyApp.Workers.SummaryWorker.new()
|> Oban.insert()

String keys. You enqueued an atom-keyed map, but jobs are serialized to JSON before they hit the database — so perform/1 receives %{"doc_id" => 42}. That is why the pattern above matches "doc_id". Pick one convention deliberately: either match string keys in every worker (realistic), or enqueue with string keys (%{"doc_id" => 42}) so what you write is what you match.

From Erlang you know: the worker is an ordinary supervised process. perform/1 returning {:error, _} is just a structured way of letting the supervisor/retry machinery decide what happens next — let-it-crash with an audit trail in Postgres.

Install once in your supervision tree. Note repo: — Oban requires it and will not boot without it:

# lib/my_app/application.ex
children = [
  MyApp.Repo,
  {Oban, repo: MyApp.Repo, queues: [default: 10, reports: 2]}
]

and yes, that option list is a keyword list like any other (Ch 02 §2.7).

Unique Jobs, Cron, and Scheduling

The knobs that replace hand-rolled dedup tables and crontabs:

defmodule MyApp.Workers.NightlyRollup do
  use Oban.Worker,
    queue: :reports,
    max_attempts: 3,
    # :infinity = duplicate-suppressed as long as the row exists;
    # :all covers every state so a re-enqueue race can't slip through
    unique: [period: :infinity, states: :all]

  @impl true
  def perform(_job), do: Reports.rollup_daily()
end

# schedule for later — a row with a future scheduled_at:
%{doc_id: id}
|> SummaryWorker.new(scheduled_at: DateTime.add(DateTime.utc_now(), 3600))
|> Oban.insert()

# recurring jobs come from the cron plugin, configured at startup:
{Oban, repo: MyApp.Repo, queues: [default: 10, reports: 2],
 plugins: [{Oban.Plugins.Cron,
            crontab: [{"0 2 * * *", MyApp.Workers.NightlyRollup}]}]}

unique: declares intent at the job level — same args + same queue within the period inserts nothing new, closing the double-enqueue race of hand-rolled queues. (Prefer the named groups like :all/:incomplete over hand-listing states — partial explicit lists are deprecated and now warn at compile time.) Oban.Testing makes workers deterministic in tests.

13.2 Broadway & GenStage — Backpressured Pipelines

GenStage is demand-driven producer/consumer flow control: consumers pull only what they can process, producers wait for credit. Broadway builds opinionated ingestion pipelines on top:

flowchart LR
    K["Kafka /<br/>SQS / RabbitMQ"] --> PR["Producer(s)<br/>buffer events"]
    PR -->|"demand-driven:<br/>consumers ask for N"| PROC["Processor stages<br/>concurrency × N<br/>per-message work"]
    PROC --> BAT["Batcher<br/>size 100 / timeout 50ms"]
    BAT --> SINK["Sink<br/>(DB bulk insert,<br/>API call, storage)"]
    PROC -.->|"slow consumer ⇒<br/>producer holds back"| PR

Use when consuming Kafka/SQS/RabbitMQ or fanning out heavy processing. Your message-passing instincts apply directly — demand is just credit-based pull across processes, the same accounting you’d hand-write with gen_stage’s Erlang port if there were one.

# deps: {:broadway_kafka, "~> 0.7"}
defmodule MyPipeline do
  use Broadway

  def start_link(_opts) do
    Broadway.start_link(__MODULE__,
      name: __MODULE__,
      producer: [
        module:
          {BroadwayKafka.Producer,
           hosts: [localhost: 9092], group_id: "demo", topics: ["events"]}
      ],
      processors: [default: [concurrency: System.schedulers_online() * 2]],
      batchers: [default: [batch_size: 100, batch_timeout: 50]]
    )
  end

  @impl true
  def handle_message(_processor, message, _ctx), do: message

  @impl true
  def handle_batch(_batcher, messages, _batch_info, _ctx) do
    Enum.each(messages, &persist/1)
    messages
  end
end

Reading the options as architecture: processors parallelize per-message work (validation, enrichment); batchers amortize expensive I/O over groups (bulk inserts). Backpressure flows automatically — no manual accounting.

The other half of Broadway is the handle_failed/2 callback, and it is where the broker differences bite:

@impl true
def handle_failed(messages, _ctx) do
  # Called with the messages that failed; you must return them (possibly
  # updated). Persist them here if you want to retry later — BroadwayKafka
  # always commits offsets, so a failure it does not handle is gone.
  Enum.each(messages, &persist_failure/1)
  messages
end

The callback is optional, but without it a failed batch is only logged and acknowledged. It must return the same list of messages it received; use Broadway.Message.configure_ack/2 if you need to change how each one is acknowledged. Design for the weakest broker guarantee you support.

Hand-Rolling GenStage: Demand Made Concrete

Writing one pair by hand makes the credit mechanics permanent knowledge:

defmodule Counter do
  use GenStage

  def start_link, do: GenStage.start_link(__MODULE__, 0, name: __MODULE__)

  @impl true
  def init(counter), do: {:producer, counter}

  @impl true
  def handle_demand(demand, counter) when demand > 0 do
    events = Enum.to_list(counter..(counter + demand - 1))
    {:noreply, events, counter + demand}   # emit only what was asked for
  end
end

defmodule Echo do
  use GenStage

  def start_link, do: GenStage.start_link(__MODULE__, :ok, name: __MODULE__)

  @impl true
  def init(:ok), do: {:consumer, :ok, subscribe_to: [{Counter, max_demand: 5}]}

  @impl true
  def handle_events(events, _from, state) do
    Process.sleep(Enum.random(10..100))    # uneven work…
    IO.inspect(length(events), label: "batch")
    {:noreply, [], state}                  # consumers emit no events onward
  end
end

Run it and batches like batch: 3, batch: 2, batch: 3 arrive, sized by consumer appetite: slow consumers pull less, producers sit idle holding events. max_demand/min_demand tune the credit window — the same knobs Broadway sets under processors: [concurrency: n]. Flow control is the message protocol itself.

Failure Strategies Across the Stack

ConcernObanBroadwayRaw GenStage
Retry unitwhole job, N attemptsmessage (ack/nack)yours to write
Backoffexponential+jitter per workerproducer-definedmanual
Poison messagesfailed job rows, inspectabledead-letter configmanual
Orderingper queuepartition_by groups relatedstage topology

Choose by ingestion shape: durable business work → Oban rows; continuous external feeds → Broadway; internal inter-stage flow you fully control → plain GenStage. Rate limiting differs accordingly — Oban throttles via queue concurrency and priorities; Broadway adds rate_limiting: [allowed_messages: n, interval: ms] on processors.

Ordering Guarantees: partition_by

Broadway’s concurrency destroys global ordering by design — twenty processors means twenty messages in flight. When related events must be processed in order (all state changes for one user), route them to the same processor with partition_by:

# the processors option of Broadway.start_link/2
[
  processors: [
    default: [
      concurrency: 20,
      partition_by: fn message ->
        message.data.user_id     # shape depends on your producer
      end
    ]
  ]
]

The routing key is hashed onto the processor indices (consistent hashing, :erlang.phash2-style): every event for one user_id lands on one processor and is handled serially in arrival order, while different users still spread across all twenty lanes. Three properties worth knowing before relying on it:

  1. Order holds per key, not globally — cross-user ordering is undefined; only events sharing a key are serialized.
  2. Hot keys create hot lanes — one chatty user throttles their own partition, but never anyone else’s. Pick keys that distribute traffic.
  3. Rescaling reshuffles keys — changing concurrency reassigns partitions; order guarantees hold within a running topology generation, which is why key design matters more than processor count.

You have written this pattern before by hand: hashing a key to pick one gen_server from a pool of registered workers. Broadway just made it a one-line option with the batching machinery already wired around it.

13.3 Explorer — DataFrames on the BEAM

Polars-backed DataFrames for Elixir. Fully runnable in Livebook with Mix.install([{:explorer, "~> 0.12"}]):

iex> require Explorer.DataFrame, as: DF
iex> alias Explorer.Series, as: S

iex> df = DF.new(name: ["ada", "grace", "alan"], age: [36, 45, 41])

# filter + project — Series ops run vectorized in Rust, not row-by-row in Elixir
iex> df |> DF.filter(age > 40) |> DF.pull(:name)
#Explorer.Series<
  Polars[2]
  string ["grace", "alan"]
>

iex> df |> DF.summarise(mean_age: S.mean(age))

The query macros import the Explorer.Series operations, so inside DF.filter/DF.summarise both mean(age) and S.mean(age) resolve age to the column. Outside a query you hold a real series and call S.mean(df["age"]) directly. Use col/1 for a column name that is not a valid identifier:

df
|> DF.group_by(:city)
|> DF.summarise(mean_age: mean(col("age")))

Mental model: DataFrame/Series operations describe transformations; Polars executes them columnar and lazy where possible. You get pandas-class ergonomics with Rust-class throughput without leaving the notebook.

Explorer vs Enum: Choosing and Combining

The same aggregation in two worlds:

# Enum: element-wise over BEAM lists, a pass per transformation:
mean = rows |> Enum.map(& &1.age) |> Enum.sum() |> Kernel./(length(rows))

# Explorer: columnar, vectorized, fused by Polars — one pass, grouped:
df
|> DF.group_by(:city)
|> DF.summarise(mean_age: S.mean(age), n: S.count(age))

Decision guidance:

  • Under ~100k rows, irregular shapes, one-off scripts → Enum; conversion overhead exceeds the vectorization gain.
  • Tabular data at millions of rows, group/join/sort-heavy → Explorer; lists that size thrash memory long before Polars blinks.
  • Mixed pipelines are normal: Explorer aggregates, DF.to_rows/2 hands off to ordinary Elixir for domain logic.

Both stay inside the VM — no NIF-bound copies out to Python, no serialization boundary crossed mid-analysis.

Pairs well with Livebook exploration (Ch 15) and Nx feature pipelines (Part IV).

13.4 Scholar — Traditional ML on Tensors

Explorer covers dataframes; Scholar covers the scikit-learn niche — clustering, trees, preprocessing, metrics — implemented as defn functions, so everything runs on the same backends as Nx (Ch 17–18):

Mix.install([{:scholar, "~> 0.4"}, {:nx, "~> 0.13"}])

# Three synthetic clusters:
key = Nx.Random.key(42)
{c1, key} = Nx.Random.normal(key, 0.0, 1.0, shape: {50, 2})
{c2, key} = Nx.Random.normal(key, 5.0, 1.0, shape: {50, 2})
{c3, _key} = Nx.Random.normal(key, 10.0, 1.0, shape: {50, 2})
x = Nx.concatenate([c1, c2, c3], axis: 0)

model = Scholar.Cluster.KMeans.fit(x, num_clusters: 3, key: Nx.Random.key(1))
labels = Scholar.Cluster.KMeans.predict(model, x)
Module familyGives you
Scholar.ClusterK-means, DBSCAN
Scholar.Linearlinear/logistic regression
Scholar.Metrics.Classificationaccuracy, precision/recall/F1, ROC-AUC
Scholar.Preprocessingscalers, PCA, encoding

Pin your Scholar version and check the module list before writing the call — coverage is narrower than scikit-learn’s (there is no decision-tree or random-forest module) and the mix is more spread out than the table suggests. Treat this table as “what families exist”, not “what functions exist”.

The One You Will Ask About: Flow

The most common question from Erlang developers choosing among these is “what about in-VM parallelism without a broker?” That is Flow, and it is a third answer to the same question Oban and Broadway answer:

# Flow: data-parallel word count across cores, no broker
"big.log"
|> File.stream!()
|> Flow.from_enumerable()
|> Flow.partition(stages: System.schedulers_online())
|> Flow.map(&String.trim/1)
|> Flow.reduce(fn -> %{} end, fn line, acc ->
  Map.update(acc, line, 1, &(&1 + 1))
end)
|> Enum.to_list()
ObanBroadwayFlow
Moves work…through Postgresthrough a brokerthrough the VM
DurabilityPostgres-backedbroker acksnone — crash loses it
Use whenjobs must survive restartexternal producers/consumersa batch fits in memory

Flow has no persistence at all. It is the right tool for a nightly batch that can be re-run and the wrong tool for anything a user is waiting on.

The mental slot it fills: when a task is “classic ML” — tabular features, a few thousand rows, a metric to report — you no longer reach for Python. Same tensors, same backends, same supervision tree; results come back as ordinary Nx.Tensors that pipe into Explorer summaries or Ecto persistence without crossing any serialization boundary.

13.5 The Composable Stack

One application typically assembles these pieces side by side:

flowchart TD
    APP["Your Application"] --> PLUG["Plug<br/>HTTP middleware"]
    APP --> DATA["Ecto / Ash<br/>data access"]
    APP --> JOBS["Oban<br/>background jobs"]
    APP --> FLOW["Broadway / GenStage<br/>ingestion pipelines"]
    APP --> MORE["domain-specific:<br/>Absinthe (GraphQL)<br/>Membrane (media)<br/>Reactor, Jido (Ch 14)"]

You compose libraries; you don’t inherit from a framework base class.

Ecosystem map at a glance:

DomainLibraries
WebPhoenix, LiveView, Channels, Hologram
DataEcto (Ch 11), Ash (Ch 12), Broadway, Explorer
Background jobsOban, Quantum
Orchestration & agentsReactor, Jido (Ch 14)
IoT / EdgeNerves, AtomVM (Ch 16)
MobileMob, Dala (emerging)
AI / NumericalNx, Axon, Scholar (Part IV)
Interactive devLivebook (Ch 15)
MediaMembrane

From Erlang you know: each library above is an OTP application with a supervision tree. Start them in your child list, observe them in Observer, debug them like any process.

Explore More

  • Oban guide — unique jobs, cron plugin, priorities, and testing helpers (Oban.Testing)
  • GenStage documentation — read the demand model explanation; it’s the best tutorial on credit-based flow
  • Broadway guides — batching strategies, graceful shutdown, rate limiting, and Off-Broadway producers
  • Explorer cheatsheet — DataFrame ops side-by-side with dplyr/pandas equivalents
  • Exercise idea: build a mini pipeline — Oban enqueues synthetic events, a GenStage producer streams them into a Broadway batcher, and the sink writes into Explorer for a Livebook chart

Checkpoint

  1. Why does Oban not need Redis?
  2. What mechanism gives Broadway its backpressure?
  3. When would you pick Explorer over plain Enum pipelines?
  4. How do you keep all events for one user in order under Broadway’s concurrency?
  5. What does Scholar run on, and what comes back from a fit/predict call?
Answers
  1. Jobs live in your relational DB (Postgres), transactional with app data; workers are ordinary supervised processes.
  2. GenStage demand: consumers pull only what they can process, producers wait for credit — slow downstream automatically throttles upstream.
  3. When data is tabular/larger-than-memory or you want vectorized columnar performance — Enum works element-wise on lists in BEAM memory.
  4. Set a partition_by on the processors — all messages sharing that key hash onto the same processor and run serially in arrival order.
  5. It runs as defn functions on the same Nx backends (BinaryBackend/ EXLA/EMLX); fit/3 returns a model struct and predict/2 returns ordinary tensors — no boundary crossing to Python.

Next: Chapter 14 — High-Level Process Frameworks