TExcelTAD
Home › Elixir › Elixir Mini Project

Elixir Mini Project

In this project you'll build a small order processing service for an online shop, step by step. It brings together much of the course: structs, pattern matching, error tuples and with, Enum pipelines, a GenServer holding state, concurrent clients with Task, a supervisor that restarts the service, and files.

By the end, the service can:

  • load a product catalogue from CSV text,
  • validate and place orders, reserving stock,
  • handle many concurrent customers safely,
  • recover from a crash under a supervisor,
  • write a sales report to a file.

Every step is a complete script you can run with elixir main.exs.

Step 1: Products from CSV

We start with pure functions: a Product struct and a parser that turns CSV text into products. Prices are stored as integer cents to avoid floating-point rounding. Bad lines are reported, not silently dropped.

elixir · try it yourself
defmodule Shop.Product do
  defstruct [:sku, :name, :price_cents, :stock]

  def parse_line(line) do
    with [sku, name, price, stock] <- String.split(line, ","),
         {price_cents, ""} <- Integer.parse(String.trim(price)),
         {stock, ""} <- Integer.parse(String.trim(stock)) do
      {:ok, %__MODULE__{sku: String.trim(sku), name: String.trim(name), price_cents: price_cents, stock: stock}}
    else
      _ -> {:error, {:bad_line, line}}
    end
  end

  def format_price(cents), do: "#{div(cents, 100)}.#{String.pad_leading(Integer.to_string(rem(cents, 100)), 2, "0")}"
end

defmodule Shop.Catalog do
  alias Shop.Product

  def load(csv) do
    results =
      csv
      |> String.split("\n", trim: true)
      |> Enum.drop(1)
      |> Enum.map(&Product.parse_line/1)

    products = for {:ok, p} <- results, into: %{}, do: {p.sku, p}
    errors = for {:error, e} <- results, do: e
    {products, errors}
  end
end

csv = """
sku,name,price_cents,stock
LMP-1,Desk lamp,2499,5
MUG-2,Coffee mug,899,20
BAD-LINE
KEY-3,Keyboard,4950,2
"""

{products, errors} = Shop.Catalog.load(csv)

products
|> Map.values()
|> Enum.sort_by(& &1.sku)
|> Enum.each(fn p ->
  IO.puts("#{p.sku}  #{String.pad_trailing(p.name, 12)} #{String.pad_leading(Shop.Product.format_price(p.price_cents), 6)}  (#{p.stock} in stock)")
end)

IO.inspect(errors)
KEY-3  Keyboard      49.50  (2 in stock)
LMP-1  Desk lamp     24.99  (5 in stock)
MUG-2  Coffee mug     8.99  (20 in stock)
[bad_line: "BAD-LINE"]

The comprehension for {:ok, p} <- results keeps only the successful results, because elements that don't match the pattern are skipped. The error list [{:bad_line, "BAD-LINE"}] is printed as [bad_line: "BAD-LINE"]: a list of {atom, value} tuples is a keyword list.

Step 2: Placing an order

An order is a list of {sku, quantity} lines. Placing it must check every line and either succeed completely (returning the new catalogue and an invoice) or fail without changing anything. with chains the steps; Enum.reduce_while/3 stops at the first bad line.

elixir · try it yourself
defmodule Shop.Product do
  defstruct [:sku, :name, :price_cents, :stock]
end

defmodule Shop.Orders do
  def place(products, lines) do
    with :ok <- validate_not_empty(lines),
         {:ok, products, invoice} <- reserve_all(products, lines) do
      {:ok, products, invoice}
    end
  end

  defp validate_not_empty([]), do: {:error, :empty_order}
  defp validate_not_empty(_), do: :ok

  defp reserve_all(products, lines) do
    Enum.reduce_while(lines, {:ok, products, []}, fn {sku, qty}, {:ok, products, invoice} ->
      case reserve(products, sku, qty) do
        {:ok, product} ->
          line = {sku, qty, qty * product.price_cents}
          {:cont, {:ok, Map.put(products, sku, product), [line | invoice]}}

        error ->
          {:halt, error}
      end
    end)
    |> case do
      {:ok, products, invoice} -> {:ok, products, Enum.reverse(invoice)}
      error -> error
    end
  end

  defp reserve(_products, _sku, qty) when not is_integer(qty) or qty <= 0, do: {:error, :invalid_quantity}

  defp reserve(products, sku, qty) do
    case Map.fetch(products, sku) do
      :error -> {:error, {:unknown_sku, sku}}
      {:ok, %{stock: stock}} when stock < qty -> {:error, {:out_of_stock, sku, stock}}
      {:ok, product} -> {:ok, %{product | stock: product.stock - qty}}
    end
  end
end

defmodule Demo do
  alias Shop.Product

  def run do
    products = %{
      "LMP-1" => %Product{sku: "LMP-1", name: "Desk lamp", price_cents: 2499, stock: 5},
      "KEY-3" => %Product{sku: "KEY-3", name: "Keyboard", price_cents: 4950, stock: 2}
    }

    {:ok, products, invoice} = Shop.Orders.place(products, [{"LMP-1", 2}, {"KEY-3", 1}])
    IO.inspect(invoice)
    IO.inspect({products["LMP-1"].stock, products["KEY-3"].stock})

    IO.inspect(Shop.Orders.place(products, [{"LMP-1", 1}, {"KEY-3", 5}]))
    IO.inspect(Shop.Orders.place(products, [{"PEN-9", 1}]))
    IO.inspect(Shop.Orders.place(products, [{"LMP-1", 0}]))
    IO.inspect(Shop.Orders.place(products, []))
  end
end

Demo.run()
[{"LMP-1", 2, 4998}, {"KEY-3", 1, 4950}]
{3, 1}
{:error, {:out_of_stock, "KEY-3", 1}}
{:error, {:unknown_sku, "PEN-9"}}
{:error, :invalid_quantity}
{:error, :empty_order}

The failed order for KEY-3 didn't change the lamp stock either: the function only returns the updated catalogue when every line succeeded. Immutability makes this "all or nothing" behaviour free; there is nothing to roll back.

Step 3: A store process for concurrent customers

Many customers order at the same time, so the catalogue needs a single owner that applies orders one at a time: a GenServer. The pure Orders.place/2 from step 2 does the work; the server just keeps the state and records sales.

elixir · try it yourself
defmodule Shop.Product do
  defstruct [:sku, :name, :price_cents, :stock]
end

defmodule Shop.Orders do
  def place(products, lines) do
    Enum.reduce_while(lines, {:ok, products, 0}, fn {sku, qty}, {:ok, products, total} ->
      case Map.fetch(products, sku) do
        {:ok, %{stock: stock} = p} when stock >= qty ->
          {:cont, {:ok, Map.put(products, sku, %{p | stock: stock - qty}), total + qty * p.price_cents}}

        {:ok, %{stock: stock}} ->
          {:halt, {:error, {:out_of_stock, sku, stock}}}

        :error ->
          {:halt, {:error, {:unknown_sku, sku}}}
      end
    end)
  end
end

defmodule Shop.Store do
  use GenServer

  def start_link(products), do: GenServer.start_link(__MODULE__, products, name: __MODULE__)
  def order(customer, lines), do: GenServer.call(__MODULE__, {:order, customer, lines})
  def stock(sku), do: GenServer.call(__MODULE__, {:stock, sku})
  def sales, do: GenServer.call(__MODULE__, :sales)

  @impl true
  def init(products), do: {:ok, %{products: products, sales: []}}

  @impl true
  def handle_call({:order, customer, lines}, _from, state) do
    case Shop.Orders.place(state.products, lines) do
      {:ok, products, total} ->
        {:reply, {:ok, total}, %{state | products: products, sales: [{customer, total} | state.sales]}}

      error ->
        {:reply, error, state}
    end
  end

  def handle_call({:stock, sku}, _from, state), do: {:reply, state.products[sku].stock, state}
  def handle_call(:sales, _from, state), do: {:reply, Enum.reverse(state.sales), state}
end

defmodule Demo do
  alias Shop.Product

  def run do
    {:ok, _} = Shop.Store.start_link(%{"LMP-1" => %Product{sku: "LMP-1", name: "Desk lamp", price_cents: 2499, stock: 5}})

    # 8 customers try to buy one lamp each at the same time; only 5 lamps exist.
    results =
      1..8
      |> Enum.map(fn n -> Task.async(fn -> Shop.Store.order("customer-#{n}", [{"LMP-1", 1}]) end) end)
      |> Task.await_many()

    IO.inspect(Enum.frequencies_by(results, fn r -> elem(r, 0) end))
    IO.inspect(Shop.Store.stock("LMP-1"))
    IO.inspect(length(Shop.Store.sales()))
  end
end

Demo.run()
%{error: 3, ok: 5}
0
5

Exactly five orders succeed and three get {:error, {:out_of_stock, ...}}: the stock never goes negative, no matter how the eight tasks are scheduled. Which customers win depends on timing, so the program prints counts rather than names. That's the kind of output you can rely on in concurrent code.

Step 4: Supervision

If the store crashes (a bug, a bad message), a supervisor starts a fresh one. Its init/1 reloads the catalogue from a source of truth, here a function standing in for a database, so the store comes back in a known state.

elixir · try it yourself
# Crash reports are logged with timestamps; silence them to keep the output stable.
Logger.configure(level: :none)

defmodule Shop.Store do
  use GenServer

  def start_link(load_fun), do: GenServer.start_link(__MODULE__, load_fun, name: __MODULE__)
  def stock(sku), do: GenServer.call(__MODULE__, {:stock, sku})
  def sell(sku, qty), do: GenServer.call(__MODULE__, {:sell, sku, qty})

  @impl true
  def init(load_fun), do: {:ok, load_fun.()}

  @impl true
  def handle_call({:stock, sku}, _from, stock), do: {:reply, Map.fetch(stock, sku), stock}

  def handle_call({:sell, sku, qty}, _from, stock) do
    # Bug on purpose: an unknown SKU makes Map.fetch! raise and crashes the store
    current = Map.fetch!(stock, sku)
    {:reply, :ok, Map.put(stock, sku, current - qty)}
  end
end

load_from_db = fn -> %{"LMP-1" => 5, "MUG-2" => 20} end

children = [{Shop.Store, load_from_db}]
{:ok, _sup} = Supervisor.start_link(children, strategy: :one_for_one)

:ok = Shop.Store.sell("LMP-1", 2)
IO.inspect(Shop.Store.stock("LMP-1"))

before = Process.whereis(Shop.Store)

result =
  try do
    Shop.Store.sell("NOPE", 1)
  catch
    :exit, _reason -> :store_crashed
  end

IO.inspect(result)
Process.sleep(50)

IO.inspect(Process.whereis(Shop.Store) != before)
IO.inspect(Shop.Store.stock("LMP-1"))
IO.inspect(Shop.Store.stock("MUG-2"))
{:ok, 3}
:store_crashed
true
{:ok, 5}
{:ok, 20}

The caller sees the crash as an exit from GenServer.call/2 and handles it. The supervisor restarts the store, which reloads the stock: the lamp count is 5 again, because the sale in memory was lost with the crashed process. That's why real systems persist important changes (in a database) before replying, and why init/1 reloads from there.

Step 5: The sales report

Finally, a report: totals per product, formatted as a table, written to a file and read back. Formatting is kept in pure functions so it is easy to test.

elixir · try it yourself
defmodule Shop.Report do
  def build(sales) do
    sales
    |> Enum.group_by(fn {sku, _qty, _cents} -> sku end)
    |> Enum.map(fn {sku, rows} ->
      {sku, Enum.sum(Enum.map(rows, &elem(&1, 1))), Enum.sum(Enum.map(rows, &elem(&1, 2)))}
    end)
    |> Enum.sort_by(fn {sku, _qty, cents} -> {-cents, sku} end)
  end

  def to_text(rows) do
    header = "SKU      QTY    REVENUE"
    lines = Enum.map(rows, fn {sku, qty, cents} -> row(sku, qty, cents) end)
    total = Enum.sum(Enum.map(rows, &elem(&1, 2)))
    Enum.join([header, String.duplicate("-", 23)] ++ lines ++ [row("TOTAL", "", total)], "\n") <> "\n"
  end

  defp row(sku, qty, cents) do
    String.pad_trailing(sku, 8) <> String.pad_leading(to_string(qty), 4) <> String.pad_leading(money(cents), 11)
  end

  defp money(cents), do: "#{div(cents, 100)}.#{String.pad_leading(Integer.to_string(rem(cents, 100)), 2, "0")}"
end

sales = [
  {"LMP-1", 2, 4998},
  {"MUG-2", 4, 3596},
  {"KEY-3", 1, 4950},
  {"MUG-2", 1, 899},
  {"LMP-1", 1, 2499}
]

report = sales |> Shop.Report.build() |> Shop.Report.to_text()

path = "/tmp/sales_report.txt"
File.write!(path, report)

IO.puts("Wrote #{byte_size(report)} bytes to #{Path.basename(path)}")
IO.write(File.read!(path))
Wrote 144 bytes to sales_report.txt
SKU      QTY    REVENUE
-----------------------
LMP-1      3      74.97
KEY-3      1      49.50
MUG-2      5      44.95
TOTAL            169.42

Where to go from here

  • Put each module in its own file in a Mix project (mix new shop --sup) and start Shop.Store from Shop.Application.
  • Write ExUnit tests for Shop.Product.parse_line/1, Shop.Orders.place/2 and Shop.Report.to_text/1: they are pure, so the tests are simple.
  • Persist the catalogue and sales with Ecto, and expose the store through a Phoenix JSON API or a LiveView dashboard.
  • Use Phoenix.PubSub to broadcast each sale so dashboards update in real time.

Test yourself

Why does a failed order in step 2 leave the stock unchanged?

  1. Because of a database transaction
  2. Because the updated map is only returned when every line succeeds, and data is immutable
  3. Because the GenServer rolls back
  4. It doesn't

In step 3, why can't two customers buy the last lamp at the same time?

  1. Tasks run one after another
  2. The Store GenServer handles one call at a time
  3. ETS locks the row
  4. Elixir is single-threaded

After the restart in step 4, why is the lamp stock 5 again?

  1. The supervisor saved the state
  2. The new process ran init/1, which reloaded the stock from the source of truth
  3. The crash was ignored
  4. Supervisors replay messages