Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: Event-Sourced Bank Accounts

Build a bank account system in Clojure: immutable data, validation, an event log folded with reduce, atoms and refs for state, transfers in dosync and tests.

This project ties together the chapters on data, state and concurrency. We build a small bank where accounts hold money, deposits, withdrawals and transfers are validated, and every change is recorded as an event. The current state is nothing more than a fold (a reduce) over the events. That pattern, event sourcing, is a natural fit for Clojure, because state is a value computed from an immutable history.

Clojure code is read-only on this site, and the runnable examples mirror the logic in JavaScript so you can test the design.

Step 1: the data

Events are plain maps. A map per account holds the balance, and the whole bank is a map from account id to account:

CLOJURE
{:type :deposit  :account "ana" :amount 100}
{:type :withdraw :account "ana" :amount 30}
{:type :transfer :from "ana" :to "ben" :amount 20}

;; bank state
{"ana" {:balance 50} "ben" {:balance 20}}

Nothing here needs a class: maps and keywords are enough, and they print, compare and serialize for free.

Step 2: apply one event (a pure function)

apply-event takes the current state and an event and returns the new state. A case on :type selects the rule (a multimethod would let others add types later).

CLOJURE
(defn apply-event [bank {:keys [type account from to amount] :as event}]
  (case type
    :open      (assoc bank account {:balance 0})
    :deposit   (update-in bank [account :balance] + amount)
    :withdraw  (update-in bank [account :balance] - amount)
    :transfer  (-> bank
                   (update-in [from :balance] - amount)
                   (update-in [to   :balance] + amount))
    (throw (ex-info "Unknown event" {:event event}))))

update-in reaches into nested maps and applies a function: (update-in bank ["ana" :balance] + 100) is bank with Ana's balance increased by 100.

Step 3: validate before recording

A command may be rejected (insufficient funds, unknown account). We check against the current state and return either an event or an error as data:

CLOJURE
(defn validate [bank {:keys [type account from to amount]}]
  (cond
    (and amount (not (pos? amount)))               "amount must be positive"
    (and account (not= type :open) (not (bank account))) (str "no such account: " account)
    (and (= type :withdraw) (< (get-in bank [account :balance]) amount)) "insufficient funds"
    (and (= type :transfer) (not (bank from)))     (str "no such account: " from)
    (and (= type :transfer) (not (bank to)))       (str "no such account: " to)
    (and (= type :transfer) (< (get-in bank [from :balance]) amount)) "insufficient funds"
    :else nil))   ; nil means valid

Returning a message (or nil) rather than throwing keeps validation easy to test. The shape "nil = OK, string = reason" is a simple convention; clojure.spec could describe the events too (see spec).

Step 4: the state and the log

We store two things in one atom, so both always change together:

CLOJURE
(def bank (atom {:accounts {} :log []}))

(defn execute! [event]
  (let [result (atom nil)]
    (swap! bank
           (fn [{:keys [accounts log] :as state}]
             (if-let [err (validate accounts event)]
               (do (reset! result {:error err}) state)   ; leave state unchanged
               (do (reset! result {:ok event})
                   {:accounts (apply-event accounts event)
                    :log (conj log event)}))))
    @result))

An aside: swap! may retry its function (atoms), so the function should be pure. Writing into the local result atom is harmless because it is thrown away on each attempt and overwritten, but a cleaner design returns the result in the state, or uses swap-vals!. The core rule remains: put no network calls or printing inside the swap function.

CLOJURE
(execute! {:type :open :account "ana"})
(execute! {:type :deposit :account "ana" :amount 100})
(execute! {:type :withdraw :account "ana" :amount 500})
;=> {:error "insufficient funds"}

Step 5: rebuild state from history

Because state is a fold over events, we can recreate it anywhere, at any point in the past:

CLOJURE
(defn replay [events]
  (reduce apply-event {} events))

(replay (:log @bank))              ; state now
(replay (take 2 (:log @bank)))     ; state after the first two events

This gives you an audit trail and time travel for free, something mutable-object designs can only approximate.

Step 6: transfers with refs

Suppose instead each account is its own ref, because accounts change independently and a transfer touches two. Then dosync makes the transfer atomic (refs and STM):

CLOJURE
(defn open-account [balance] (ref balance :validator #(>= % 0)))

(defn transfer! [from to amount]
  (dosync
    (alter from - amount)
    (alter to   + amount)))

(def ana (open-account 100))
(def ben (open-account 20))
(transfer! ana ben 30)
[@ana @ben]   ;=> [70 50]

(transfer! ana ben 1000)   ; validator rejects: whole transaction rolls back
[@ana @ben]                 ;=> [70 50]

Which design is better? One atom plus an event log is simple and gives history; refs scale to many independent accounts with fine-grained coordination. Both are valid, and comparing them is the lesson.

Step 7: test it

CLOJURE
(deftest replay-test
  (let [events [{:type :open :account "ana"}
                {:type :open :account "ben"}
                {:type :deposit :account "ana" :amount 100}
                {:type :transfer :from "ana" :to "ben" :amount 40}]]
    (is (= {"ana" {:balance 60} "ben" {:balance 40}}
           (replay events)))))

(deftest validation-test
  (is (= "insufficient funds"
         (validate {"ana" {:balance 10}} {:type :withdraw :account "ana" :amount 50}))))

Extensions

  • Add interest events computed by a scheduled agent.
  • Add snapshots: store state every 100 events so replay is fast.
  • Use a core.async channel as an inbox so many clients send commands to one processing loop (core.async).
  • Persist the log to a file with spit and :append true, writing one EDN map per line, and reload with edn/read-string.

Try it: the event log, in JavaScript

JS Event-sourced bank

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

No output.

Try it: all-or-nothing transfers

This models dosync with validators: both balances change together or not at all.

JS Atomic transfer with rollback

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In event sourcing, how is the current state computed?

    State is a value derived from history: (reduce apply-event {} events).
  2. 2. What does (update-in bank ["ana" :balance] + 100) do?

    update-in applies the function to the nested value and returns a new map; the original is unchanged.
  3. 3. Why return an error message from validate instead of throwing?

    Rejected commands are an expected outcome, not an exceptional one, and data results compose well.
  4. 4. How does the ref version keep a transfer consistent?

    STM transactions are atomic: a failed validator or conflict discards the whole transaction.

Summary

  • Plain maps and keywords model events and state; apply-event is a pure function and replay is a reduce.
  • Validate commands into data (nil or a message) before recording them.
  • One atom can hold state and log together; many independent accounts suit refs with dosync.
  • The event log gives auditing and time travel; test by replaying fixed events.

Next: Practice Problems