Implementing Clean Architecture in Clojure
Good architecture separates business logic from infrastructure. It is the foundation of almost every architecture you have studied. Separating responsibilities keeps you from being tied to a specific technology, like a database or a web framework, and as a side effect, it makes testing and modularity easier.
I decided to write this article because I needed to build a desktop application in Clojure, and the most natural option is Functional Core, Imperative Shell: the core of the application is only pure functions that receive data and return data. You will find it recommended in plenty of articles and talks because it fits so well with Clojure's immutability and pure functions. And if you use it, that's fine, it is very elegant to work with. However, it has a design problem that makes it hard to deal with uncertainty: if you don't know in advance what data you will need, the separation between the core and the infrastructure loses its clarity.
That is why I chose Clean Architecture, a first cousin of Hexagonal Architecture. It is a pattern I know in depth after applying it, and fighting with it, in other languages. Thanks to that experience, I was sure it would fit very well with a functional language.
This is not an article about Clean Architecture in general. If you are interested, I recommend reading my article Implementing Clean Architecture in Python. Broadly speaking, clean architecture splits the application into four layers:
flowchart TB
subgraph EI["External Interfaces"]
direction TB
subgraph GW["Gateways"]
direction TB
subgraph UC["Use Cases"]
direction TB
E["Entities"]
end
end
end
style EI fill:#dbeafe,stroke:#3b82f6,color:#1e3a8a
style GW fill:#dcfce7,stroke:#22c55e,color:#14532d
style UC fill:#fee2e2,stroke:#ef4444,color:#7f1d1d
style E fill:#fef9c3,stroke:#eab308,color:#713f12
- Entities: The business data.
- Use Cases: The business logic. They orchestrate the entities and talk to the outside world through interfaces.
- Gateways: The interfaces the use cases need to interact with the outside world.
- External Interfaces: The pieces that touch the real world, or infrastructure.
- Database
- File system
- REST API
- HTTP (website)
- CLI
And one golden rule: inner layers cannot depend on outer layers. For example, use cases cannot import an external interface.
Therefore:
flowchart LR
EI["External Interfaces"] -- "Calls come in through interfaces" --> CORE["Use Cases and Entities"]
CORE -. "Results go out as simple structures" .-> EI
style EI fill:#dbeafe,stroke:#3b82f6,color:#1e3a8a
style CORE fill:#fee2e2,stroke:#ef4444,color:#7f1d1d
The differences between Functional Core, Imperative Shell and Clean Architecture are not trivial.
| Clean Architecture | Functional core, imperative shell | |
|---|---|---|
| Separation criterion | Direction of dependencies | Purity |
| Can the core do IO? | Yes, through an interface | Never |
| Dependency injection | Protocols or functions | Not needed |
| Core tests | With test doubles | Only input and output data |
| Data the core needs | Asks for it when needed | All of it upfront |
Now, to adapt it to Clojure, we have to use the language's own quirks. Not much effort is needed, though, because Clojure's design already pushes you towards this pattern:
- Data is immutable. An entity cannot change behind your back.
- Maps are the universal structure. Maps go in, maps come out. No need to convert objects into DTOs, or DTOs into JSON.
- Protocols are interfaces. They define a contract that any implementation can fulfil, without inheritance.
- Functions are values. You can pass a dependency as an argument without any ceremony.
So each element of the architecture translates into its own nature:
- Entities: Maps and functions. No classes, obviously.
- Use Cases: Functions that orchestrate pure functions and side effects.
- Gateways: Protocols.
- External Interfaces: The libraries in the ecosystem that touch the real world: http-kit, Ring, Compojure, Hiccup, next.jdbc, etc.
Let's build a practical example and see how everything fits together.
Setting up the project
We are going to build a basic to-do list: create, list, mark as done and delete.
It will have two entry points in our infrastructure:
- A REST API that returns JSON.
- A web page with a few minimal forms, almost no HTML.
Both will use exactly the same use cases. That is the whole point of the architecture!
The folder structure will be the following:
- tasks: The main project folder.
- deps.edn: Dependencies and aliases.
- src/tasks: Source code.
- core: Business logic.
- entities
- task.clj
- gateways
- repository.clj
- use_cases
- response.clj
- tasks.clj
- entities
- infra: Infrastructure or external interfaces.
- database
- memory_repo.clj
- api
- routes.clj
- http
- routes.clj
- database
- main.clj
- core: Business logic.
At first, our repository (database) will live in memory. Later we will iterate towards better solutions, such as a file on disk or a conventional database like SQLite.
About how namespaces work, in case you are not used to Clojure: dashes become underscores in folder names. For example, the namespace tasks.core.use-cases.tasks lives in src/tasks/core/use_cases/tasks.clj. Dependencies, on the other hand, are defined in deps.edn.
- HTTP server: Ring + Jetty
- Routing: Compojure
- HTML rendering: Hiccup
- JSON: data.json
- Logs: slf4j-simple
;; deps.edn
{:paths ["src"]
:deps {org.clojure/clojure {:mvn/version "1.12.7"}
ring/ring-jetty-adapter {:mvn/version "1.15.6"}
compojure/compojure {:mvn/version "1.7.2"}
org.clojure/data.json {:mvn/version "2.5.2"}
hiccup/hiccup {:mvn/version "2.0.0"}
org.slf4j/slf4j-simple {:mvn/version "2.0.20"}}
:aliases {:run {:main-opts ["-m" "tasks.main"]}}}
All the libraries will be used in the infrastructure, never in the core.
Now let's define the entities, the business data, as data and pure functions.
Entities
In other languages the entity would be a class. We will use a map.
{:id #uuid "b1ef0868-8e2b-4ce8-87cc-c3b55ed11e46"
:title "Buy bread"
:done? false}
Not only is it easy to read, it also converts to JSON effortlessly and it is safe, since there is no mutability.
Now we need pure functions that build, transform and validate tasks.
;; src/tasks/core/entities/task.clj
(ns tasks.core.entities.task
(:require [clojure.string :as str]))
(def max-title-length 100)
(defn make-task
"Build a new pending task."
[id title]
{:id id
:title (str/trim title)
:done? false})
(defn complete
"Mark a task as done."
[task]
(assoc task :done? true))
(defn title-errors
"Return the list of errors of a title. Empty if the title is valid."
[title]
(cond
(not (string? title)) [{:field :title :message "Title is required"}]
(str/blank? title) [{:field :title :message "Title can't be empty"}]
(> (count (str/trim title)) max-title-length)
[{:field :title :message (str "Title can't be longer than " max-title-length " characters")}]
:else []))
The first reaction you would have in OOP is to make make-task generate a random id. Instead, we pass it in from outside. Generating a random identifier is a side effect, and we don't want side effects in the entities. The way it is designed now, the function always returns the same output for the same input. That is why it is a pure function.
Another detail is that complete does not modify the task. It returns a new one with :done? set to true, and the original stays intact.
Finally, title-errors does not throw exceptions. It returns a list of errors, empty if everything is fine.
We can try it in the REPL:
(complete (make-task 1 " Buy bread "))
;; {:id 1, :title "Buy bread", :done? true}
(title-errors "Buy bread")
;; []
(title-errors " ")
;; [{:field :title, :message "Title can't be empty"}]
With the entities ready, let's write the use cases, which orchestrate the entities and call the infrastructure through interfaces. They are no longer pure functions: that is the price of being able to ask for data right when they need it.
Use cases
First, let's define the shape of the responses: a map with 3 keys that every use case will return.
;; src/tasks/core/use_cases/response.clj
(ns tasks.core.use-cases.response)
(defn success [data]
{:type :success :errors [] :data data})
(defn parameters-error [errors]
{:type :parameters-error :errors errors :data {}})
(defn resource-error [field message]
{:type :resource-error :errors [{:field field :message message}] :data {}})
(defn system-error [error]
{:type :system-error :errors [{:field :system :message (ex-message error)}] :data {}})
:success: Everything went fine.:parameters-error: The input is wrong.:resource-error: The process is correct, but the resource does not exist.:system-error: Something blew up. An exception we have caught.
The use cases are the functions that implement the business logic: list, create, complete and delete tasks. They receive a repository as their first argument and return a response map.
;; src/tasks/core/use_cases/tasks.clj
(ns tasks.core.use-cases.tasks
(:require [tasks.core.entities.task :as task]
[tasks.core.gateways.repository :as repository]
[tasks.core.use-cases.response :as response]))
(defn list-tasks [repo]
(try
(response/success {:tasks (repository/find-all repo)})
(catch Exception error
(response/system-error error))))
(defn create-task [repo title]
(let [errors (task/title-errors title)]
(if (seq errors)
(response/parameters-error errors)
(try
(let [new-task (task/make-task (random-uuid) title)]
(repository/save! repo new-task)
(response/success {:task new-task}))
(catch Exception error
(response/system-error error))))))
(defn complete-task [repo id]
(try
(if-let [found (repository/find-by-id repo id)]
(let [done (task/complete found)]
(repository/save! repo done)
(response/success {:task done}))
(response/resource-error :id "Task not found"))
(catch Exception error
(response/system-error error))))
(defn delete-task [repo id]
(try
(if (repository/find-by-id repo id)
(do (repository/delete! repo id)
(response/success {:id id}))
(response/resource-error :id "Task not found"))
(catch Exception error
(response/system-error error))))
As you can see, we never throw an exception. If something fails, we return an error map. Now it is predictable, and we can decide what to do with the error in the infrastructure.
This is dependency injection in Clojure: passing the dependency as an argument.
Now let's define the contracts the use cases need to interact with the infrastructure.
Gateways: the contract and its first implementation
The use cases call repository/find-all, repository/save!, etc. It may look like it, but we are not calling a database. We can't. Remember the rule: the core cannot depend on the infrastructure.
To solve the problem, we create a contract that states what the repository must do, and any concrete implementation can fulfil it.
In Clojure we use defprotocol to define a contract and defrecord to implement it.
First, we define the contract:
;; src/tasks/core/gateways/repository.clj
(ns tasks.core.gateways.repository)
(defprotocol TaskRepository
(find-all [repo])
(find-by-id [repo id])
(save! [repo task])
(delete! [repo id]))
Now let's implement the functions of the in-memory repository, which will store the tasks in an atom.
;; src/tasks/infra/database/memory_repo.clj
(ns tasks.infra.database.memory-repo
(:require [tasks.core.gateways.repository :refer [TaskRepository]]))
(defrecord MemoryRepo [store]
TaskRepository
(find-all [_] (vals @store))
(find-by-id [_ id] (get @store id))
(save! [_ task] (swap! store assoc (:id task) task))
(delete! [_ id] (swap! store dissoc id)))
(defn make-memory-repo []
(->MemoryRepo (atom {})))
An atom is a mutable reference to an immutable value. I don't want to overwhelm you with Clojure technicalities. Just keep in mind that it is the simplest way to manage state.
An example of how it works:
(def store (atom {}))
@store
;; {}
(swap! store assoc 1 "Buy bread")
;; {1 "Buy bread"}
(swap! store assoc 2 "Call mom")
;; {1 "Buy bread", 2 "Call mom"}
(swap! store dissoc 1)
;; {2 "Call mom"}
Now we can inject a MemoryRepo into the use cases.
It is time to build the infrastructure, the next layer.
Infra: REST API
The first entry point is a REST API. We will use Compojure for routing and data.json to read and write JSON: each route receives JSON, calls the use case and returns JSON.
All the code lives in src/tasks/infra/api/routes.clj, which starts by declaring its dependencies.
;; src/tasks/infra/api/routes.clj
(ns tasks.infra.api.routes
(:require [clojure.data.json :as json]
[compojure.core :refer [DELETE GET PATCH POST context]]
[tasks.core.use-cases.tasks :as use-cases]))
First we need to translate the response type into an HTTP status code. A map is enough, and in Clojure a map can also be called as a function: (http-status :parameters-error) returns 400.
(def http-status
{:success 200
:parameters-error 400
:resource-error 404
:system-error 500})
This way we link each :type to its HTTP status code, so the infrastructure doesn't have to worry about business logic.
We also need a function that turns the use case result into an HTTP response with JSON.
(defn- json-response [result]
{:status (http-status (:type result))
:headers {"Content-Type" "application/json"}
:body (json/write-str result)})
Another one to read the request body and parse it into a map.
(defn- read-body [request]
(try
(json/read-str (slurp (:body request)) :key-fn keyword)
(catch Exception _ {})))
Finally, we define the API routes, which call the use cases and return the HTTP response.
(defn api-routes [repo]
(context "/api/tasks" []
(GET "/" []
(json-response (use-cases/list-tasks repo)))
(POST "/" request
(json-response (use-cases/create-task repo (:title (read-body request)))))
(PATCH "/:id" [id]
(json-response (use-cases/complete-task repo (parse-uuid id))))
(DELETE "/:id" [id]
(json-response (use-cases/delete-task repo (parse-uuid id))))))
The API validates nothing, and it doesn't know what a valid title is: it only receives, translates and delivers. It is robust, because if the body is not valid JSON, read-body returns an empty map and the use case replies that the title is missing. It is also aligned with the architecture. The HTTP status codes are the ones that match each response type, and the body is JSON with the same map the use case returns.
The API infrastructure is done. Now let's go for the web.
Infra: HTML forms
The second entry point, or way to interact with the use cases, is a page with an HTML form. We will include a minimal interface to create, complete and delete tasks.
To render HTML we will use Hiccup, which represents HTML as vectors and maps.
For example, the following vector:
[:ul
[:li "Buy bread"]
[:li "Call mom"]]
Is equivalent to this HTML:
<ul>
<li>Buy bread</li>
<li>Call mom</li>
</ul>
We will use forms to create, complete and delete tasks. Each form sends a POST to the matching route and, if everything goes well, the server redirects to the home page.
;; src/tasks/infra/http/routes.clj
(ns tasks.infra.http.routes
(:require [compojure.core :refer [GET POST routes]]
[hiccup2.core :as h]
[ring.util.response :refer [redirect]]
[tasks.core.use-cases.tasks :as use-cases]))
(defn- task-item [{:keys [id title done?]}]
[:li
(if done? [:s title] title)
(when-not done?
[:form {:method "post" :action (str "/tasks/" id "/complete")}
[:button "Done"]])
[:form {:method "post" :action (str "/tasks/" id "/delete")}
[:button "Delete"]]])
(defn- page [tasks errors]
(str
(h/html
[:html
[:body
[:h1 "Tasks"]
(for [{:keys [message]} errors]
[:p message])
[:form {:method "post" :action "/tasks"}
[:input {:name "title"}]
[:button "Add"]]
[:ul (map task-item tasks)]]])))
(defn- html-response [status body]
{:status status
:headers {"Content-Type" "text/html; charset=utf-8"}
:body body})
(defn http-routes [repo]
(routes
(GET "/" []
(let [result (use-cases/list-tasks repo)]
(html-response 200 (page (get-in result [:data :tasks]) (:errors result)))))
(POST "/tasks" [title]
(let [result (use-cases/create-task repo title)]
(if (= :success (:type result))
(redirect "/" :see-other)
(html-response 400 (page (get-in (use-cases/list-tasks repo) [:data :tasks])
(:errors result))))))
(POST "/tasks/:id/complete" [id]
(use-cases/complete-task repo (parse-uuid id))
(redirect "/" :see-other))
(POST "/tasks/:id/delete" [id]
(use-cases/delete-task repo (parse-uuid id))
(redirect "/" :see-other))))
Once again, the infrastructure knows nothing about the business logic. It translates the use cases into the language the browser speaks, and vice versa.
Main
We are missing main.clj, the entry point where the application is assembled.
;; src/tasks/main.clj
(ns tasks.main
(:require [compojure.core :refer [routes]]
[ring.adapter.jetty :refer [run-jetty]]
[ring.middleware.params :refer [wrap-params]]
[tasks.infra.api.routes :refer [api-routes]]
[tasks.infra.database.memory-repo :refer [make-memory-repo]]
[tasks.infra.http.routes :refer [http-routes]]))
(defn -main []
(let [repo (make-memory-repo)
app (routes (api-routes repo)
(http-routes repo))]
(run-jetty (wrap-params app) {:port 3000})))
Let's run it.
clojure -M:run
Let's try the API.
curl -X POST localhost:3000/api/tasks \
-H 'Content-Type: application/json' \
-d '{"title":"Buy bread"}'
{"type":"success","errors":[],"data":{"task":{"id":"ac089379-d761-4623-bce3-9f0fe6b7828f","title":"Buy bread","done?":false}}}
Now let's try to create a task with an empty title.
curl -X POST localhost:3000/api/tasks \
-H 'Content-Type: application/json' \
-d '{"title":""}'
{"type":"parameters-error","errors":[{"field":"title","message":"Title can't be empty"}],"data":{}}
Let's mark the task as done.
curl -X PATCH localhost:3000/api/tasks/ac089379-d761-4623-bce3-9f0fe6b7828f
{"type":"success","errors":[],"data":{"task":{"id":"ac089379-d761-4623-bce3-9f0fe6b7828f","title":"Buy bread","done?":true}}}
Now let's try the web version.
Open http://localhost:3000/ in the browser and you will see "Buy bread", crossed out. Add another task from the form and it will also show up in GET /api/tasks.
:quality(85)/https://andros.dev/media/blog/2026/11/clojure-clean-architecture-tasks.png)
If we submit the form empty, the page shows the same error the API returned. The entity decided it, the web just displays it.
:quality(85)/https://andros.dev/media/blog/2026/11/clojure-clean-architecture-tasks-error.png)
The full journey of a request:
sequenceDiagram
autonumber
participant U as User
participant W as HTML form (infra)
participant C as create-task (core)
participant E as Task entity (core)
participant R as MemoryRepo (infra)
U->>W: POST /tasks title=Buy bread
W->>C: (create-task repo "Buy bread")
C->>E: (title-errors "Buy bread")
E-->>C: []
C->>E: (make-task uuid "Buy bread")
E-->>C: {:id ... :title "Buy bread" :done? false}
C->>R: (save! repo task)
C-->>W: {:type :success ...}
W-->>U: 303 redirect to /
Call arrows always point inwards. What comes back is always a map.
We've got it!
However, there is a small problem: if we restart the application, the tasks disappear. We need to store them somewhere more permanent, like the disk.
Changing the database
EDN (extensible data notation) is Clojure's native data format. It looks like JSON, but it supports more types: keywords, sets, UUIDs or dates. That is why our tasks are stored and read back as they are, #uuid included.
We only need another implementation of the same protocol.
;; src/tasks/infra/database/edn_repo.clj
(ns tasks.infra.database.edn-repo
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[tasks.core.gateways.repository :refer [TaskRepository]]))
(defn- read-tasks [path]
(if (.exists (io/file path))
(edn/read-string (slurp path))
{}))
(defn- write-tasks! [path tasks]
(spit path (pr-str tasks)))
(defrecord EdnRepo [path]
TaskRepository
(find-all [_] (vals (read-tasks path)))
(find-by-id [_ id] (get (read-tasks path) id))
(save! [_ task] (write-tasks! path (assoc (read-tasks path) (:id task) task)))
(delete! [_ id] (write-tasks! path (dissoc (read-tasks path) id))))
(defn make-edn-repo [path]
(->EdnRepo path))
And in main.clj we change a single line (plus its require).
;; src/tasks/main.clj
(ns tasks.main
(:require ...
[tasks.infra.database.edn-repo :refer [make-edn-repo]])) ; Cambio
(defn -main []
(let [repo (make-edn-repo "tasks.edn") ; Cambio
...]))
Right in front of you is a practical example of how easy it is to change the infrastructure. Tomorrow it could be PostgreSQL or MongoDB, and the story would be the same: a new defrecord that fulfils TaskRepository.
However, reading and rewriting the whole file on every operation causes problems when several requests arrive at the same time: one write can overwrite another. We should use a conventional database like SQLite, which takes care of that.
SQLite database
Unlike other languages, almost nobody uses an ORM in Clojure. It makes no sense to turn rows into objects when there are no objects. A row is already a map.
The ecosystem looks like this:
- next.jdbc: The reference library. It includes functions like
insert!,get-by-idordelete!for everyday CRUD. - HoneySQL: Write SQL as data structures.
- HugSQL: Plain SQL in
.sqlfiles, turned into Clojure functions. - Toucan 2: The most complete option. It is the closest thing to an ORM, with models, hooks and column transformations.
We will use next.jdbc. We add next.jdbc and the SQLite JDBC driver to :deps in deps.edn.
;; deps.edn (en :deps)
com.github.seancorfield/next.jdbc {:mvn/version "1.4.72"}
org.xerial/sqlite-jdbc {:mvn/version "3.54.1.0"}
And a JVM option to the :run alias. The SQLite driver loads a native library, and recent Java versions warn about it on every start. This option silences the warning.
;; deps.edn (en :aliases)
:run {:jvm-opts ["--enable-native-access=ALL-UNNAMED"]
:main-opts ["-m" "tasks.main"]}
And the new repository.
;; src/tasks/infra/database/sqlite_repo.clj
(ns tasks.infra.database.sqlite-repo
(:require [next.jdbc :as jdbc]
[next.jdbc.result-set :as rs]
[next.jdbc.sql :as sql]
[tasks.core.gateways.repository :refer [TaskRepository]]))
(def ^:private options {:builder-fn rs/as-unqualified-maps})
(defn- row->task [{:keys [id title done]}]
{:id (parse-uuid id)
:title title
:done? (= 1 done)})
(defn- task->row [{:keys [id title done?]}]
{:id (str id)
:title title
:done (if done? 1 0)})
(defrecord SqliteRepo [datasource]
TaskRepository
(find-all [_]
(map row->task (sql/query datasource ["SELECT * FROM tasks"] options)))
(find-by-id [_ id]
(some-> (sql/get-by-id datasource :tasks (str id) options) row->task))
(save! [_ task]
(let [{:keys [id title done]} (task->row task)]
(jdbc/execute-one! datasource
["INSERT INTO tasks (id, title, done) VALUES (?, ?, ?)
ON CONFLICT (id) DO UPDATE SET title = excluded.title, done = excluded.done"
id title done])))
(delete! [_ id]
(sql/delete! datasource :tasks {:id (str id)})))
(defn make-sqlite-repo [path]
(let [datasource (jdbc/get-datasource {:dbtype "sqlite" :dbname path})]
(jdbc/execute! datasource ["CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0)"])
(->SqliteRepo datasource)))
Look at the row->task and task->row functions. SQLite has no UUID or boolean types, and done? is not a valid column name in SQL without quotes. So the repository translates both: the UUID travels as text and :done? as a 0 or a 1. The rest of the details come straight from the next.jdbc documentation.
To change the database, once again, we only change one line (plus its require).
;; src/tasks/main.clj
(ns tasks.main
(:require ...
[tasks.infra.database.sqlite-repo :refer [make-sqlite-repo]])) ; Cambio
(defn -main []
(let [repo (make-sqlite-repo "tasks.db") ; Cambio
...]))
We run it, create a task from the form and another from the API, and look inside the database.
sqlite3 tasks.db 'SELECT * FROM tasks'
f2ef2060-0dd2-4627-928c-4302bf27a36d|Buy bread|0
fa7be8c4-ba42-4d4f-bcb7-02615d5acb36|Call mom|0
The infrastructure keeps changing, and the core stays intact.
Final notes
Back to the desktop application that brought me here: there, the infrastructure was the graphical interface, built with cljfx, and a JSON-RPC API. The core followed exactly the same structure. The infrastructure changes, not the business logic.
I have left testing out, it would deserve its own article. With this architecture it is extraordinarily cheap. The use cases are tested by injecting a MemoryRepo, and Ring routes are functions that receive a map and return another one, so they can be tested without starting the server.
One last thought about Functional Core. To get around the flaw I pointed out at the beginning, yogthos proposes modelling the flow as a state machine, where each step receives a map of resources as its first argument. In my opinion, deep down it is the same idea as Clean Architecture: IO comes in as an explicit argument.
I hope this article serves as a starting point for building Clojure applications with an architecture where the business logic is separated from the infrastructure.
Now it's time to open the REPL and paste the examples. There is no better teacher than practice.
- Setting up the project
- Entities
- Use cases
- Gateways: the contract and its first implementation
- Infra: REST API
- Infra: HTML forms
- Main
- Changing the database
- SQLite database
- Final notes
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Help me keep writing
Every coffee gives me a push toward the next article.
Sure, it's on me!
Comments
There are no comments yet.