Sometimes you have a pure function that is expensive to run and gets called with the same input again and again. Rendering Markdown with syntax highlighting is a good example: it’s CPU-heavy, the output depends only on the input, and the same document is requested over and over.
You could reach for a caching library, and often that’s the right call. But for a small, well-bounded case, a plain ETS table gets you surprisingly far in about 70 lines. Here’s the technique and the traps to avoid.
The shape of the solution
Three ideas, each small:
- A GenServer that only owns the table. It does no work on the hot path.
- A public ETS table, so callers read and write directly, without going through a single process.
- A cache key that includes everything the output depends on, so you never need to invalidate by hand.
1. The GenServer is just a table owner
An ETS table lives as long as the process that created it. Put that process in your supervision tree, and the table follows the lifecycle of your app.
The common mistake is to route every read through the GenServer. That turns a concurrent data structure into a bottleneck: one process handling one message at a time. Instead, make the table :public and let callers talk to ETS directly:
defmodule MyApp.Renderer.Cache do
use GenServer
@table __MODULE__
def start_link(opts \\ []),
do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
@impl true
def init(_opts) do
:ets.new(@table, [
:set,
:public,
:named_table,
read_concurrency: true,
write_concurrency: true
])
{:ok, nil}
end
end
read_concurrency: true optimizes for many simultaneous readers, which is exactly the access pattern of a cache. The GenServer has no handle_call at all; its only job is to keep the table alive.
2. A fetch/3 that computes on a miss
The public API is a single function: give it an input, a version, and a function that produces the value on a miss.
def fetch(input, version, fun) when is_binary(input) and is_function(fun, 0) do
key = {version, :crypto.hash(:sha256, input)}
case lookup(key) do
{:ok, value} ->
value
:error ->
value = fun.()
put(key, value)
value
end
end
defp lookup(key) do
case :ets.lookup(@table, key) do
[{^key, value}] -> {:ok, value}
[] -> :error
end
rescue
ArgumentError -> :error
end
The rescue ArgumentError is deliberate. If the table does not exist (the cache process is down or restarting), :ets.lookup/2 raises. Treating that as a miss means the cache can fail without taking the feature down: you just fall back to computing the value. A cache should never be a hard dependency.
Calling it looks like this:
def render_article(markdown) do
Cache.fetch(markdown, renderer_version(), fn ->
markdown
|> sanitize()
|> convert_to_html()
end)
end
3. Put the version in the key
This is the part that removes the hardest problem in caching.
The key is {version, sha256(input)}:
- The hash means identical input hits the same entry, and the key stays small no matter how large the document is.
- The version captures everything else the output depends on. Here, it’s a fingerprint built from the versions of the libraries doing the work:
def renderer_version do
"mdex-#{app_version(:mdex)}+lumis-#{app_version(:lumis)}"
end
defp app_version(app) do
case Application.spec(app, :vsn) do
vsn when is_list(vsn) -> List.to_string(vsn)
nil -> "unknown"
end
end
When you upgrade a dependency, the version string changes, every old key becomes unreachable, and new requests render fresh output. No flush on deploy, no “did we remember to clear the cache?” step. If you change your own rendering logic in a way the dependencies cannot detect, add a manual @version "2" to the fingerprint and bump it.
Stale entries are never served; they just sit there until the table is trimmed.
Keeping it bounded
A cache without a limit is a memory leak with good intentions. The simplest bound that works:
@max_entries 500
defp put(key, value) do
if :ets.info(@table, :size) >= @max_entries,
do: :ets.delete_all_objects(@table)
:ets.insert(@table, {key, value})
rescue
ArgumentError -> :ok
end
When the table is full, throw everything away. It’s crude, and I wouldn’t call it a good eviction policy. But it’s bounded, it’s one line, and the worst case is that some entries get recomputed. For a cache whose misses are merely slow rather than dangerous, that’s a fair trade.
What this does not give you
Be honest about the limits. This approach is a good fit for small caches and a poor one when you need any of the following:
- Real eviction. Flushing everything at the limit means a busy moment can empty a warm cache. If you care about keeping the hottest entries, you want LRU or something similar.
- TTLs. Entries live until the next flush. That’s fine when the key already encodes everything that matters, but wrong for data that goes stale with time.
- Stampede protection. If ten requests miss the same key at once, all ten compute the value. For expensive work under bursty traffic, you want single-flight behavior, where one caller computes and the rest wait.
- Sharing across nodes. The table is local to one node. Each node warms its own copy.
If you need those features, a library such as Cachex provides them. The migration is small precisely because the call site is a single fetch. Start simple, and swap the implementation when a real limitation shows up.
Testing it
Because the interesting behavior is “computed once per key and version,” the tests are short. Count how many times the function runs:
test "computes the value only once per input and version" do
input = "once #{System.unique_integer([:positive])}"
{:ok, calls} = Agent.start_link(fn -> 0 end)
compute = fn ->
Agent.update(calls, &(&1 + 1))
"html"
end
assert Cache.fetch(input, "v1", compute) == "html"
assert Cache.fetch(input, "v1", compute) == "html"
assert Agent.get(calls, & &1) == 1
end
test "does not share entries between versions" do
input = "versioned #{System.unique_integer([:positive])}"
assert Cache.fetch(input, "v1", fn -> "old" end) == "old"
assert Cache.fetch(input, "v2", fn -> "new" end) == "new"
assert Cache.fetch(input, "v1", fn -> "unused" end) == "old"
end
Note the System.unique_integer/1 in the input. The table is global, so tests that run concurrently must use distinct keys or they’ll interfere with each other.
Takeaways
- Use a GenServer to own an ETS table, not to serve it.
- Make the table public with
read_concurrency: trueand let callers hit ETS directly. - Put everything the output depends on into the key, and you can skip invalidation entirely.
- Treat a missing table as a cache miss, so the cache can never take the feature down.
- Always bound the size, even if the policy is blunt.
- Know where this stops being enough, and have a plan for what you would swap in.
It’s not a replacement for a full caching library. It’s a good way to avoid pulling one in until you actually need it.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.