ETS

In Elixir, the state of a process dies with the process, as the state lesson showed. ETS is the other direction: a table that lives outside any one process, is read by many processes at once and survives the death of its readers. It is the key-value store of the runtime, built for the data that must outlive one server.

A table outside the process

:ets.new/2 creates a table and answers a reference. The table is owned by the process that created it; other processes may read and, if the table is public, write it. The first program uses a set, which keeps one row per key:

set.exs

table = :ets.new(:scores, [:set, :public]) :ets.insert(table, {"ada", 10}) :ets.insert(table, {"bob", 7}) :ets.insert(table, {"ada", 12}) IO.inspect(:ets.lookup(table, "ada")) IO.inspect(:ets.info(table, :size)) IO.inspect(:ets.member(table, "bob"))

elixir set.exs

[{"ada", 12}]
2
true

The second insert of "ada" replaced the first, because a set keys on the first element of the tuple. lookup/2 always answers a list, empty when the key is not there, and info/2 reads the number of rows without walking them.

insert, lookup and the set

The operations are the Erlang functions with the leading colon, and they are fast because the table is a hash table outside the process heap. A row is any tuple, and the key is its first element. A process that reads the table does not copy it: ETS shares the rows and copies only the values a lookup returns.

An ordered set

:ordered_set keeps the rows sorted by key, so a walk returns them in that order. A program that prints a leaderboard or a range of keys uses it instead of sorting a set on every read:

ordered.exs

table = :ets.new(:scores, [:ordered_set]) for {name, score} <- [{"ada", 10}, {"bob", 7}, {"cy", 9}] do :ets.insert(table, {name, score}) end IO.inspect(:ets.tab2list(table) |> Enum.map(fn {name, _} -> name end))

elixir ordered.exs

["ada", "bob", "cy"]

The rows come out in key order, which is the string order here. The set form has no order at all, so a program that needs one sorts the result or asks for the ordered table; the choice is made when the table is created and cannot change.

A named table

:named_table gives the table a name that any process can use in place of the reference. The name is the table, and :ets.whereis/1 finds the reference when a program needs it:

named.exs

:ets.new(:cache, [:named_table, :public]) :ets.insert(:cache, {:answer, 42}) IO.inspect(:ets.lookup(:cache, :answer)) IO.inspect(:ets.whereis(:cache) != :undefined)

elixir named.exs

[answer: 42]
true

A named table is a global name in the VM, so two tables with one name cannot exist. That is convenient for one cache and a problem for a program that wants one table per user; the unnamed form with a reference passed in a message is the shape for many tables.

Delete and size

:ets.delete/2 removes one row and :ets.delete/1 removes the whole table. The size of the table after a delete is the count a program reads to confirm it:

delete.exs

table = :ets.new(:scores, [:set]) :ets.insert(table, {"ada", 10}) :ets.delete(table, "ada") IO.inspect(:ets.lookup(table, "ada")) IO.inspect(:ets.info(table, :size))

elixir delete.exs

[]
0

A lookup of a missing key is not an error, which is why ETS fits a cache: the caller gets an empty list and decides what a miss means. The next section shows the error that is real, the use of a table whose owner has ended.

The mistake: the owner ends

The table belongs to the process that created it. When that process ends, the runtime deletes the table, and a reader that kept the reference finds nothing. The error is an ArgumentError whose second line names the cause:

dies.exs

parent = self() spawn(fn -> table = :ets.new(:temp, [:public]) send(parent, {:table, table}) Process.sleep(50) end) table = receive do {:table, t} -> t end Process.sleep(100) :ets.lookup(table, :key)

elixir dies.exs

** (ArgumentError) errors were found at the given arguments:

  * 1st argument: the table identifier does not refer to an existing ETS table

    dies.exs:15: (file)

The reference line of the trace names the dead table with numbers that change on every run, so the block leaves it out; the message is the stable part. The fix is an owner that lives as long as the table, which in an OTP program is a supervised process, often a GenServer that creates the table in init/1 and hands the reference to its callers.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Where does an ETS table live?

    Answer

    Outside the processes, owned by the process that created it

    ETS is a table outside the process heaps, owned by its creator and shared with its readers.

  2. What does :ets.lookup/2 answer when the key is missing?

    Answer

    an empty list

    lookup always answers a list, so a miss is the empty list.

  3. What is the key of a row in an ETS table?

    Answer

    The first element of the tuple

    The table keys on the first element of the tuple it stores.

  4. What happens to a table when its owner process ends?

    Answer

    It is deleted

    The owner holds the table; its death removes the table and the readers see a dead reference.

  5. What does this program print? table = :ets.new(:t, [:set]) :ets.insert(table, {:a, 1}) :ets.insert(table, {:a, 2}) IO.inspect(:ets.lookup(table, :a))

    Answer

    [a: 2]

    A set keeps one row per key, and the second insert replaces the first.

  6. What does this program print? table = :ets.new(:t, [:set]) :ets.insert(table, {"ada", 10}) IO.inspect(:ets.info(table, :size))

    Answer

    1

    One row was inserted, and info/2 reports the row count.

  7. What does this program print? table = :ets.new(:t, [:ordered_set]) for name <- ["cy", "ada", "bob"] do :ets.insert(table, {name, 1}) end IO.inspect(:ets.tab2list(table) |> Enum.map(fn {n, _} -> n end))

    Answer

    ["ada", "bob", "cy"]

    An ordered set walks the rows by key, whatever order they were inserted in.

  8. What does this program print? :ets.new(:cache, [:named_table, :public]) :ets.insert(:cache, {:answer, 42}) IO.inspect(:ets.lookup(:cache, :answer))

    Answer

    [answer: 42]

    A named table is used by its name, and lookup answers the list of rows.

  9. What does this program print? table = :ets.new(:t, [:set]) :ets.insert(table, {:a, 1}) :ets.delete(table, :a) IO.inspect(:ets.member(table, :a))

    Answer

    false

    The row was deleted, so the key is no longer a member.

  10. Which process should own a table that lives as long as the application?

    Answer

    A supervised process that creates it in init/1

    The owner must outlive the table; a supervised server is the stable choice.

Article author: Arthur Isaev