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
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:
${CLAUDE_SKILL_DIR}/references/pattern-matching.md - Pattern matching, guards, binary matching
${CLAUDE_SKILL_DIR}/references/otp-patterns.md - GenServer, Supervisor, Task, Registry
${CLAUDE_SKILL_DIR}/references/error-handling.md - Tagged tuples, rescue, with
${CLAUDE_SKILL_DIR}/references/with-and-pipes.md - When to use with and |> (idiomatic patterns)
${CLAUDE_SKILL_DIR}/references/troubleshooting.md - Production BEAM debugging (memory, performance, crashes)
${CLAUDE_SKILL_DIR}/references/anti-patterns.md - Common mistakes and fixes
${CLAUDE_SKILL_DIR}/references/mix-tasks.md - Mix task naming, option parsing, shell output
${CLAUDE_SKILL_DIR}/references/elixir-118-features.md - Duration module, dbg improvements (1.18+)
1---2name: elixir-idioms3description: OTP/BEAM patterns and Elixir idioms — GenServer, Supervisor, Task, Registry, pattern matching, with chains, pipes. Use when designing processes or debugging BEAM issues.4---5
6# Elixir Idioms
7
8Reference for writing idiomatic Elixir code with BEAM-aware patterns.
9
10## Iron Laws — Never Violate These
11
121. **NO PROCESS WITHOUT A RUNTIME REASON** — Processes model concurrency, state, isolation—NOT code structure
132. **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 internal
165. **RESCUE ONLY FOR EXTERNAL CODE** — Never use rescue for control flow
176. **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 trees
209. **WRAP THIRD-PARTY LIBRARY APIs** — Always facade external deps behind a project-owned module. Enables swapping without touching callers
21
22## BEAM Architecture (Why Elixir Works This Way)
23
24- **Processes are cheap (2.6KB)** — Spawn liberally for concurrency/isolation
25- **Complete memory isolation** — No shared state, no locks needed
26- **Messages are copied** (except binaries >64 bytes) — Keep messages small
27- **Per-process GC** — No global GC pauses
28- **"Let it crash"** — Supervisors restart to known-good state
29
30## Core Principles
31
321. **Pattern match over conditionals** — Function heads first, then `case`, then `cond`
332. **Tagged tuples for expected failures** — `{:ok, _}`/`{:error, _}` for expected errors, raise for bugs
343. **Pipe operator for data transformation** — Start with data, never pipe single calls
354. **Let it crash** — Handle expected errors, crash on unexpected ones
365. **Explicit over implicit** — Be clear about intentions
37
38## Quick Decision Trees
39
40### Control Flow
41
42```
43Need patterns? → case (or function heads)
44Multiple operations? → with
45Boolean conditions? → cond (multiple) or if (single)
46```
47
48### Error Handling
49
50```
51Expected failure? → {:ok, _}/{:error, _} tuples
52Unexpected/bug? → raise exception (let supervisor handle)
53External library? → rescue (only here!)
54```
55
56### OTP
57
58```
59Need state?
60├─ No → Plain functions
61├─ Simple get/update → Agent or ETS
62├─ Complex messages/timeouts → GenServer
63└─ One-off async → Task
64```
65
66## Quick Patterns
67
68```elixir
69# Pattern match in function head
70def process(%{status: :active} = user), do: activate(user)
71def process(%{status: :inactive} = user), do: deactivate(user)
72
73# with for happy path
74with {:ok, user} <- get_user(id),
75 {:ok, order} <- create_order(user) do
76 {:ok, order}
77end
78
79# Task for async
80Task.Supervisor.async_nolink(TaskSup, fn -> work() end)
81|> Task.yield(5000) || Task.shutdown(task)
82```
83
84## Common Pitfalls
85
86| Wrong | Right |
87|-------|-------|
88| `length(list) == 0` | `list == []` or `Enum.empty?(list)` |
89| `list ++ [item]` | `[item \| list] \|> Enum.reverse()` |
90| `String.to_atom(input)` | `String.to_existing_atom(input)` |
91| `spawn(fn -> log(conn) end)` | `ip = conn.ip; spawn(fn -> log(ip) end)` |
92| `unless condition` | `if !condition` (unless deprecated in 1.18) |
93
94## References
95
96For detailed patterns, see:
97
98- `${CLAUDE_SKILL_DIR}/references/pattern-matching.md` - Pattern matching, guards, binary matching
99- `${CLAUDE_SKILL_DIR}/references/otp-patterns.md` - GenServer, Supervisor, Task, Registry
100- `${CLAUDE_SKILL_DIR}/references/error-handling.md` - Tagged tuples, rescue, with
101- `${CLAUDE_SKILL_DIR}/references/with-and-pipes.md` - When to use `with` and `|>` (idiomatic patterns)
102- `${CLAUDE_SKILL_DIR}/references/troubleshooting.md` - Production BEAM debugging (memory, performance, crashes)
103- `${CLAUDE_SKILL_DIR}/references/anti-patterns.md` - Common mistakes and fixes
104- `${CLAUDE_SKILL_DIR}/references/mix-tasks.md` - Mix task naming, option parsing, shell output
105- `${CLAUDE_SKILL_DIR}/references/elixir-118-features.md` - Duration module, dbg improvements (1.18+)