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 15 — Livebook

Livebook is the Jupyter-like environment for Elixir — notebooks + docs + executable code + data + ML, all backed by a live BEAM runtime. For an Erlang developer it doubles as something more interesting: a remote control for running production nodes.

15.1 Setup

# macOS
brew install livebook

# Or via mix
mix escript.install hex livebook

livebook server          # open http://localhost:8080

New notebooks start blank; open any existing .livemd via “Open” → file, or “Open from URL” with a raw GitHub link — many ecosystem projects ship notebooks you can load straight from their repositories this way.

15.2 Basics in Two Minutes

  1. Cells — markdown cells and Elixir cells. Evaluate with ▶ or Shift+Enter.
  2. Run in order — later cells depend on earlier ones (Mix.install, variables, loaded models).
  3. First cell is Mix.install/2 — downloads and compiles dependencies into the notebook’s own environment. First evaluation is slowest.
Mix.install([
  {:nx, "~> 0.13"},
  {:kino, "~> 0.19"}
])
  1. Evaluate all — one button, top to bottom.
  2. Restart — needed after switching backends or dependency conflicts.
ActionHow
Evaluate cellClick ▶ or Shift+Enter
Evaluate all“Evaluate all” (top-right)
Insert cellHover between cells → +
Add text cell+ → Markdown
Notebook infoCtrl/Cmd+J

The Session Is One Dependency Graph

All cells in a notebook evaluate in one BEAM session, top to bottom: Mix.install/1 pins dependencies, bindings persist, module definitions overwrite. Out-of-order evaluation is real — a cell can run against stale bindings until you re-run its ancestors. Sections are visual groupings, not isolation boundaries; when experiments fork, prefer a second session or a duplicated notebook over clever cell ordering.

Smart Cells: GUI In, Source Code Out

Smart cells are point-and-click generators — database connections, charts, forms — and clicking the </> icon reveals the Elixir they emitted. Nothing is hidden: the result is ordinary code you edit afterward. They double as teaching devices: the fastest way to learn the idiomatic incantation for a library you haven’t memorized yet.

15.3 Four Modes in One Tool

flowchart TD
    LB["Livebook"] --> LEARN["Learn<br/>Elixir · OTP · Phoenix"]
    LB --> EXPLORE["Explore<br/>data · SQL · APIs"]
    LB --> BUILD["Build<br/>Nx · models"]
    LB --> OPERATE["Operate<br/>attach to live nodes"]
    style OPERATE fill:#e8f5e9
  • Learn — mix Markdown, Mermaid/GraphViz diagrams, and runnable code; an increasing share of ecosystem documentation ships as Livebooks for exactly this reason.
  • Explore — datasets, tensors, APIs, VegaLite charts, Kino tables.
  • Build — prototype Nx/Axon/Bumblebee workflows before promoting them into Mix projects.
  • Operate — connect to running BEAM systems and inspect them live.

15.4 Kino: Rich Outputs

# Tables
Kino.DataTable.new([
  %{name: "Phoenix", domain: "Web", maturity: "Production"},
  %{name: "Nerves", domain: "Edge/IoT", maturity: "Production"},
  %{name: "Nx", domain: "AI/ML", maturity: "Active"}
])

# Charts
alias VegaLite, as: Vl

Vl.new(width: 400, height: 300)
|> Vl.data_from_values(x: 1..10, y: Enum.map(1..10, &(&1 * &1)))
|> Vl.mark(:line)
|> Vl.encode_field(:x, "x", type: :quantitative)
|> Vl.encode_field(:y, "y", type: :quantitative)

# Process inspection
# Kino.Process.render supervisor tree / app graph

Kino.Process.render_sup_tree(MyApp.Supervisor) draws what Ch 05 taught you to read, straight from the live node — supervision trees as diagrams, not :sys.get_state dumps.

Note the chart pipeline returns a spec; the last step must hand it to Kino.VegaLite.new/1 (or Kino.VegaLite.window/1) for anything to display. And data_from_values needs real lists — a 1..10 range is not enumerable data here:

xs = Enum.to_list(1..10)

Vl.new(width: 400, height: 300)
|> Vl.data_from_values(x: xs, y: Enum.map(xs, &(&1 * &1)))
|> Vl.mark(:line)
|> Vl.encode_field(:x, "x", type: :quantitative)
|> Vl.encode_field(:y, "y", type: :quantitative)
|> Kino.VegaLite.new()

15.5 The Killer Feature for Erlang Devs: Operate Mode

Livebook can attach to a running node (same cookie):

  1. Start your release with the distribution port enabled.
  2. In Livebook: “Connect to an existing node” → enter app@host.
  3. Every notebook cell now evaluates on production, supervised by your app:
# Running against prod:
Process.whereis(MyApp.Repo) |> :sys.get_state()
Kino.Process.render_sup_tree(App.Supervisor)     # supervision tree as a diagram
:sys.get_state(MyApp.Worker)                     # any process's state, rendered

Not :observer.start() here — Observer is a desktop GUI, and running it via this path tries to open it on the server, which is usually headless. The notebook-native equivalents are the Kino calls above; for the real Observer, start it on your workstation and Node.connect/1 from there (Ch 27 covers :observer_cli and :etop for terminals).

This replaces a whole category of remote-shell debugging sessions with shareable, re-runnable runbooks. A crash investigation becomes a saved notebook.

Connection Mechanics: Cookies and Distribution

“Connect to an existing node” performs ordinary Erlang distribution — Node.connect/1 under the hood, gated by the cookie:

%% the handshake Livebook performs, from an Erlang shell:
erlang:set_cookie(node(), mysecret).
net_adm:ping('app@10.0.0.7').     %% => pong | pang

Production hygiene transfers unchanged: distinct cookie per environment, distribution ports firewalled or tunneled (Livebook over an SSH tunnel is the standard remote pattern). And remember every cell executes with production privileges — treat notebooks like deploy scripts: reviewed, versioned, never ad-hoc.

Secrets: Credentials Without Commits

The notebook sidebar stores secrets (API keys, DB URLs) per user; cells read them as LB_-prefixed environment variables:

token = System.fetch_env!("LB_GITHUB_TOKEN")

Secrets never appear in notebook text, so .livemd files stay commit-safe — the same discipline as runtime.exs env lookups (Ch 09), one level down.

15.6 Executable Knowledge

Markdown + Code + Data + Visualization + Runtime = executable knowledge

The intended learning loop: read a chapter here, prototype its ideas in a scratch notebook, tweak cells until the concepts click, then keep your annotated copy. Notebooks you save after an incident become the next engineer’s debugging runbook — institutional memory that actually executes.

A Runbook in Five Lines

Kino controls turn notebooks into interactive ops tools — inputs, buttons, and outputs wired to whatever the incident needs:

threshold = Kino.Input.number("Queue depth threshold", default: 500)
run = Kino.Control.button("Audit queues")

Kino.listen(run, fn _event ->
  for {queue, len} <- MyApp.Oban.audit(),
      len > Kino.Input.read(threshold) do
    IO.puts("#{queue}: #{len} pending — investigating")
  end
end)

Click the button during an incident; the notebook remembers the parameters afterward. Compare with scrolling a shell history nobody can rerun.

15.7 Livebook Apps: The Reason Teams Keep It

A notebook you run is a debugging tool. A notebook with inputs and buttons, deployed as a small internal app, is a tool other people use without knowing Elixir. From the File menu: “Deploy as App” turns the current notebook into a standalone web app — form inputs, buttons, rendered outputs, no Livebook UI. Commit the .livemd beside your code and the “app” is reviewable in a pull request like anything else.

The pattern that pays off operationally:

# inputs cell — typed parameters the user fills in
range = Kino.Input.select("window", ["1h", "24h", "7d"], default: "24h")

# button cell — runs the real code path, no notebook required to read it
Kino.Control.button("Run report")
|> Kino.listen(fn _event ->
  case Reports.generate(Kino.Input.read(range)) do
    {:ok, path} -> Kino.Markdown.new("Wrote `#{path}`")
    {:error, e}  -> Kino.Markdown.new("**Failed:** #{Exception.message(e)}")
  end
end)

The result is a deployable internal tool: run a backfill, regenerate a report, trigger a reindex — by someone who has never opened IEx. That progression (script → notebook → deployed app) is the argument for Livebook in a team, and it is the reason to keep .livemd files in version control rather than in a personal scratch directory.

Explore More

  • Livebook docs — including desktop app and Teams features for shared deployments
  • Kino docs — every widget: tables, terminals, forms, process diagrams
  • Smart cells — no-code cells that generate Elixir for DB connections, charts, and more
  • Exercise idea: attach a Livebook to iex --sname dev on your machine, run Kino.Process.render_sup_tree(MyApp.Supervisor), and keep the notebook as your first ops runbook

Checkpoint

  1. What does Mix.install/2 do and why does the first cell matter?
  2. How do you point Livebook at a production node safely?
  3. What are the four modes?
Answers
  1. Installs+compiles deps into the notebook’s isolated Mix env; everything downstream depends on it, so it must evaluate first.
  2. Set matching Erlang cookie on both sides, use “connect to existing node”; treat connected sessions as privileged operations (they execute on prod).
  3. Learn, Explore, Build, Operate.

Next: Chapter 16 — Edge, IoT & Mobile