Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 48 ยท Projects

Project: Bank Account Process

Build a bank account as an Elixir process: state in a GenServer, call and cast messages, error tuples for bad requests, plus a runnable JavaScript actor model.

The todo project kept state in a value that you passed from function to function. In this project the state lives inside a process. A bank account is a perfect fit: many callers may deposit and withdraw at the same time, the balance must never become inconsistent, and a withdrawal that would overdraw the account has to be refused.

Because a process handles one message at a time, there are no locks and no race conditions. You will see the design with a real GenServer, which is read-only on this site, and then run the same behavior with a JavaScript actor that has a mailbox and an async message loop. If any idea feels new, review GenServer and Keeping State in a Process.

The account as a process

State The balance lives inside the process.
Mailbox Requests wait in line, one at a time.
Replies Callers get ok or error tuples.

One message at a time means no race conditions.

1 / 2

Step 1: the public API

The standard GenServer pattern splits a module into two halves: a client API that other code calls, and server callbacks that run inside the process. The API hides the messages, so callers never write GenServer.call themselves.

ELIXIR
defmodule Bank.Account do
  use GenServer

  # Client API

  def start_link(opts) do
    owner = Keyword.fetch!(opts, :owner)
    initial = Keyword.get(opts, :balance, 0)
    GenServer.start_link(__MODULE__, %{owner: owner, balance: initial, history: []})
  end

  def balance(account), do: GenServer.call(account, :balance)

  def deposit(account, amount), do: GenServer.call(account, {:deposit, amount})

  def withdraw(account, amount), do: GenServer.call(account, {:withdraw, amount})

  def statement(account), do: GenServer.call(account, :statement)

  def note(account, text), do: GenServer.cast(account, {:note, text})
end

start_link/1 takes the starting state in the init argument, here a map with the owner, the balance and a history list. Every request that needs an answer is a call. The only cast is a note, which is not worth waiting for.

Step 2: the callbacks

ELIXIR
  # Server callbacks

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

  @impl true
  def handle_call(:balance, _from, state) do
    {:reply, {:ok, state.balance}, state}
  end

  def handle_call({:deposit, amount}, _from, state) when is_integer(amount) and amount > 0 do
    new_state = record(state, {:deposit, amount}, state.balance + amount)
    {:reply, {:ok, new_state.balance}, new_state}
  end

  def handle_call({:withdraw, amount}, _from, state) when is_integer(amount) and amount > 0 do
    if amount > state.balance do
      {:reply, {:error, :insufficient_funds}, state}
    else
      new_state = record(state, {:withdraw, amount}, state.balance - amount)
      {:reply, {:ok, new_state.balance}, new_state}
    end
  end

  def handle_call({op, _amount}, _from, state) when op in [:deposit, :withdraw] do
    {:reply, {:error, :invalid_amount}, state}
  end

  def handle_call(:statement, _from, state) do
    {:reply, Enum.reverse(state.history), state}
  end

  @impl true
  def handle_cast({:note, text}, state) do
    {:noreply, %{state | history: [{:note, text} | state.history]}}
  end

  defp record(state, entry, balance) do
    %{state | balance: balance, history: [entry | state.history]}
  end

A few design choices are worth pointing out:

  • Guards make bad input a normal result. A non-integer or non-positive amount does not crash the account. The catch-all clause for deposit and withdraw replies {:error, :invalid_amount}. Clause order matters: the valid clauses come first, as taught in Multiple Clauses and Guards.
  • Overdrafts are an expected error, so the reply is {:error, :insufficient_funds} and the state does not change. Truly unexpected input, such as an unknown message, falls through and raises a FunctionClauseError, which crashes the process: let it crash, and a supervisor can restart it.
  • Money is an integer (cents, not floats), to avoid rounding errors.
  • The history is prepended and reversed on demand, which is the cheap way to grow a list.

Step 3: using it

In IEx, a session would look like this (sample session; nothing here ran on the site):

ELIXIR
{:ok, acct} = Bank.Account.start_link(owner: "Ana", balance: 100)
Bank.Account.deposit(acct, 50)      # {:ok, 150}
Bank.Account.withdraw(acct, 500)    # {:error, :insufficient_funds}
Bank.Account.withdraw(acct, -5)     # {:error, :invalid_amount}
Bank.Account.balance(acct)          # {:ok, 150}

Because all requests queue in the mailbox, ten processes depositing at once will all be applied one after another and the final balance will be correct. You can also give the account a name with name: Bank.Ana in start_link, so callers do not need the pid, and put it under a supervisor.

A runnable actor in JavaScript

JavaScript has no processes, but an object with a queue and an async loop behaves similarly: messages are processed strictly one at a time, in order. Below is a small Actor class that models GenServer.call with promises and GenServer.cast with a plain send. It is a teaching model, not the BEAM: it has no crash handling or supervision.

JS A bank account actor with call and cast (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The note is sent with cast and no reply is awaited, yet it still appears in the statement in the right place, because the mailbox keeps order. That is the guarantee you get from a real process too: messages from one sender arrive in the order they were sent.

Many callers at once

The point of the design is concurrency. Let us have several "customers" hit the same account at the same time, and check that no update is lost.

JS Concurrent deposits never lose an update

Press Run (or Ctrl + Enter) to see the console output here.

No output.

All twenty deposits land, and each reply is the balance right after that customer's own deposit. The drain loop is the only code that touches balance, so there is nothing to lock. A real GenServer gives you the same property by construction.

Extending the project

  • Add a transfer(from, to, amount) function. It needs two processes, so think about what happens if the second deposit fails after the first withdrawal. A common answer is to withdraw, try to deposit, and on failure deposit the money back (a compensating action).
  • Add a daily withdrawal limit stored in the state, and reset it with Process.send_after/3 and a handle_info/2 clause.
  • Start many accounts under a DynamicSupervisor and find them by name with a Registry, as in ETS, Registry and Application State.
  • Persist the history with Ecto or a file, and test with ExUnit using start_supervised!/1.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the account use call for deposits instead of cast?

    A call waits for a reply, which carries the result or an error. A cast is fire and forget and returns :ok immediately.
  2. 2. How does the process avoid race conditions on the balance?

    Only the process touches its state, and it handles messages sequentially, so updates cannot interleave.
  3. 3. What does the account reply to an overdraft request?

    An overdraft is an expected situation, so it is an error tuple, not a crash.
  4. 4. Why is the balance stored as an integer number of cents?

    Binary floats cannot represent most decimal amounts exactly. Integers in the smallest currency unit are exact.

Summary

  • A process owns the account state and handles requests one at a time, so concurrency is safe.
  • A client API hides the messages; callbacks handle_call/3 and handle_cast/2 hold the logic.
  • Use call when you need an answer, cast when you do not.
  • Guards and clause order turn invalid input into {:error, reason} replies, while unexpected messages crash and can be restarted by a supervisor.
  • Keep money in integers and history in a prepended list.
  • The JavaScript actor shows the mailbox idea, but it is a model, not the BEAM.

Next up: Project: Word Frequency Counter.