The most asked Elixir interview questions with structured answers — a quick answer, a clear explanation and working code for each. Covers basics for freshers through advanced, scenario and coding questions for experienced developers.
Updated November 2026 Reviewed by Abhishek Kumar 118 min read
98 Elixir interview questions, grouped by level: freshers, intermediate, experienced and coding.
Every answer starts with a one-line “Quick answer” you can say out loud, followed by the explanation and runnable code.
Use the filter bar to practise only the level you are interviewing for, then test yourself with the free Elixir quiz.
What is Elixir, and why do interviewers ask about it?
Elixir is a dynamic, functional programming language built on the Erlang VM (BEAM). Designed for building scalable, maintainable, and fault-tolerant applications, Elixir leverages the battle-tested OTP framework to create resilient systems with lightweight concurrency and message passing. Its Phoenix web framework delivers real-time capabilities through Channels and LiveView, making it a top choice for modern web and distributed systems.
This comprehensive guide collects the most frequently asked Elixir interview questions, ranging from foundational concepts like pattern matching, recursion, and the pipe operator to advanced topics such as OTP behaviours, Ecto, Phoenix LiveView, distributed Elixir, and performance optimization. Whether you are starting your Elixir journey or preparing for a senior role, these questions will help you solidify your knowledge and ace your next technical interview.
Why companies hire for Elixir
Strong static typing – catches errors at compile time, reducing runtime bugs
Excellent tooling and IDE support – autocompletion, navigation, and refactoring
Superset of JavaScript – works seamlessly with all existing JavaScript libraries
Used by major frameworks like React, Angular, and Vue – essential for large-scale apps
Enables scalable and maintainable enterprise-grade applications
Growing community, continuous improvements, and high demand in the job market
98 shown
Basic Elixir Interview Questions for Freshers
8 questions
Start here if you are a fresher or switching to Elixir. These fundamentals are asked in almost every first-round and campus interview.
Quick answerElixir is a functional, concurrent programming language built on the Erlang VM (BEAM). It is designed for building scalable and maintainable applications with high fault tolerance.
Functional Programming: Immutable data and pure functions
Concurrency: Lightweight processes and message passing
Fault Tolerance: Supervisor trees and "let it crash" philosophy
Hot Code Upgrades: Update code without stopping the system
Pattern Matching: Powerful matching and destructuring
Quick answerElixir uses immutable variables that cannot be reassigned. Constants can be defined using module attributes with the @ syntax. Variables are bound through pattern matching and cannot be mutated.
Variables: Immutable, can be rebound but not mutated
Module Attributes: @constant for compile-time constants
Pattern Matching: Bind variables through matching
Pinning Operator: ^ to use existing value in pattern matching
Rebinding: Variables can be rebound to new values
Elixir
# Variables and Constants in Elixir
x = 10
pi = 3.14159
val = 3.14
str = "Hello"IO.puts("x = #{x}")
IO.puts("pi = #{pi}")
IO.puts("val = #{val}")
IO.puts("str = #{str}")
Quick answerPattern Matching allows matching values against patterns and binding variables. It's a fundamental feature used throughout Elixir for destructuring data structures and controlling program flow.
Match Operator: = for pattern matching
List Matching: [head | tail] pattern
Tuple Matching: {a, b} pattern
Map Matching: %{key: value} pattern
Pinning: ^ to match existing value
Elixir
# Pattern Matching in Elixir
{x, y} = {3, 4}
IO.puts("x = #{x}, y = #{y}")
[head | tail] = [1, 2, 3, 4]
IO.puts("Head: #{head}, Tail: #{inspect(tail)}")
%{name: name, age: age} = %{name:"Alice", age:25}
IO.puts("Name: #{name}, Age: #{age}")
# Pinning operator
x = 10
^x = 10# Matches# ^x = 20 # Will not match, raises error# Pattern matching in function clausesdefmoduleMathdodefadd({a, b}), do: a + b
defadd([a, b]), do: a + b
defadd(%{a: a, b: b}), do: a + b
endIO.puts(Math.add({3, 4}))
IO.puts(Math.add([3, 4]))
IO.puts(Math.add(%{a:3, b:4}))
Quick answerModules are used to group related functions. Functions are defined using def and can have multiple clauses for pattern matching. Private functions are defined with defp.
defmodule — Defines a module
def — Defines a public function
defp — Defines a private function
Multiple Clauses: Different implementations for different patterns
Guard Clauses: when for additional conditions
Elixir
# Modules and Functions in ElixirdefmoduleMathdo# Public functiondefadd(a, b) do
a + b
end# Private functiondefpsubtract(a, b) do
a - b
end# One-liner functiondefmultiply(a, b), do: a * b
# Multiple clausesdefdivide(a, 0), do: {:error, "Division by zero"}
defdivide(a, b), do: {:ok, a / b}
# Guard clausesdeffactorial(0), do:1deffactorial(n) when n > 0do
n * factorial(n - 1)
end# Default argumentsdefgreet(name, greeting \ "Hello") do"#{greeting}, #{name}!"endendIO.puts(Math.add(10, 20))
IO.puts(Math.multiply(5, 4))
IO.puts(Math.factorial(5))
IO.puts(Math.greet("Alice"))
IO.puts(Math.greet("Bob", "Hi"))
Quick answerRecursion is a technique where a function calls itself. Elixir prefers recursion over loops due to immutability and the absence of traditional loops. Tail call optimization ensures efficiency.
Base Case: Stopping condition
Recursive Case: Self-call with smaller input
Tail Call Optimization: Efficient recursion without stack overflow
Recursive Functions: Factorial, Fibonacci, list processing
Accumulator Pattern: Efficient recursion with accumulators
Elixir
# Recursion in ElixirdefmoduleRecursiondo# Factorialdeffactorial(0), do:1deffactorial(n) when n > 0do
n * factorial(n - 1)
end# Fibonaccideffibonacci(0), do:0deffibonacci(1), do:1deffibonacci(n) when n > 1do
fibonacci(n - 1) + fibonacci(n - 2)
end# List processingdefsum([]), do:0defsum([head | tail]) do
head + sum(tail)
enddeflength([]), do:0deflength([_ | tail]) do1 + length(tail)
end# Tail recursiondefreverse(list), do: reverse(list, [])
defpreverse([], acc), do: acc
defpreverse([head | tail], acc) do
reverse(tail, [head | acc])
end# Map function with recursiondefmap([], _func), do: []
defmap([head | tail], func) do
[func.(head) | map(tail, func)]
end# Filter function with recursiondeffilter([], _predicate), do: []
deffilter([head | tail], predicate) doif predicate.(head) do
[head | filter(tail, predicate)]
else
filter(tail, predicate)
endendendIO.puts("Factorial 5: #{Recursion.factorial(5)}")
IO.puts("Fibonacci 8: #{Recursion.fibonacci(8)}")
IO.puts("Sum [1,2,3,4,5]: #{Recursion.sum([1,2,3,4,5])}")
IO.puts("Length [1,2,3,4,5]: #{Recursion.length([1,2,3,4,5])}")
IO.puts("Reverse [1,2,3]: #{inspect(Recursion.reverse([1,2,3]))}")
IO.puts("Map [1,2,3] *2: #{inspect(Recursion.map([1,2,3], fn x -> x * 2end))}")
IO.puts("Filter [1,2,3,4,5] even: #{inspect(Recursion.filter([1,2,3,4,5], fn x -> rem(x, 2) == 0end))}")
Quick answerThe Enum module provides a rich set of functions to work with collections like lists, maps, and streams. It offers functional programming operations for data transformation.
Enum.map — Transform elements
Enum.filter — Filter elements
Enum.reduce — Aggregate values
Enum.sort — Sort elements
Enum.each — Iterate for side effects
Elixir
# Enum Module in Elixir
list = [5, 1, 8, 3, 9, 2, 7]
# Map - transform elements
doubled = Enum.map(list, fn x -> x * 2end)
IO.puts("Doubled: #{inspect(doubled)}")
# Filter - select elements
evens = Enum.filter(list, fn x -> rem(x, 2) == 0end)
IO.puts("Evens: #{inspect(evens)}")
# Reduce - accumulate values
sum = Enum.reduce(list, 0, fn x, acc -> x + acc end)
IO.puts("Sum: #{sum}")
# Sort - order elements
sorted = Enum.sort(list)
IO.puts("Sorted: #{inspect(sorted)}")
# Map with capture syntax
squares = Enum.map(list, &(&1 * &1))
IO.puts("Squares: #{inspect(squares)}")
# Filter with capture
greater_than_5 = Enum.filter(list, &(&1 > 5))
IO.puts("> 5: #{inspect(greater_than_5)}")
# Each - side effectsEnum.each(list, fn x -> IO.puts("Item: #{x}") end)
# Find - find first matching
first_even = Enum.find(list, fn x -> rem(x, 2) == 0end)
IO.puts("First even: #{first_even}")
# Any? - check if any matches
has_even = Enum.any?(list, fn x -> rem(x, 2) == 0end)
IO.puts("Has even: #{has_even}")
# All? - check if all match
all_even = Enum.all?(list, fn x -> rem(x, 2) == 0end)
IO.puts("All even: #{all_even}")
# Join - convert to string
joined = Enum.join(list, ", ")
IO.puts("Joined: #{joined}")
# With_index - add index
with_index = Enum.with_index(list)
IO.puts("With index: #{inspect(with_index)}")
Quick answerThe Pipe Operator ( |> ) passes the result of one function as the first argument to the next function, making code more readable and expressive by creating a data pipeline.
The Pipe Operator (|>) passes the result of one function as the first argument to the next function, making code more readable and expressive by creating a data pipeline.
Function Chaining: Chain multiple operations
Readability: Read left-to-right flow
Composition: Easily compose functions
Pipeline Pattern: Common in Elixir codebases
Multiple Arguments: Works with functions taking multiple arguments
Elixir
# Pipe Operator in Elixir
list = [5, 1, 8, 3, 9, 2, 7]
# Without pipe - nested function calls
result = Enum.sum(Enum.filter(Enum.map(list, fn x -> x * 2end), fn x -> x > 10end))
IO.puts("Without pipe: #{result}")
# With pipe - readable flow
result = list
|> Enum.map(&(&1 * 2))
|> Enum.filter(&(&1 > 10))
|> Enum.sum()
IO.puts("With pipe: #{result}")
# Chaining multiple operations
list
|> Enum.map(&(&1 * 2))
|> Enum.filter(&(&1 > 10))
|> Enum.sort()
|> IO.inspect(label:"Result")
# Pipe with multiple argumentsdefmoduleMathdodefdouble(x), do: x * 2defadd(x, y), do: x + y
defsquare(x), do: x * x
end
result = 5
|> Math.double()
|> Math.add(10)
|> Math.square()
IO.puts("Result: #{result}")
# Pipe with functions that take multiple arguments
result = 10
|> Kernel.+(5)
|> Kernel.*(2)
IO.puts("Result: #{result}")
Quick answerGenServer is a behaviour module for implementing server processes. OTP (Open Telecom Platform) provides a set of libraries and design principles for building fault-tolerant systems with supervision trees.
Quick answerSupervisors are processes that monitor other processes and restart them if they crash, providing fault tolerance and self-healing capabilities through supervision trees.
Quick answerTasks are used for asynchronous computations and parallel processing. They provide a simple way to run code concurrently with built-in timeout support and supervision.
Async/Await: Task.async and Task.await
Parallel Processing: Run multiple tasks concurrently
Task Supervision: Task.Supervisor for supervised tasks
Timeouts: Handle slow tasks with timeouts
Task.async_stream: Process streams concurrently
Elixir
# Task Module in Elixir# Async task
task = Task.async(fn ->
Process.sleep(1000)
"Task completed"end)
IO.puts("Task started...")
result = Task.await(task)
IO.puts("Result: #{result}")
# Task with timeout
task = Task.async(fn ->
Process.sleep(5000)
"Slow task"end)
trydoTask.await(task, 2000)
rescue
e inTask.TimeoutError -> IO.puts("Task timed out!")
end# Async stream with multiple tasks
tasks = 1..5
|> Enum.map(fn i ->
Task.async(fn ->
Process.sleep(i * 100)
i * i
end)
end)
results = Enum.map(tasks, &Task.await/1)
IO.puts("Results: #{inspect(results)}")
# Task with supervisordefmoduleMyTaskdodefstart_linkdoTask.start_link(fn ->
Process.sleep(1000)
IO.puts("Task completed")
end)
endend# Task started
{:ok, _} = MyTask.start_link()
# Task as functionTask.async(fn ->
IO.puts("Running task")
end)
|> Task.await()
Quick answerETS is an in-memory storage system for fast lookups. It provides efficient key-value storage with various table types and is ideal for caching and temporary data storage.
Table Types: :set, :ordered_set, :bag
Operations: Insert, lookup, delete, update
Performance: Very fast read/write operations
Use Cases: Caching, lookups, temporary storage
Match Specifications: Complex query patterns
Elixir
# ETS (Erlang Term Storage) in Elixir# Create an ETS table
table = :ets.new(:my_table, [:set, :public, :named_table])
# Insert data:ets.insert(:my_table, {:user1, "Alice", 25})
:ets.insert(:my_table, {:user2, "Bob", 30})
:ets.insert(:my_table, {:user3, "Carol", 22})
# Lookup datacase:ets.lookup(:my_table, :user1) do
[{:user1, name, age}] ->
IO.puts("User: #{name}, Age: #{age}")
[] ->
IO.puts("User not found")
end# Update data:ets.insert(:my_table, {:user1, "Alice Johnson", 26})
# Delete data:ets.delete(:my_table, :user2)
# Get all data
all_data = :ets.tab2list(:my_table)
IO.puts("All data: #{inspect(all_data)}")
# Match data
matches = :ets.match(:my_table, {:user1, :"$1", :"$2"})
IO.puts("Matches: #{inspect(matches)}")
# Match with conditions
matches = :ets.match(:my_table, {:"$1", :"$2", 25})
IO.puts("Users with age 25: #{inspect(matches)}")
# Delete all:ets.delete_all_objects(:my_table)
# Clean up:ets.delete(:my_table)
Quick answerEcto is a database wrapper and query generator for Elixir applications. It provides a type-safe, composable query API with support for multiple databases and migrations.
Repo: Database repository module
Schemas: Define data models
Changesets: Data validation and transformation
Queries: from syntax for composable queries
Migrations: Database schema management
Elixir
# Ecto Query ExamplesdefmoduleMyApp.RepodouseEcto.Repo,
otp_app::my_app,
adapter:Ecto.Adapters.PostgresenddefmoduleMyApp.UserdouseEcto.SchemaimportEcto.Changeset
schema "users"do
field :name, :string
field :email, :string
field :age, :integer
timestamps()
enddefchangeset(user, attrs) do
user
|> cast(attrs, [:name, :email, :age])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> validate_number(:age, greater_than:0)
endenddefmoduleMyApp.PostdouseEcto.SchemaimportEcto.Changeset
schema "posts"do
field :title, :string
field :content, :string
belongs_to :user, MyApp.User
timestamps()
endend# Basic QueriesaliasMyApp.{Repo, User, Post}
# Insert
user = User.changeset(%User{}, %{name:"Alice", email:"alice@email.com", age:25})
caseRepo.insert(user) do
{:ok, user} -> IO.puts("User created: #{user.name}")
{:error, changeset} -> IO.puts("Error: #{inspect(changeset.errors)}")
end# Query
query = from u inUser, where: u.age > 18, select: u
users = Repo.all(query)
IO.puts("Users over 18: #{inspect(users)}")
# Query with order
query = from u inUser, order_by: [desc: u.age], select: u
users = Repo.all(query)
# Update
user = Repo.get(User, 1)
updated = User.changeset(user, %{age:26})
Repo.update(updated)
# DeleteRepo.delete(user)
# Join query
query = from u inUser,
join: p in assoc(u, :posts),
where: p.title == "Hello",
select: {u.name, p.title}
results = Repo.all(query)
# Preload
user = Repo.get(User, 1)
user = Repo.preload(user, :posts)
IO.puts("User posts: #{inspect(user.posts)}")
Quick answerPhoenix is a web framework for Elixir built on OTP and Plug. It provides real-time features with channels and LiveView, with high performance and low latency.
MVC Pattern: Controllers, views, templates
Channels: Real-time communication via WebSockets
LiveView: Interactive, server-rendered UIs
Performance: High concurrency and low latency
Ecto Integration: Built-in database support
Elixir
# Phoenix Framework ExampledefmoduleMyAppWeb.RouterdousePhoenix.RouterimportPhoenix.LiveView.Router
scope "/", MyAppWebdo
pipe_through :browser
get "/", PageController, :index
get "/hello/:name", PageController, :hello
resources "/users", UserController# LiveView routes
live "/counter", CounterLive
live "/dashboard", DashboardLiveend
scope "/api", MyAppWebdo
pipe_through :api
resources "/users", UserController, only: [:index, :create, :show, :update, :delete]
endenddefmoduleMyAppWeb.PageControllerdouseMyAppWeb, :controllerdefindex(conn, _params) do
render(conn, "index.html", message:"Hello, World!")
enddefhello(conn, %{"name" => name}) do
render(conn, "hello.html", name: name)
endenddefmoduleMyAppWeb.UserControllerdouseMyAppWeb, :controllerdefindex(conn, _params) do
users = Repo.all(User)
render(conn, "index.json", users: users)
enddefcreate(conn, %{"user" => user_params}) do
changeset = User.changeset(%User{}, user_params)
caseRepo.insert(changeset) do
{:ok, user} -> render(conn, "show.json", user: user)
{:error, changeset} -> conn |> put_status(400) |> render("error.json", changeset: changeset)
endenddefshow(conn, %{"id" => id}) do
user = Repo.get(User, id)
render(conn, "show.json", user: user)
enddefupdate(conn, %{"id" => id, "user" => user_params}) do
user = Repo.get(User, id)
changeset = User.changeset(user, user_params)
caseRepo.update(changeset) do
{:ok, user} -> render(conn, "show.json", user: user)
{:error, changeset} -> conn |> put_status(400) |> render("error.json", changeset: changeset)
endenddefdelete(conn, %{"id" => id}) do
user = Repo.get(User, id)
Repo.delete(user)
send_resp(conn, 204, "")
endend
Quick answerPhoenix LiveView enables building rich, real-time user interfaces with server-rendered HTML. It syncs state between server and client automatically over WebSockets.
Server-side Rendering: HTML rendered on server
Real-time Updates: State changes pushed to client
WebSocket Connection: Persistent connection for updates
Event Handling: phx-click and other bindings
Performance: Minimal client-side JavaScript
Elixir
# Phoenix LiveView ExampledefmoduleMyAppWeb.CounterLivedousePhoenix.LiveViewdefmount(_params, _session, socket) do
{:ok, assign(socket, count:0, history: [])}
enddefrender(assigns) do~H"""
<div class="counter-container">
<h1>Count: <%= @count %></h1>
<div class="buttons">
<button phx-click="increment" phx-value-amount="1">+1</button>
<button phx-click="increment" phx-value-amount="5">+5</button>
<button phx-click="decrement">-1</button>
<button phx-click="reset">Reset</button>
</div>
<div class="history">
<h3>History</h3>
<ul>
<%= for entry <- @history do %>
<li><%= entry %></li>
<% end %>
</ul>
</div>
</div>
"""enddefhandle_event("increment", %{"amount" => amount}, socket) do
count = socket.assigns.count + String.to_integer(amount)
history = ["Incremented by #{amount}" | socket.assigns.history]
{:noreply, assign(socket, count: count, history: history)}
enddefhandle_event("decrement", _params, socket) do
count = socket.assigns.count - 1
history = ["Decremented by 1" | socket.assigns.history]
{:noreply, assign(socket, count: count, history: history)}
enddefhandle_event("reset", _params, socket) do
history = ["Reset" | socket.assigns.history]
{:noreply, assign(socket, count:0, history: history)}
endend# PubSub for real-time updatesdefmoduleMyAppWeb.ChatLivedousePhoenix.LiveViewdefmount(_params, _session, socket) doif connected?(socket) doMyAppWeb.Endpoint.subscribe("chat:global")
end
{:ok, assign(socket, messages: [])}
enddefrender(assigns) do~H"""
<div>
<h2>Chat</h2>
<div id="messages">
<%= for message <- @messages do %>
<div><%= message %></div>
<% end %>
</div>
<form phx-submit="send_message">
<input type="text" name="message" placeholder="Type a message..." />
<button type="submit">Send</button>
</form>
</div>
"""enddefhandle_event("send_message", %{"message" => message}, socket) doMyAppWeb.Endpoint.broadcast("chat:global", "new_message", message)
{:noreply, socket}
enddefhandle_info(%{event:"new_message", payload: message}, socket) do
{:noreply, update(socket, :messages, fn msgs -> [message | msgs] end)}
endend
Quick answerPlug is a specification and toolkit for building composable web modules. It is the foundation for Phoenix and other web frameworks, providing a simple HTTP abstraction.
Plug Functions: Define request/response handlers
Plug Pipeline: Chain multiple plugs together
Conn Struct: Represents request/response
Router: Route matching and dispatching
Adapters: Cowboy, Bandit, and others
Elixir
# Plug ExampledefmoduleMyApp.PlugExampledoimportPlug.Conndefinit(options), do: options
defcall(conn, _opts) do
conn
|> put_resp_content_type("text/plain")
|> send_resp(200, "Hello, World!")
endenddefmoduleMyApp.RouterdousePlug.Router
plug(:match)
plug(:dispatch)
get "/"do
send_resp(conn, 200, "Welcome to Plug!")
end
get "/hello/:name"do
send_resp(conn, 200, "Hello, #{name}!")
end
post "/api/users"do
{:ok, body, conn} = read_body(conn)
caseJason.decode(body) do
{:ok, params} ->
send_resp(conn, 201, Jason.encode!(%{message:"User created", user: params}))
{:error, _} ->
send_resp(conn, 400, Jason.encode!(%{error:"Invalid JSON"}))
endend
get "/api/users"do
users = [%{id:1, name:"Alice"}, %{id:2, name:"Bob"}]
send_resp(conn, 200, Jason.encode!(users))
end
match _ do
send_resp(conn, 404, Jason.encode!(%{error:"Not found"}))
endend# Custom PlugdefmoduleMyApp.AuthPlugdoimportPlug.Conndefinit(options), do: options
defcall(conn, _opts) docase get_req_header(conn, "authorization") do
["Bearer " <> token] ->
case validate_token(token) do
{:ok, user} -> assign(conn, :current_user, user)
{:error, _} -> conn |> send_resp(401, "Unauthorized") |> halt()
end
_ ->
conn |> send_resp(401, "Unauthorized") |> halt()
endenddefpvalidate_token(token) do# Validate JWT or other token
{:ok, %{id:1, name:"Alice"}}
endend# Run the router
{:ok, _} = Plug.Cowboy.http(MyApp.Router, [])
Quick answerProtocols provide polymorphism for different data types. They allow you to define behavior that can be implemented for various types, similar to interfaces in other languages.
Protocol Definition: defprotocol
Protocol Implementation: defimpl for specific types
Data Types: Any data type can implement protocols
Use Cases: Custom serialization, formatting, inspection
Fallback: @fallback_to_any for default implementation
Elixir
# Protocol Example in ElixirdefprotocolGreeterdodefgreet(person)
end# Implement protocol for various typesdefimplGreeter, for:Stringdodefgreet(name) do"Hello, #{name}!"endenddefimplGreeter, for:Mapdodefgreet(person) do"Hello, #{person[:name]}! You are #{person[:age]} years old."endenddefimplGreeter, for:Listdodefgreet([name, age]) do"Hello, #{name}! You are #{age} years old."endenddefimplGreeter, for:Integerdodefgreet(id) do"User with ID: #{id}"endenddefimplGreeter, for:Tupledodefgreet({name, age, city}) do"Hello, #{name} from #{city}! You are #{age} years old."endend# Fallback to anydefimplGreeter, for:Anydodefgreet(_), do:"Greetings!"end# UsageIO.puts(Greeter.greet("Alice"))
IO.puts(Greeter.greet(%{name:"Bob", age:30}))
IO.puts(Greeter.greet(["Carol", 22]))
IO.puts(Greeter.greet(123))
IO.puts(Greeter.greet({"Dave", 35, "NYC"}))
# Protocol inheritancedefprotocolSerializerdodefto_json(data)
enddefimplSerializer, for:Mapdodefto_json(data) doJason.encode!(data)
endenddefimplSerializer, for:Listdodefto_json(data) doJason.encode!(data)
endenddefimplSerializer, for:Atomdodefto_json(data) doJason.encode!(Atom.to_string(data))
endend
data = %{name:"Alice", age:25}
IO.puts("JSON: #{Serializer.to_json(data)}")
Quick answerMacros allow metaprogramming by generating code at compile time. They enable powerful abstractions and DSL creation by manipulating the abstract syntax tree (AST).
Quote/Unquote: quote and unquote for code generation
Compile-time Execution: Macros run during compilation
Custom Constructs: Create custom syntax and constructs
DSL Creation: Build domain-specific languages
Hygiene: Macros are hygienic by default
Elixir
# Macros in ElixirdefmoduleMyMacrosdodefmacrounless(condition, do: expression) doquotedoif !unquote(condition) dounquote(expression)
endendenddefmacrodebug(expression) doquotedoIO.puts("Expression: #{unquote(expression)}")
result = unquote(expression)
IO.puts("Result: #{result}")
result
endenddefmacrolog(message) doquotedoIO.puts("[LOG] #{unquote(message)} at #{DateTime.utc_now()}")
endenddefmacroassert(expression, message \ "Assertion failed") doquotedoif !unquote(expression) doraiseunquote(message)
endendenddefmacrochain(expressions) doquotedounquote(expressions)
|> Enum.reduce(fn expr, acc -> expr + acc end)
endenddefmacrounless(condition, do: do_block, else: else_block) doquotedoifunquote(condition) dounquote(else_block)
elseunquote(do_block)
endendendenddefmoduleMyAppdorequireMyMacrosdeftestdoMyMacros.unlesstruedoIO.puts("This won't print")
endMyMacros.unlessfalsedoIO.puts("This will print")
end
x = 10MyMacros.debug(x * 2)
MyMacros.log("Application started")
MyMacros.assert(x > 5, "x must be greater than 5")
result = MyMacros.chain([1, 2, 3, 4, 5])
IO.puts("Chain result: #{result}")
# Custom unless with elseMyMacros.unlesstruedoIO.puts("This won't print")
elseIO.puts("This will print")
endendendMyApp.test()
Quick answerDistributed Elixir allows multiple Elixir nodes to communicate over a network, enabling distributed systems and fault tolerance with built-in Erlang distribution.
Node Communication: Connect nodes via Node.connect
Remote Spawning: Node.spawn for remote process creation
Distributed Erlang: Built on Erlang's distribution capabilities
Network Topology: Fully connected mesh network
Distributed Transactions: Across multiple nodes
Elixir
# Distributed Elixir Example# Node 1# Start node with name# iex --name node1@127.0.0.1 --cookie secret# Node 2# iex --name node2@127.0.0.1 --cookie secretdefmoduleDistributeddodefping(node) doNode.ping(node)
enddeflist_nodesdoNode.list()
enddefsend_message(node, message) doNode.spawn(node, fn ->
IO.puts("Received message: #{message}")
end)
enddefremote_call(node, module, function, args) docaseNode.spawn(node, fn ->
apply(module, function, args)
end) do
pid when is_pid(pid) -> {:ok, pid}
error -> {:error, error}
endenddefremote_call_with_result(node, module, function, args) do
result = :rpc.call(node, module, function, args)
case result do
{:badrpc, _} -> {:error, "RPC failed"}
_ -> {:ok, result}
endenddefregister_node(name) doNode.set_cookie(:secret)
Node.start(name)
endend# Usage on node1Distributed.ping(:node2@127.0.0.1)
Distributed.list_nodes()
Distributed.send_message(:node2@127.0.0.1, "Hello from node1")
# Execute function on remote nodeDistributed.remote_call(:node2@127.0.0.1, IO, :puts, ["Hello from remote"])
# Remote call with resultDistributed.remote_call_with_result(:node2@127.0.0.1, :erlang, :now, [])
Quick answerStreams enable lazy, composable operations on collections. They process data on-demand, making them memory efficient and ideal for handling large datasets.
Quick answerOTP Applications provide a standardized structure for organizing code, dependencies, and starting the supervision tree. They are the building blocks of Elixir systems.
Application Callback: start/2 and stop/1
Supervision Tree: Root supervisor for all processes
Configuration: config/config.exs for app settings
Dependencies: Managed via mix.exs
Environment: Mix.env() for runtime environment
Elixir
# OTP Application StructuredefmoduleMyAppdouseApplicationdefstart(_type, _args) do# Start the supervision tree
children = [
# Start the HTTP server
{Plug.Cowboy, scheme::http, plug:MyApp.Router, options: [port:4000]},
# Start the databaseMyApp.Repo,
# Start the cache
{Cache, []},
# Start the scheduler
{Scheduler, []},
# Start the registry
{Registry, keys::unique, name:MyApp.Registry}
]
opts = [strategy::one_for_one, name:MyApp.Supervisor]
Supervisor.start_link(children, opts)
enddefstop(_state) doIO.puts("Application stopping...")
:okendend# ConfigurationdefmoduleMyApp.Configdodefget(key) doApplication.get_env(:my_app, key)
enddefset(key, value) doApplication.put_env(:my_app, key, value)
enddefget_alldoApplication.get_all_env(:my_app)
endend# UsageMyApp.Config.set(:database_url, "postgres://localhost/myapp")
MyApp.Config.set(:pool_size, 10)
IO.puts("Database URL: #{MyApp.Config.get(:database_url)}")
IO.puts("Pool size: #{MyApp.Config.get(:pool_size)}")
Quick answerBehaviours define a set of callbacks that modules must implement. They provide a contract for module interaction and are used extensively in OTP.
Behaviour Definition: @callback and @macrocallback
Implementation: @behaviour module attribute
Common Behaviours: GenServer, Supervisor, Application
Quick answerAgents provide a simple way to manage state in a process. They are lightweight and easy to use for basic state management with get and update operations.
State Management: Agent.start_link with initial state
Get/Update: Agent.get, Agent.update
Thread Safety: State changes are sequential
Use Cases: Simple counters, caches, configuration
Short-lived: For simple state management
Elixir
# Agent Example in ElixirdefmoduleUserAgentdodefstart_link(initial_state) doAgent.start_link(fn -> initial_state end, name: __MODULE__)
enddefadd_user(user) doAgent.update(__MODULE__, fn state -> [user | state] end)
enddefget_usersdoAgent.get(__MODULE__, fn state -> state end)
enddefget_user_by_id(id) doAgent.get(__MODULE__, fn state ->
Enum.find(state, fn user -> user.id == id end)
end)
enddefupdate_user(id, new_user_data) doAgent.update(__MODULE__, fn state ->
Enum.map(state, fn user ->
if user.id == id doMap.merge(user, new_user_data)
else
user
endend)
end)
enddefdelete_user(id) doAgent.update(__MODULE__, fn state ->
Enum.filter(state, fn user -> user.id != id end)
end)
enddefclear_alldoAgent.update(__MODULE__, fn _ -> [] end)
enddefcount_usersdoAgent.get(__MODULE__, fn state -> length(state) end)
endend# Usage
{:ok, _pid} = UserAgent.start_link([])
# Add usersUserAgent.add_user(%{id:1, name:"Alice", age:25})
UserAgent.add_user(%{id:2, name:"Bob", age:30})
UserAgent.add_user(%{id:3, name:"Carol", age:22})
# Get all users
all_users = UserAgent.get_users()
IO.puts("All users: #{inspect(all_users)}")
# Find user by ID
user = UserAgent.get_user_by_id(2)
IO.puts("User 2: #{inspect(user)}")
# Update userUserAgent.update_user(1, %{age:26, name:"Alice Johnson"})
# Delete userUserAgent.delete_user(3)
# Get updated listIO.puts("Updated users: #{inspect(UserAgent.get_users())}")
IO.puts("User count: #{UserAgent.count_users()}")
Quick answerRegistry provides a way to register processes by name for easy lookup. It supports unique and duplicate keys with built-in conflict resolution.
Registration: Registry.register for process registration
Quick answerTask Supervisor provides a supervisor for managing tasks, making it easy to run supervised asynchronous operations with automatic error handling.
Supervised Tasks: Tasks are automatically supervised
Quick answerPhoenix PubSub provides a publish-subscribe mechanism for real-time messaging between processes and nodes. It's built on PG2 for distributed messaging.
Quick answerStreams enable efficient data processing with lazy evaluation, making them suitable for large datasets and real-time processing with memory efficiency.
Lazy Evaluation: Process on demand
Memory Efficiency: No need to load entire dataset
Composition: Chain operations together
Use Cases: File processing, data pipelines
Infinite Streams: Process infinite sequences
Elixir
# Streaming Example in ElixirdefmoduleDataStreamdodefgenerate_random_numbers(count) doStream.repeatedly(fn -> :rand.uniform(100) end)
|> Enum.take(count)
enddefprocess_data(stream) do
stream
|> Stream.map(&(&1 * 2))
|> Stream.filter(&(&1 > 50))
|> Stream.map(&IO.inspect/1)
|> Enum.to_list()
enddefread_file_chunks(file_path, chunk_size \ 10) doFile.stream!(file_path)
|> Stream.map(&String.trim/1)
|> Stream.filter(&(&1 != ""))
|> Stream.chunk_every(chunk_size)
|> Stream.map(fn chunk -> Enum.join(chunk, ",") end)
enddefweb_request_stream(url) do# Simulate web request streamingStream.iterate(1, &(&1 + 1))
|> Stream.map(fn page ->
# Simulate paginated API
%{page: page, data:Enum.to_list(1..10)}
end)
|> Stream.filter(&(&1.page <= 5))
enddefprocess_large_file(file_path) doFile.stream!(file_path)
|> Stream.map(&String.trim/1)
|> Stream.map(&String.split/1)
|> Stream.flat_map(& &1)
|> Stream.map(&String.downcase/1)
|> Stream.filter(&(&1 != ""))
|> Enum.reduce(%{}, fn word, acc ->
Map.update(acc, word, 1, &(&1 + 1))
end)
enddefstream_with_state(data) doStream.iterate(data, fn state ->
new_state = state + 1IO.puts("State: #{new_state}")
new_state
end)
|> Enum.take(5)
enddefslow_streamdoStream.iterate(0, &(&1 + 1))
|> Stream.take(10)
|> Stream.map(fn x ->
Process.sleep(100)
x * 2end)
endend# Usage# Generate random numbers
random_numbers = DataStream.generate_random_numbers(20)
IO.puts("Random numbers: #{inspect(random_numbers)}")
# Process data
processed = DataStream.process_data(1..100)
IO.puts("Processed: #{inspect(processed)}")
# Web request streamDataStream.web_request_stream()
|> Enum.each(fn response ->
IO.puts("Page #{response.page}: #{inspect(response.data)}")
end)
# Process large file# result = DataStream.process_large_file("data.txt")# IO.puts("Word count: #{inspect(result)}")
Quick answerMnesia is a distributed database management system built into Erlang/Elixir, providing ACID transactions and fault tolerance with built-in replication.
Quick answerGenStage is a behaviour for building event processing pipelines with back-pressure and flow control. It enables scalable data processing systems.
Quick answerFlow is a library built on GenStage for parallel data processing with built-in back-pressure and composition. It provides high-performance data processing.
Parallel Processing: Process data in parallel
Back-pressure: Automatic flow control
Composition: Chain operations together
Use Cases: ETL, data pipelines, batch processing
MapReduce: Built-in MapReduce support
Elixir
# Flow Example (Parallel Processing)defmoduleFlowExampledodefprocess_data(data) do
data
|> Flow.from_enumerable()
|> Flow.map(&(&1 * 2))
|> Flow.filter(&(&1 > 10))
|> Flow.map(&IO.inspect/1)
|> Enum.to_list()
enddefprocess_file(file_path) doFile.stream!(file_path)
|> Flow.from_enumerable()
|> Flow.map(&String.trim/1)
|> Flow.filter(&(&1 != ""))
|> Flow.chunk_every(100)
|> Flow.map(fn chunk ->
Enum.join(chunk, ",")
end)
|> Enum.to_list()
enddefparallel_map(data, function) do
data
|> Flow.from_enumerable(max_demand:10)
|> Flow.map(function)
|> Enum.to_list()
enddefparallel_aggregate(data) do
data
|> Flow.from_enumerable(max_demand:10)
|> Flow.reduce(fn -> 0end, fn x, acc -> x + acc end)
|> Enum.to_list()
enddefparallel_group_by(data, key_function) do
data
|> Flow.from_enumerable()
|> Flow.group_by(key_function)
|> Enum.to_list()
enddefparallel_join(left, right, join_key) doFlow.from_enumerables([left, right])
|> Flow.map(fn item -> {join_key.(item), item} end)
|> Flow.group_by(fn {key, _} -> key end)
|> Flow.map(fn {key, items} ->
{key, Enum.map(items, fn {_, item} -> item end)}
end)
|> Enum.to_list()
endend# Usage
data = 1..100# Process data in parallel
result = FlowExample.process_data(data)
IO.puts("Processed: #{inspect(result)}")
# Parallel map
squares = FlowExample.parallel_map(data, fn x -> x * x end)
IO.puts("Squares: #{inspect(Enum.take(squares, 10))}")
# Parallel aggregate
sum = FlowExample.parallel_aggregate(data)
IO.puts("Sum: #{inspect(sum)}")
Quick answerBroadway is a data processing pipeline library for Elixir, built on GenStage for high-throughput and fault-tolerant processing with built-in error handling.
Pipeline Processing: Process data in stages
Batch Processing: Process data in batches
Fault Tolerance: Automatic retry and failure handling
Quick answerTelemetry provides a standard way to emit and handle events for metrics, logging, and monitoring in Elixir applications with built-in integration support.
Events: Emit events with measurements
Handlers: Attach handlers to events
Metrics: Collect performance and business metrics
Integration: Works with Prometheus, StatsD, etc.
Instrumentation: Built-in library instrumentation
Elixir
# Telemetry ExampledefmoduleMyApp.TelemetrydouseSupervisordefstart_linkdoSupervisor.start_link(__MODULE__, [], name: __MODULE__)
enddefinit(_) do
children = [
{Telemetry, []}
]
Supervisor.init(children, strategy::one_for_one)
enddefsetupdo:telemetry.attach(
"my-handler",
[:my_app, :request, :stop],
&handle_event/4,
nil
)
:telemetry.attach(
"error-handler",
[:my_app, :request, :error],
&handle_error/4,
nil
)
enddefhandle_event([:my_app, :request, :stop], measurements, metadata, _config) do
duration = measurements.duration
path = metadata.path
status = metadata.status
IO.puts("Request to #{path} completed in #{duration}ms with status #{status}")
# Log slow requestsif duration > 1000doIO.puts("Slow request: #{path} took #{duration}ms")
endenddefhandle_error([:my_app, :request, :error], measurements, metadata, _config) do
error = metadata.error
path = metadata.path
IO.puts("Error on #{path}: #{inspect(error)}")
enddefmeasure_request(path, status, function) do
start = System.monotonic_time()
trydo
result = function.()
stop = System.monotonic_time()
duration = System.convert_time_unit(stop - start, :native, :millisecond)
:telemetry.execute([:my_app, :request, :stop], %{duration: duration}, %{
path: path,
status: status
})
result
rescue
e ->
stop = System.monotonic_time()
duration = System.convert_time_unit(stop - start, :native, :millisecond)
:telemetry.execute([:my_app, :request, :error], %{duration: duration}, %{
path: path,
error: e
})
{:error, e}
endendend# UsageMyApp.Telemetry.start_link()
MyApp.Telemetry.setup()
# Measure a successful requestMyApp.Telemetry.measure_request("/api/users", 200, fn ->
Process.sleep(500)
{:ok, "Response data"}
end)
# Measure a slow requestMyApp.Telemetry.measure_request("/api/reports", 200, fn ->
Process.sleep(1500)
{:ok, "Report data"}
end)
# Measure a failed requestMyApp.Telemetry.measure_request("/api/error", 500, fn ->
Process.sleep(100)
raise"Something went wrong"end)
Quick answerLogger is the built-in logging system in Elixir, providing structured logging with configurable levels and backends for comprehensive logging capabilities.
Quick answerElixir provides a comprehensive configuration system through Application module, environment variables, and config files for flexible application setup.
Application.get_env: Access configuration
config/config.exs: Configuration files
Environment Variables: System environment variables
Runtime Configuration: Config module
Release Configuration: Runtime config for releases
Quick answerMix is Elixir's build tool for creating, compiling, testing, and managing dependencies in Elixir projects.
Project Management: mix new to create projects
Dependencies: Manage dependencies with Hex
Tasks: mix test, mix compile, mix run
Custom Tasks: Create your own Mix tasks
Elixir
# Mix Tasks ExampledefmoduleMix.Tasks.HellodouseMix.Task@shortdoc"Prints Hello, World!"defrun(_args) doIO.puts("Hello, World!")
endenddefmoduleMix.Tasks.GreetdouseMix.Task@shortdoc"Greets a person by name"defrun(args) do
name = case args do
[name] -> name
_ -> "World"endIO.puts("Hello, #{name}!")
endenddefmoduleMix.Tasks.SetupdouseMix.Taskdefrun(_args) doMix.shell().info("Setting up application...")
# Run database migrationsMix.Task.run("ecto.create")
Mix.Task.run("ecto.migrate")
# Seed dataMix.Task.run("run", ["priv/repo/seeds.exs"])
Mix.shell().info("Setup complete!")
endend
Quick answerDynamicSupervisor allows starting and stopping child processes dynamically at runtime, ideal for worker pools and temporary processes with one-for-one strategy.
Quick answerPhoenix LiveView with Ecto enables building interactive UIs with database integration, providing real-time updates and form handling with Ecto changesets.
Quick answerPhoenix LiveView with PubSub enables real-time communication between LiveViews, allowing broadcasting of messages and updates across connected clients.
PubSub Integration: Phoenix PubSub for messaging
Real-time Updates: Broadcast to multiple LiveViews
Event Handling: Handle incoming messages
Use Cases: Chat, notifications, real-time feeds
Cross-View Communication: Communicate between views
Quick answerPhoenix Controllers handle HTTP requests with Plug for authentication, authorization, and request/response processing in a pipeline pattern.
Quick answerPhoenix Router defines routes for both traditional controllers and LiveViews, enabling seamless integration of server-rendered and real-time pages.
Routing: Define URL routes
LiveView Routes: live macro for LiveViews
Scopes: Group routes by scope
Pipelines: Apply plugs to routes
Nested Routes: Resource nesting and routing
Elixir
# Phoenix Router with LiveViewdefmoduleMyAppWeb.RouterdouseMyAppWeb, :routerimportPhoenix.LiveView.Router
pipeline :browserdo
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headersend
pipeline :apido
plug :accepts, ["json"]
end
scope "/", MyAppWebdo
pipe_through :browser
get "/", PageController, :index
live "/counter", CounterLive
live "/chat", ChatLive
live "/users", UserLive
live "/dashboard", DashboardLive
live "/profile/:id", ProfileLiveend
scope "/api", MyAppWebdo
pipe_through :api
resources "/users", UserController, except: [:new, :edit]
resources "/posts", PostController, except: [:new, :edit]
end# Admin routes
scope "/admin", MyAppWeb.Admin, as::admindo
pipe_through [:browser, :admin_auth]
resources "/users", UserController
resources "/posts", PostController
live "/dashboard", DashboardLiveendend
Quick answerPhoenix with Ecto Multi enables performing multiple database operations in a single transaction with built-in error handling and rollback support.
Ecto.Multi: Bundle multiple operations
Transactions: ACID transactions with rollback
Error Handling: Handle errors gracefully
Run/Insert/Update: Multiple operation types
Complex Operations: Combine inserts, updates, and custom logic
Quick answerPhoenix with Absinthe GraphQL provides GraphQL API support with schema definition, resolvers, and subscriptions for real-time GraphQL queries.
GraphQL Schema: Define types, queries, mutations
Resolvers: Handle GraphQL queries
Subscriptions: Real-time GraphQL updates
Middleware: Authentication and authorization
Complexity Analysis: Query complexity limits
Elixir
# Phoenix with Absinthe GraphQLdefmoduleMyAppWeb.SchemadouseAbsinthe.Schema
import_types MyAppWeb.Types
query do
field :users, list_of(:user) do
resolve fn _parent, _args, _resolution ->
{:ok, MyApp.Repo.all(MyApp.User)}
endend
field :user, :userdo
arg :id, non_null(:id)
resolve fn %{id: id}, _resolution ->
{:ok, MyApp.Repo.get(MyApp.User, id)}
endendend
mutation do
field :create_user, :userdo
arg :name, non_null(:string)
arg :email, non_null(:string)
arg :age, :integer
resolve fn %{name: name, email: email, age: age}, _resolution ->
caseMyApp.Accounts.create_user(%{name: name, email: email, age: age}) do
{:ok, user} -> {:ok, user}
{:error, changeset} -> {:error, changeset}
endendendend
subscription do
field :user_created, :userdo
config fn _args, _resolution ->
{:ok, topic:"user_created"}
endendendend
Quick answerPhoenix with Absinthe Subscriptions enables real-time GraphQL subscriptions with Phoenix PubSub, allowing clients to subscribe to data changes.
GraphQL Subscriptions: Real-time data streaming
PubSub Integration: Phoenix PubSub for subscriptions
Topic Management: Manage subscription topics
Broadcasting: Broadcast updates to subscribers
Use Cases: Live data, notifications, real-time feeds
Elixir
# Phoenix with Absinthe SubscriptionsdefmoduleMyAppWeb.SchemadouseAbsinthe.Schema
subscription do
field :user_created, :userdo
config fn _args, _resolution ->
{:ok, topic:"user_created"}
endend
field :post_created, :postdo
config fn _args, _resolution ->
{:ok, topic:"post_created"}
endendendenddefmoduleMyAppWeb.Resolversdodefcreate_user(_parent, args, _resolution) docaseMyApp.Accounts.create_user(args) do
{:ok, user} ->
Absinthe.Subscription.publish(MyAppWeb.Endpoint, user, user_created:"user_created")
{:ok, user}
{:error, changeset} -> {:error, changeset}
endendenddefmoduleMyAppWeb.UserSubscriptiondouseAbsinthe.Subscriptiondefpublish(doc_result, _args, _resolution) do
{:ok, doc_result}
endend
Quick answerPhoenix Context is a module that encapsulates related functionality and data, providing a clear boundary between different parts of the application.
Context Definition: Bounded context for domain logic
Data Management: Handle data operations
Business Logic: Encapsulate business rules
Separation of Concerns: Clear module boundaries
Testing: Easily test contexts
Elixir
# Phoenix Context ExampledefmoduleMyApp.Accountsdo@moduledoc"""
The Accounts context for user management
"""aliasMyApp.{Repo, User, Profile}
defget_user(id) doRepo.get(User, id)
enddefget_user_by_email(email) doRepo.get_by(User, email: email)
enddeflist_usersdoRepo.all(User)
enddefcreate_user(attrs \ %{}) do
%User{}
|> User.changeset(attrs)
|> Repo.insert()
enddefupdate_user(%User{} = user, attrs) do
user
|> User.changeset(attrs)
|> Repo.update()
enddefdelete_user(%User{} = user) doRepo.delete(user)
endenddefmoduleMyApp.Blogdo@moduledoc"""
The Blog context for post management
"""aliasMyApp.{Repo, Post, Comment}
deflist_postsdoRepo.all(Post)
enddefget_post(id) doRepo.get(Post, id)
enddefcreate_post(attrs \ %{}) do
%Post{}
|> Post.changeset(attrs)
|> Repo.insert()
endend
Quick answerPhoenix Context with Ecto combines domain logic with database operations, providing a clean separation between business rules and data access.
Data Access: Ecto for database operations
Business Logic: Encapsulated in contexts
Preloading: Eager loading of associations
Pagination: Page through large datasets
Search: Full-text and partial search
Elixir
# Phoenix Context with EctodefmoduleMyApp.AccountsdoaliasMyApp.{Repo, User, Profile}
defget_user_with_profile(id) do
query = from u inUser,
where: u.id == ^id,
preload: [:profile]
Repo.one(query)
enddefget_user_with_posts(id) do
query = from u inUser,
where: u.id == ^id,
preload: [posts: from(p inPost, order_by: [desc: p.inserted_at])]
Repo.one(query)
enddefget_user_with_comments(id) do
query = from u inUser,
where: u.id == ^id,
preload: [comments: from(c inComment, order_by: [desc: c.inserted_at])]
Repo.one(query)
enddefsearch_users(search_term) do
query = from u inUser,
where: ilike(u.name, ^"%#{search_term}%") or ilike(u.email, ^"%#{search_term}%"),
order_by: u.name
Repo.all(query)
enddefpaginate_users(page \ 1, page_size \ 10) do
query = from u inUser, order_by: u.name
Repo.paginate(query, page: page, page_size: page_size)
endend
Quick answerA Complete Library Management System in Elixir demonstrates OTP principles, Ecto for database, and Phoenix for web interface with real-time updates.
Book Management: Add, search, track availability
Member Management: Registration and borrowing
Borrow/Return: Transaction processing with Ecto
Real-time Updates: Phoenix Channels for live updates
Reports: Generate library statistics and reports
Elixir
# Complete Library Management System in ElixirdefmoduleMyApp.LibrarydoaliasMyApp.{Repo, Book, Member, Borrowing}
defadd_book(attrs) do
%Book{}
|> Book.changeset(attrs)
|> Repo.insert()
enddefregister_member(attrs) do
%Member{}
|> Member.changeset(attrs)
|> Repo.insert()
enddefborrow_book(member_id, book_id) do
member = Repo.get(Member, member_id)
book = Repo.get(Book, book_id)
if book.available_copies > 0doRepo.transaction(fn ->
# Decrement available copies
book
|> Book.available_changeset(%{available_copies: book.available_copies - 1})
|> Repo.update!()
# Create borrowing record
%Borrowing{}
|> Borrowing.changeset(%{member_id: member_id, book_id: book_id})
|> Repo.insert!()
end)
{:ok, "Book borrowed successfully"}
else
{:error, "No copies available"}
endenddefreturn_book(member_id, book_id) do
borrowing = Repo.get_by(Borrowing, member_id: member_id, book_id: book_id, returned_at:nil)
if borrowing doRepo.transaction(fn ->
# Update borrowing record
borrowing
|> Borrowing.return_changeset()
|> Repo.update!()
# Increment available copies
book = Repo.get(Book, book_id)
book
|> Book.available_changeset(%{available_copies: book.available_copies + 1})
|> Repo.update!()
end)
{:ok, "Book returned successfully"}
else
{:error, "No active borrowing record found"}
endenddefsearch_books(query) do
from b inBook,
where: ilike(b.title, ^"%#{query}%") or ilike(b.author, ^"%#{query}%"),
order_by: b.title
|> Repo.all()
enddefget_member_borrowings(member_id) do
query = from b inBorrowing,
where: b.member_id == ^member_id,
preload: [:book],
order_by: [desc: b.borrowed_at]
Repo.all(query)
enddefget_overdue_booksdo
query = from b inBorrowing,
where: b.returned_at == niland b.due_date < ^Date.utc_today(),
preload: [:member, :book]
Repo.all(query)
enddefget_available_booksdo
query = from b inBook,
where: b.available_copies > 0,
order_by: b.title
Repo.all(query)
enddefget_library_statsdo
%{
total_books:Repo.aggregate(Book, :count, :id),
total_members:Repo.aggregate(Member, :count, :id),
active_borrowings:Repo.aggregate(Borrowing, :count, :id, where: [returned_at:nil]),
overdue_books: length(get_overdue_books())
}
endend# Phoenix ControllerdefmoduleMyAppWeb.LibraryControllerdouseMyAppWeb, :controllerdefindex(conn, _params) do
books = MyApp.Library.get_available_books()
stats = MyApp.Library.get_library_stats()
render(conn, "index.html", books: books, stats: stats)
enddefsearch(conn, %{"q" => query}) do
results = MyApp.Library.search_books(query)
json(conn, results)
enddefborrow(conn, %{"member_id" => member_id, "book_id" => book_id}) docaseMyApp.Library.borrow_book(member_id, book_id) do
{:ok, message} ->
json(conn, %{success:true, message: message})
{:error, error} ->
conn |> put_status(400) |> json(%{success:false, error: error})
endenddefreturn(conn, %{"member_id" => member_id, "book_id" => book_id}) docaseMyApp.Library.return_book(member_id, book_id) do
{:ok, message} ->
json(conn, %{success:true, message: message})
{:error, error} ->
conn |> put_status(400) |> json(%{success:false, error: error})
endendend
Elixir is a functional, concurrent programming language built on the Erlang VM (BEAM). It is designed for scalable, fault-tolerant, and distributed applications.
What is pattern matching in Elixir?
Pattern matching is a core feature of Elixir that allows values to be matched against patterns for variable assignment and control flow.
What is OTP in Elixir?
OTP (Open Telecom Platform) is a collection of libraries and design principles used to build reliable, fault-tolerant Elixir applications.
What is GenServer?
GenServer is an OTP behavior used to implement server processes that maintain state and handle synchronous and asynchronous requests.
What are supervision trees?
Supervision trees monitor worker processes and automatically restart them if they fail, improving application reliability.
What is the Phoenix Framework?
Phoenix is a high-performance web framework for Elixir used to build scalable APIs, real-time applications, and web platforms.
How does concurrency work in Elixir?
Elixir achieves concurrency using lightweight processes that communicate through asynchronous message passing without shared memory.
Why is Elixir popular for backend development?
Elixir provides excellent scalability, high availability, fault tolerance, and real-time capabilities, making it ideal for backend systems.
Where is Elixir used?
Elixir is commonly used for chat applications, fintech platforms, IoT systems, APIs, distributed services, and other high-concurrency backend applications.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.