Elixir Idioms
Reference for writing idiomatic Elixir code with BEAM-aware patterns.
Iron Laws — Never Violate These
- NO PROCESS WITHOUT A RUNTIME REASON — Processes model concurrency, state, isolation—NOT code structure
- MESSAGES ARE COPIED — Keep messages small (except binaries >64 bytes)
- GUARDS USE
and/or/not — Never use short-circuit operators in guards (guards require boolean operands)
- CHANGESETS FOR EXTERNAL DATA — Use
cast/4 for user input, change/2 for internal
- RESCUE ONLY FOR EXTERNAL CODE — Never use rescue for control flow
- NO DYNAMIC ATOM CREATION —
String.to_atom(user_input) causes memory leak (atoms aren't GC'd)
- @external_resource FOR COMPILE-TIME FILES — Modules reading files at compile time MUST declare
@external_resource
- SUPERVISE ALL LONG-LIVED PROCESSES — Never bare
GenServer.start_link/Agent.start_link in production. Use supervision trees
- WRAP THIRD-PARTY LIBRARY APIs — Always facade external deps behind a project-owned module. Enables swapping without touching callers
- MIX TASKS START ONLY WHAT THEY NEED —
Mix.Task.run("app.config") + Application.ensure_all_started/1, never Mix.Task.run("app.start") (boots the FULL tree: endpoint port, Oban consuming)
- CAPTURE LOCALE BEFORE SPAWNING — Gettext/CLDR locale is process-local. Read it in the caller and pass explicitly; a spawned Task/GenServer starts with the default locale
BEAM Architecture (Why Elixir Works This Way)
- Processes are cheap (2.6KB) — Spawn liberally for concurrency/isolation
- Complete memory isolation — No shared state, no locks needed
- Messages are copied (except binaries >64 bytes) — Keep messages small
- Per-process GC — No global GC pauses
- "Let it crash" — Supervisors restart to known-good state
Core Principles
- Pattern match over conditionals — Function heads first, then
case, then cond
- Tagged tuples for expected failures —
{:ok, _}/{:error, _} for expected errors, raise for bugs
- Pipe operator for data transformation — Start with data, never pipe single calls
- Let it crash — Handle expected errors, crash on unexpected ones
- Explicit over implicit — Be clear about intentions
Quick Decision Trees
Control Flow
Need patterns? → case (or function heads)
Multiple operations? → with
Boolean conditions? → cond (multiple) or if (single)
Error Handling
Expected failure? → {:ok, _}/{:error, _} tuples
Unexpected/bug? → raise exception (let supervisor handle)
External library? → rescue (only here!)
OTP
Need state?
├─ No → Plain functions
├─ Simple get/update → Agent or ETS
├─ Complex messages/timeouts → GenServer
└─ One-off async → Task
Quick Patterns
# Pattern match in function head
def process(%{status: :active} = user), do: activate(user)
def process(%{status: :inactive} = user), do: deactivate(user)
# with for happy path
with {:ok, user} <- get_user(id),
{:ok, order} <- create_order(user) do
{:ok, order}
end
# Task for async
Task.Supervisor.async_nolink(TaskSup, fn -> work() end)
|> Task.yield(5000) || Task.shutdown(task)
Common Pitfalls
| Wrong |
Right |
length(list) == 0 |
list == [] or Enum.empty?(list) |
list ++ [item] |
[item | list] |> Enum.reverse() |
String.to_atom(input) |
String.to_existing_atom(input) |
spawn(fn -> log(conn) end) |
ip = conn.ip; spawn(fn -> log(ip) end) |
unless condition |
if !condition (unless deprecated in 1.18) |
References
For detailed patterns, see:
references/pattern-matching.md - Pattern matching, guards, binary matching
references/otp-patterns.md - GenServer, Supervisor, Task, Registry
references/error-handling.md - Tagged tuples, rescue, with
references/with-and-pipes.md - When to use with and |> (idiomatic patterns)
references/troubleshooting.md - Production BEAM debugging (memory, performance, crashes)
references/anti-patterns.md - Common mistakes and fixes
references/mix-tasks.md - Mix task naming, option parsing, shell output
references/elixir-118-features.md - Duration module, dbg improvements (1.18+)
references/elixir-120-type-system.md - Gradual type checker, dynamic(), verified bugs as compile warnings (1.20+, OTP 27+)
1---2name: elixir-idioms3description: OTP/BEAM patterns and Elixir idioms — GenServer, Supervisor, Task; Use when designing processes or debugging BEAM…4---56# Elixir Idioms78Reference for writing idiomatic Elixir code with BEAM-aware patterns.910## Iron Laws — Never Violate These11121. **NO PROCESS WITHOUT A RUNTIME REASON** — Processes model concurrency, state, isolation—NOT code structure132. **MESSAGES ARE COPIED** — Keep messages small (except binaries >64 bytes)143. **GUARDS USE `and`/`or`/`not`** — Never use short-circuit operators in guards (guards require boolean operands)154. **CHANGESETS FOR EXTERNAL DATA** — Use `cast/4` for user input, `change/2` for internal165. **RESCUE ONLY FOR EXTERNAL CODE** — Never use rescue for control flow176. **NO DYNAMIC ATOM CREATION** — `String.to_atom(user_input)` causes memory leak (atoms aren't GC'd)187. **@external_resource FOR COMPILE-TIME FILES** — Modules reading files at compile time MUST declare `@external_resource`198. **SUPERVISE ALL LONG-LIVED PROCESSES** — Never bare `GenServer.start_link`/`Agent.start_link` in production. Use supervision trees209. **WRAP THIRD-PARTY LIBRARY APIs** — Always facade external deps behind a project-owned module. Enables swapping without touching callers2110. **MIX TASKS START ONLY WHAT THEY NEED** — `Mix.Task.run("app.config")` + `Application.ensure_all_started/1`, never `Mix.Task.run("app.start")` (boots the FULL tree: endpoint port, Oban consuming)2211. **CAPTURE LOCALE BEFORE SPAWNING** — Gettext/CLDR locale is process-local. Read it in the caller and pass explicitly; a spawned Task/GenServer starts with the default locale2324## BEAM Architecture (Why Elixir Works This Way)2526- **Processes are cheap (2.6KB)** — Spawn liberally for concurrency/isolation27- **Complete memory isolation** — No shared state, no locks needed28- **Messages are copied** (except binaries >64 bytes) — Keep messages small29- **Per-process GC** — No global GC pauses30- **"Let it crash"** — Supervisors restart to known-good state3132## Core Principles33341. **Pattern match over conditionals** — Function heads first, then `case`, then `cond`352. **Tagged tuples for expected failures** — `{:ok, _}`/`{:error, _}` for expected errors, raise for bugs363. **Pipe operator for data transformation** — Start with data, never pipe single calls374. **Let it crash** — Handle expected errors, crash on unexpected ones385. **Explicit over implicit** — Be clear about intentions3940## Quick Decision Trees4142### Control Flow4344```45Need patterns? → case (or function heads)46Multiple operations? → with47Boolean conditions? → cond (multiple) or if (single)48```4950### Error Handling5152```53Expected failure? → {:ok, _}/{:error, _} tuples54Unexpected/bug? → raise exception (let supervisor handle)55External library? → rescue (only here!)56```5758### OTP5960```61Need state?62├─ No → Plain functions63├─ Simple get/update → Agent or ETS64├─ Complex messages/timeouts → GenServer65└─ One-off async → Task66```6768## Quick Patterns6970```elixir71# Pattern match in function head72def process(%{status: :active} = user), do: activate(user)73def process(%{status: :inactive} = user), do: deactivate(user)7475# with for happy path76with {:ok, user} <- get_user(id),77 {:ok, order} <- create_order(user) do78 {:ok, order}79end8081# Task for async82Task.Supervisor.async_nolink(TaskSup, fn -> work() end)83|> Task.yield(5000) || Task.shutdown(task)84```8586## Common Pitfalls8788| Wrong | Right |89|-------|-------|90| `length(list) == 0` | `list == []` or `Enum.empty?(list)` |91| `list ++ [item]` | `[item \| list] \|> Enum.reverse()` |92| `String.to_atom(input)` | `String.to_existing_atom(input)` |93| `spawn(fn -> log(conn) end)` | `ip = conn.ip; spawn(fn -> log(ip) end)` |94| `unless condition` | `if !condition` (unless deprecated in 1.18) |9596## References9798For detailed patterns, see:99100- `references/pattern-matching.md` - Pattern matching, guards, binary matching101- `references/otp-patterns.md` - GenServer, Supervisor, Task, Registry102- `references/error-handling.md` - Tagged tuples, rescue, with103- `references/with-and-pipes.md` - When to use `with` and `|>` (idiomatic patterns)104- `references/troubleshooting.md` - Production BEAM debugging (memory, performance, crashes)105- `references/anti-patterns.md` - Common mistakes and fixes106- `references/mix-tasks.md` - Mix task naming, option parsing, shell output107- `references/elixir-118-features.md` - Duration module, dbg improvements (1.18+)108- `references/elixir-120-type-system.md` - Gradual type checker, `dynamic()`, verified bugs as compile warnings (1.20+, OTP 27+)