Skip to content
LumenaryAcademy
Foundations 45 min

Getting started with Elixir

Where Elixir came from, why it runs on the Erlang virtual machine, and your first programs in scripts, iex and Mix.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Why Elixir exists

Imagine you are responsible for a service that a million people use at the same moment: a messaging app, a ride-sharing dispatcher, a system that watches thousands of sensors on farms in Kenya or in factories in Brazil. Three things are true about such a system.

First, it is concurrent: thousands of independent conversations happen at once, and each should feel as if it has the machine to itself. Second, things will go wrong: a malformed message arrives, a disk fills up, a remote service times out, a programmer misses an edge case. Third, it should keep running anyway: one user's bad request must not take down everyone else, and ideally the broken piece should repair itself and carry on.

Most languages treat those three needs as add-ons. You reach for a thread pool, a message queue, a process manager that restarts your server when it dies, and a great deal of careful defensive code. Elixir starts from the other end. It runs on the BEAM, the virtual machine built by Ericsson for Erlang, a language designed in the 1980s for telephone exchanges that were expected to run for years without stopping. On the BEAM, a program is made of many small, isolated processes (not operating-system processes, but very light ones managed by the virtual machine) that share nothing and talk only by sending messages. If one fails, it fails alone, and another process whose job is to watch it can start a fresh copy.

Elixir keeps all of that and adds a modern, approachable language on top: a clean syntax, documentation built into the language, a build tool and package manager from the first day, macros that let libraries extend the language, and a type checker that finds bugs without asking you to write type annotations. People use it for web applications and APIs, real-time features (chat, live dashboards, multiplayer games), data pipelines, embedded devices and, increasingly, numerical computing and machine learning.

This course teaches you to write Elixir the way experienced teams do. In this first lesson you will install it, run your first programs, and get a feel for the pieces you will use every day.

History & global context

From Ericsson's switches to Elixir

Elixir's story starts with Erlang. In 1986 Joe Armstrong, soon joined by Robert Virding and Mike Williams, began designing a language at Ericsson's Computer Science Laboratory in Sweden for programming telephone switches. Those systems had unusual requirements: huge numbers of simultaneous calls, hardware that fails, and software that must be upgraded while calls are in progress. The answers they found (lightweight processes, message passing, "let it crash" error handling and code that can be replaced while it runs) became Erlang and its virtual machine. In 1998 Ericsson released Erlang as open source, together with OTP, a library of battle-tested building blocks for servers and supervisors. Armstrong's paper A history of Erlang, linked at the end of this lesson, tells that story in his own words, and the Erlang course on this site teaches the language itself.

Fast forward to 2011. José Valim, a Brazilian developer then working at the consultancy Plataformatec and a member of the Ruby on Rails core team, wanted a language that made it easy and safe to use every core of a modern machine. He admired the BEAM but wanted more for everyday productivity: a friendlier syntax, first-class documentation, macros, polymorphism through protocols, and one standard build tool. He started Elixir, and its first public releases appeared in 2012. Elixir 1.0 arrived in September 2014, and with it a promise of backwards compatibility across the 1.x line that the project has kept ever since.

Elixir was never meant to replace Erlang. Both compile to the same bytecode, and an Elixir program can call any Erlang library directly, as you will see below. The web framework Phoenix, the embedded-systems platform Nerves, and the numerical library Nx with its notebook companion Livebook widened what people build with it.

The newest chapter is the type system. Starting in 2022, the Elixir team worked with researchers at the French national research centre CNRS on a gradual set-theoretic type system designed for the way Elixir code is actually written. It began shipping in Elixir 1.17 in 2024 and has grown with every release since; in Elixir 1.20 (June 2026), the version this course was checked against, it infers types for the functions you write without any annotations. You will meet it properly in Structs, protocols and types.

DefinitionsH

The BEAM, OTP and the tools you install

A few names come up constantly in Elixir, and it helps to separate them early.

Definition— BEAM

The BEAM is the virtual machine that runs Erlang and Elixir code. It schedules huge numbers of lightweight processes across all CPU cores, gives each process its own small heap and garbage collector, and switches between them preemptively so that no single process can hog a core. Since Erlang/OTP 24 it translates bytecode to native machine code when it loads it (a just-in-time compiler).

Definition— OTP

OTP (originally the "Open Telecom Platform", now simply OTP) is the Erlang distribution: the virtual machine, the standard libraries, and a set of design patterns called behaviours for servers, supervisors and applications. "Erlang/OTP 29" names a version of the whole bundle. Elixir uses OTP directly and wraps its most important parts in Elixir modules such as GenServer and Supervisor.

When you install Elixir you get four commands:

CommandWhat it does
elixirruns an Elixir script: elixir hello.exs
iexInteractive Elixir, a shell where you type expressions and see their values
elixirccompiles .ex files to .beam bytecode files (you will rarely call it yourself)
mixthe build tool: creates projects, compiles, runs tests, fetches packages, formats code

Elixir needs Erlang/OTP underneath. The official installation page lists the options: an installer for Windows, Homebrew on macOS, distribution packages or prebuilt archives on Linux, and Docker images. Many professionals use a version manager such as asdf or mise so that each project can pin its own Elixir and Erlang versions. Elixir 1.20 requires Erlang/OTP 27 or later.

Once installed, ask for the versions. Here is what the toolchain used for this course printed (the numbers in square brackets describe the machine, so yours will differ):

text
$ elixir --version
Erlang/OTP 29 [erts-17.1.1] [source] [64-bit] [smp:20:20] [ds:20:20:10] [async-threads:1] [jit:ns]

Elixir 1.20.5 (compiled with Erlang/OTP 29)

The first line is the BEAM introducing itself: smp:20:20 means it started 20 schedulers, one per CPU core it found, and jit means the just-in-time compiler is on. The second line is Elixir, which is itself mostly written in Elixir and compiled to BEAM bytecode.

Worked examplesH

Your first programs

Create a file called hello.exs with one line in it, and run it with elixir hello.exs:

elixir
IO.puts("Hello, world!")

It prints:

text
Hello, world!

IO is a module, a named group of functions, and puts is a function in it that writes a string and a newline to standard output. The dot connects them: IO.puts means "the puts function of the IO module". The parentheses around the argument are optional in many places (IO.puts "Hello" works too), but the community style, and the formatter you will meet later, keeps them for ordinary calls.

Strings go in double quotes and are UTF-8 text. Inside a string, #{...} evaluates any expression and inserts its value; this is called interpolation. To look at a value as Elixir code, with quotes, brackets and all, use IO.inspect. It prints the value and then returns it unchanged, which makes it a convenient probe you can drop into the middle of a computation:

elixir
name = "Amara"
languages = ["Elixir", "Erlang", "Gleam"]

IO.puts("Hello, #{name}!")
IO.puts("The BEAM runs #{length(languages)} languages in this list.")

IO.inspect(languages)
IO.inspect({:ok, 42}, label: "result")

doubled = IO.inspect(21, label: "before") * 2
IO.puts("after: #{doubled}")

It prints:

text
Hello, Amara!
The BEAM runs 3 languages in this list.
["Elixir", "Erlang", "Gleam"]
result: {:ok, 42}
before: 21
after: 42

A few things to notice. name = "Amara" binds a variable; there is no keyword such as let or var. ["Elixir", "Erlang", "Gleam"] is a list. {:ok, 42} is a tuple containing the atom :ok and the integer 42; atoms are constants whose value is their own name, and you will see {:ok, value} and {:error, reason} everywhere in Elixir. label: is a keyword argument giving IO.inspect an option. Finally, IO.inspect(21, label: "before") * 2 printed 21 and still computed 42, because IO.inspect returned its argument.

Now a slightly bigger program. It defines a module with a function, calls an Erlang library function directly, and gives a first taste of processes:

elixir
defmodule Greeter do
  def hello(name), do: "Hello, #{name}!"
end

IO.puts(Greeter.hello("Kenji"))

# Erlang modules are atoms such as :math; Elixir calls them directly.
IO.puts(:math.sqrt(2))

# Start a second process that sends us a message, then wait for it.
parent = self()
spawn(fn -> send(parent, {:greeting, Greeter.hello("another process")}) end)

receive do
  {:greeting, text} -> IO.puts(text)
end

It prints:

text
Hello, Kenji!
1.4142135623730951
Hello, another process!

defmodule creates a module named Greeter, and def defines a public function inside it. :math.sqrt(2) calls the sqrt function of Erlang's math module: in Elixir, Erlang modules are written as atoms. The last part uses three functions you will study in Processes and messages: self() returns the identifier of the running process, spawn starts a new process running the given function, and send puts a message in a process's mailbox. receive waits until a message matching one of its patterns arrives.

How cheap are processes? Cheap enough that starting a hundred thousand of them is an ordinary thing to do:

elixir
parent = self()

for i <- 1..100_000 do
  spawn(fn -> send(parent, i * i) end)
end

total =
  Enum.reduce(1..100_000, 0, fn _, sum ->
    receive do
      square -> sum + square
    end
  end)

IO.puts("Sum of the first 100,000 squares: #{total}")

It prints:

text
Sum of the first 100,000 squares: 333338333350000

Each process computes one square, sends it to the parent and ends. The parent receives exactly 100,000 messages and adds them up. The messages arrive in whatever order the processes happen to finish, but addition does not care. On a laptop this runs in well under a second: a fresh BEAM process needs a couple of kilobytes of memory, where an operating-system thread typically reserves megabytes for its stack. (Underscores in 100_000 are just digit separators.) Integers in Elixir never overflow; they grow as large as needed.

ComputationC

Exploring in iex

For trying things out, the interactive shell is faster than editing a file. Type iex in a terminal; it prints the same BEAM banner and then waits for input. Here is a short session from the toolchain used for this course, with each result exactly as iex printed it:

text
iex(1)> 40 + 2
42
iex(2)> "Elixir" <> " runs on the BEAM"
"Elixir runs on the BEAM"
iex(3)> String.length("naïve")
5
iex(4)> byte_size("naïve")
6
iex(5)> Enum.map([1, 2, 3], fn x -> x * 10 end)
[10, 20, 30]
iex(6)> self()
#PID<0.105.0>

<> joins two strings. String.length counts the characters a reader sees, while byte_size counts bytes; they differ because "ï" takes two bytes in UTF-8. fn x -> x * 10 end is an anonymous function. And self() shows the identifier of the shell's own process: the shell is just another process on the BEAM.

Three shell helpers are worth learning on the first day:

  • h shows documentation: h String.length or h Enum. The docs live inside the compiled modules, so they are always the ones for your installed version.
  • i describes a value: i "naïve" tells you its type, its raw bytes and which protocols it implements.
  • recompile reloads your project's code after you edit it, when you started the shell inside a project with iex -S mix.

To leave the shell press Ctrl+C twice (or Ctrl+\). If an expression is incomplete, say you opened a parenthesis and pressed Enter, iex waits for more input; type #iex:break on its own line to abandon it; iex reports the unfinished expression as an error and gives you a fresh prompt.

ExplanationH

Scripts, compiled modules and Mix projects

Elixir code lives in two kinds of file, and the difference is a convention that the tools respect:

  • .exs files are scripts. elixir file.exs compiles them in memory and runs them immediately; nothing is written to disk. Tests and configuration files are scripts, and so is every complete program in this course.
  • .ex files are compiled. They normally contain modules, and the compiler turns each module into a .beam file that the virtual machine can load later. Your application's code lives in .ex files.

Real projects are built with Mix. mix new greeter creates a project skeleton; this is what it printed for us:

text
$ mix new greeter
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating lib
* creating lib/greeter.ex
* creating test
* creating test/test_helper.exs
* creating test/greeter_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd greeter
    mix test

Run "mix help" for more commands.

mix.exs describes the project: its name, version, the Elixir version it requires, and its dependencies. lib/ holds the code, test/ the tests, and .formatter.exs configures mix format, the official code formatter. Inside the project, mix compile builds it, mix test runs the tests, mix run runs it, and iex -S mix opens a shell with the whole project loaded, which is how many Elixir developers work: write a function in the editor, recompile in the shell, try it, repeat. You will build a full Mix project in the final lesson.

A note on style that will save you trouble later: Elixir modules are named in CamelCase (Greeter, MyApp.Accounts), while functions and variables use snake_case (hello_world, user_id). Files are named after the module in snake case: lib/my_app/accounts.ex. Indentation is two spaces. You never need to argue about any of it, because mix format decides.

Common misconceptionsH

Common first misunderstandings

Misconception

"Elixir is Ruby running on Erlang." The syntax borrows some friendliness from Ruby (do ... end blocks, optional parentheses), but the semantics are entirely different: values are immutable, there are no classes or objects, and the unit of concurrency is the process. Expecting Ruby behaviour, such as changing a list in place, leads straight to confusion.

Misconception

"A process is an operating-system process or thread." BEAM processes are managed by the virtual machine, not the operating system. They are created in microseconds, start with a couple of kilobytes of memory, and a single BEAM can run millions of them. The BEAM runs one scheduler thread per core and multiplexes processes onto them.

Misconception

"Being functional makes it slow." Immutable data is not copied wholesale on every change; new versions share structure with old ones. The BEAM is not the fastest platform for raw number crunching (for that, Elixir teams call into native code or use Nx, which compiles numerical code for CPUs and GPUs), but it is very good at what most servers spend their time doing: juggling many concurrent, mostly waiting, tasks with predictable latency.

Note

You will sometimes see Elixir described as "dynamically typed" and sometimes as having a type system. Both are true: values carry their types at run time, and since 1.17 the compiler also infers and checks types as it compiles, warning about code that is certain to fail. The program still runs if you ignore the warning, which is what "gradual" means here.

Exercises

Exercises

1. Getting started with Elixir

Warm-upHuman

You have saved a program in report.exs. Which command runs it?

Choose one

2. Getting started with Elixir

Warm-upHuman

Which statement best describes the BEAM?

Choose one

3. Getting started with Elixir

Warm-upComputational

What does this program print?

count = 3
IO.puts("#{count * 2} cups of tea")

4. Getting started with Elixir

CoreComputational

This program prints two lines. What number is on the second line?

x = IO.inspect(4, label: "x") * 10
IO.puts(x + 1)

5. Getting started with Elixir

CoreComputational

String.length("São Paulo") returns 9. What does byte_size("São Paulo") return?

6. Getting started with Elixir

CoreComputational

Erlang's math module has a function pow/2 that raises a number to a power and always returns a float. What does IO.inspect(:math.pow(2, 10)) print?

7. Getting started with Elixir

StretchHuman

Which of these statements are true? List their letters.

  • A: .exs files are compiled in memory and run; no .beam file is written.
  • B: In a Mix project, application code normally lives in .ex files under lib/.
  • C: Tests in a Mix project are .exs scripts.
  • D: iex -S mix opens a shell with the project's code loaded.
  • E: A BEAM process is an operating-system thread.

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

Further reading and resources

  • Install ElixirOfficial instructions for every operating system, including installers that bring Erlang/OTP with them.
  • Getting started: IntroductionThe first chapter of the official guide, with notes on iex and running scripts.
  • Elixir documentationThe standard library reference; every module mentioned in this course is documented here.
  • Introduction to MixThe official guide's walk through creating and testing a Mix project.
  • A history of Erlang · Joe Armstrong · 2007The HOPL III paper on where the BEAM's ideas came from.
  • LivebookInteractive Elixir notebooks, a comfortable place to experiment.