Elixir ETS Tables
ETS (Erlang Term Storage) is an in-memory key-value store built into the BEAM. An ETS table lives outside the memory of any single process, so many processes can read and write it concurrently without sending messages to a single owner. It is the standard tool for caches, lookup tables and counters that are read far more often than they are written.
ETS is an Erlang module, so you call it with an atom: :ets.new/2, :ets.insert/2, :ets.lookup/2.
Creating a table and storing tuples
A table stores tuples. By default, the first element of the tuple is the key:
table = :ets.new(:products, [:set, :public])
:ets.insert(table, {"SKU-1", "Keyboard", 49.0})
:ets.insert(table, [{"SKU-2", "Mouse", 19.5}, {"SKU-3", "Monitor", 189.0}])
IO.inspect(:ets.lookup(table, "SKU-2"))
IO.inspect(:ets.lookup(table, "SKU-9"))
IO.inspect(:ets.info(table, :size))
:ets.insert(table, {"SKU-2", "Wireless mouse", 24.0}) # same key: replaced in a :set
IO.inspect(:ets.lookup(table, "SKU-2"))
:ets.delete(table, "SKU-1")
IO.inspect(:ets.member(table, "SKU-1"))[{"SKU-2", "Mouse", 19.5}]
[]
3
[{"SKU-2", "Wireless mouse", 24.0}]
false
lookup/2 always returns a list of matching tuples, which is empty when the key is missing.
Table types and access
| Option | Meaning |
|---|---|
:set (default) |
one tuple per key |
:ordered_set |
like :set, kept sorted by key |
:bag |
many tuples per key, no exact duplicates |
:duplicate_bag |
many tuples per key, duplicates allowed |
:protected (default) |
owner writes, any process reads |
:public |
any process reads and writes |
:private |
only the owner process |
:named_table |
refer to the table by its atom name |
read_concurrency: true |
optimise for many concurrent readers |
:ets.new(:tags, [:bag, :named_table])
:ets.insert(:tags, {"post-1", "elixir"})
:ets.insert(:tags, {"post-1", "otp"})
:ets.insert(:tags, {"post-1", "elixir"}) # exact duplicate: ignored in a bag
:ets.insert(:tags, {"post-2", "phoenix"})
IO.inspect(:ets.lookup(:tags, "post-1"))
:ets.new(:ranking, [:ordered_set, :named_table])
:ets.insert(:ranking, [{3, "bronze"}, {1, "gold"}, {2, "silver"}])
IO.inspect(:ets.tab2list(:ranking))
IO.inspect(:ets.first(:ranking))[{"post-1", "elixir"}, {"post-1", "otp"}]
[{1, "gold"}, {2, "silver"}, {3, "bronze"}]
1
With :named_table the atom you passed to :ets.new/2 is the table's identifier.
Atomic counters
:ets.update_counter/4 increments a number inside a tuple atomically, so concurrent processes never lose an update, without any process acting as a bottleneck:
:ets.new(:hits, [:set, :public, :named_table, write_concurrency: true])
1..50
|> Enum.map(fn i ->
Task.async(fn ->
page = if rem(i, 5) == 0, do: "/pricing", else: "/home"
:ets.update_counter(:hits, page, 1, {page, 0})
end)
end)
|> Task.await_many()
IO.inspect(:ets.lookup(:hits, "/home"))
IO.inspect(:ets.lookup(:hits, "/pricing"))[{"/home", 40}]
[{"/pricing", 10}]
The last argument {page, 0} is the default tuple inserted when the key doesn't exist yet.
A simple cache module
Typically one process (often a GenServer started by a supervisor) owns the table, because a table is deleted when its owner exits. Reads go directly to ETS:
defmodule PriceCache do
@table :price_cache
def init, do: :ets.new(@table, [:set, :public, :named_table, read_concurrency: true])
def fetch(sku, compute) do
case :ets.lookup(@table, sku) do
[{^sku, price}] ->
{:hit, price}
[] ->
price = compute.(sku)
:ets.insert(@table, {sku, price})
{:miss, price}
end
end
end
PriceCache.init()
expensive = fn sku -> String.length(sku) * 10 end
IO.inspect(PriceCache.fetch("A-100", expensive))
IO.inspect(PriceCache.fetch("A-100", expensive))
IO.inspect(PriceCache.fetch("B-2", expensive)){:miss, 50}
{:hit, 50}
{:miss, 30}
Things to know
- ETS data is copied in and out of the table (except large binaries), just like messages.
- ETS is not persistent: the data is gone when the owner process dies or the VM stops. (Erlang's
:detsstores tables on disk; Mnesia is a full distributed database.) - Iterating over a big table with
tab2list/1copies everything. Use:ets.select/2match specifications (or:ets.fun2ms/1) to filter inside ETS.
Test yourself
What does :ets.lookup(t, key) return when the key is missing?
nil:error[]- It raises
Which table type keeps several tuples for one key?
:set:ordered_set:bag:named_table
What happens to an ETS table when its owner process exits?
- It is saved to disk
- It is deleted
- It moves to the supervisor
- Nothing