man erlang/ets

ETS: mutable tables in an immutable language

lib / Erlang and the BEAM 10 mindraft

checked against: Erlang/OTP 29.1.3

Erlang values never change. A map update returns a new map, and the old one stays as it was. Yet ets:update_counter/4 adds 1 to a number stored in a table, and every process that looks afterwards sees the new value. Where does that table live, how does the update happen, and is it faster than a map?

T = ets:new(counts, [set]),
ets:update_counter(T, apple, 1, {apple, 0}),   %% 1
ets:update_counter(T, apple, 1, {apple, 0}),   %% 2
ets:lookup(T, apple).                          %% [{apple,2}]

This article reads the ETS code in the runtime at the tag OTP-29.1.3, the version Homebrew installs, together with the ets module documentation, and checks both with escripts run on an Apple M2 Pro. Every number below comes from that source, those docs, or one of those runs.

The short version

ETS (“built-in term storage”, as the module documentation calls it) is a set of tables implemented in C inside the runtime. A table stores tuples, keyed by one of their elements. A set table is a linear hash table, and an ordered_set table is an AVL tree. Tables live outside every process heap, so inserting a tuple copies it into the table and looking it up copies it back out. A table belongs to the process that created it and disappears when that process exits. update_counter finds the key once, inserts the default tuple if the key is missing, and overwrites the integer inside the stored tuple, in C.

A table belongs to a process

The ets documentation is direct about ownership: “Each table is created by a process. When the process terminates, the table is automatically destroyed.” There is no garbage collection of tables. A table nobody refers to stays until its owner exits or someone calls ets:delete/1. This script creates a table in a short-lived process and keeps using it from the parent:

#!/usr/bin/env escript
main(_) ->
    Parent = self(),
    Owner = spawn(fun() ->
                      T = ets:new(scores, [public]),
                      Parent ! {table, T},
                      receive stop -> ok end
                  end),
    T = receive {table, Tab} -> Tab end,
    ets:insert(T, {alice, 3}),
    io:format("before: ~p~n", [ets:lookup(T, alice)]),
    Ref = monitor(process, Owner),
    Owner ! stop,
    receive {'DOWN', Ref, _, _, _} -> ok end,
    io:format("after:  ~p~n", [ets:info(T)]).
$ escript owner.erl
before: [{alice,3}]
after:  undefined

The parent wrote {alice, 3}, but the table was the owner’s, and it went with it. The heir option or ets:give_away/3 hand a table to another process instead. Access is set at creation: public lets any process read and write, protected (the default) lets the others only read, and private keeps the table to its owner.

One lookup, one change in place

ets:update_counter/4 is a BIF. In erl_db.c, do_update_counter checks the arguments, then calls the table’s db_lookup_dbterm with the key and the default tuple. For a hash table that function, in erl_db_hash.c, hashes the key, takes the bucket’s write lock if the table has per-bucket locks, and walks the bucket’s chain. If the key isn’t there, it copies the default tuple, puts the real key in the key position, and links the new object into the chain. Either way it returns a handle to the stored tuple.

The counter is then added in C and written back with db_do_update_element, which starts like this:

void db_do_update_element(DbUpdateHandle* handle,
			  Sint position,
			  Eterm newval)
{
    Eterm oldval = handle->dbterm->tpl[position];
    ...
    if (is_both_immed(newval,oldval)) {
	handle->dbterm->tpl[position] = newval;
	...
	return;
    }

When the old and the new count are both immediates (small integers that fit in a machine word), the new value overwrites the old one in the stored tuple. Nothing is allocated, nothing is copied. A counter that outgrows a small integer, or a table created with compressed, takes the longer path further down, which may resize the stored object.

Compare maps:update_with/4, which is ordinary Erlang in maps.erl:

update_with(Key, Fun, Init, Map) when is_function(Fun, 1), is_map(Map) ->
    case Map of
        #{Key := Value} -> Map#{Key := Fun(Value)};
        #{} -> Map#{Key => Init}
    end;

That matches the key once, calls the fun, and builds a new map with the update, which finds the key a second time. How a map shares structure between versions is its own story: Maps on the BEAM →.

A linear hash table

The header comment of erl_db_hash.c says it plainly: “The tables are implemented as linear dynamic hash tables.” Each bucket is a linked list of HashDbTerm nodes, and each node holds a pointer to the next one, the key’s hash value, and the stored tuple:

typedef struct hash_db_term {
    struct  hash_db_term* next;  /* next bucket */
    UWord hvalue : sizeof(UWord)*8 - 1;     /* stored hash value */
    UWord pseudo_deleted : 1;               /* delete marked in fixed table */
    ...
    DbTerm dbterm;         /* The actual term */
} HashDbTerm;

A new table starts with 256 active buckets. The grow rule is one line, GROW_LIMIT(NACTIVE) ((NACTIVE)*1). After an insert, if the table holds more objects than it has active buckets, grow adds a bucket. Linear hashing grows one bucket at a time. grow takes the bucket the new one pairs with, walks its chain, and moves each object whose hash now points at the new bucket. The rest of the table is not touched, so there is no pause where the whole table is rehashed. Bucket arrays come in segments, 256 slots in the first and 2,048 in each later one.

start, mask 255:  [0][1][2] ... [255]
grow, mask 511:   [0][1][2] ... [255][256]       256 takes from 0 the objects with hash & 511 == 256
grow again:       [0][1][2] ... [255][256][257]  257 takes from 1 the objects with hash & 511 == 257
lookup:           ix = hash & 511, and if ix is not open yet, ix = hash & 255

The hash itself is erts_internal_hash(term) >> 1 for any key except an atom, which reuses the hash stored in the atom table. An ordered_set table is a different structure altogether. erl_db_tree.c opens with “The tables are implemented as AVL trees”.

By default a write locks the whole table, and erl_db.c takes that lock before calling into the hash code. With write_concurrency, the hash table keeps one read-write lock for every N-th bucket instead, so writes to different parts of the table can run at the same time. The auto setting starts at 64 locks and can grow to 8,192.

Every read is a copy

The documentation’s “implementation details” list says that “every object insert and look-up operation results in a copy of the object.” The cost grows with the object:

#!/usr/bin/env escript
main(_) ->
    Big = lists:seq(1, 1000000),
    T = ets:new(big, []),
    ets:insert(T, {k, Big}),
    M = #{k => Big},
    {Ets, _} = timer:tc(fun() -> ets:lookup(T, k) end),
    {Map, _} = timer:tc(fun() -> maps:get(k, M) end),
    io:format("ets:lookup ~w us, maps:get ~w us~n", [Ets, Map]).
$ escript copy.erl
ets:lookup 13906 us, maps:get 0 us

Reading a million-element list out of a table takes 14 ms because the whole list is copied onto the reader’s heap. maps:get returns a reference to the list that is already there. ETS suits many small objects, such as counters, better than a few big ones.

Counting, measured

The case where ETS should do well is many small updates. This script counts 100,000 random keys drawn from 1 to 50,000 with five containers and keeps the best of 11 runs of each:

#!/usr/bin/env escript
%% Count 100,000 random keys drawn from 1..50,000 with each container.
main(_) ->
    rand:seed(exsss, {7, 8, 9}),
    Keys = [rand:uniform(50000) || _ <- lists:seq(1, 100000)],
    Cases =
        [{"map, maps:update_with/4",
          fun() -> lists:foldl(fun(K, M) -> maps:update_with(K, fun(N) -> N + 1 end, 1, M) end, #{}, Keys) end},
         {"ets set, update_counter/4",
          fun() -> T = ets:new(t, [set]), [ets:update_counter(T, K, 1, {K, 0}) || K <- Keys], ets:delete(T) end},
         {"ets ordered_set",
          fun() -> T = ets:new(t, [ordered_set]), [ets:update_counter(T, K, 1, {K, 0}) || K <- Keys], ets:delete(T) end},
         {"dict:update_counter/3",
          fun() -> lists:foldl(fun(K, D) -> dict:update_counter(K, 1, D) end, dict:new(), Keys) end},
         {"process dictionary",
          fun() -> [put(K, case get(K) of undefined -> 1; N -> N + 1 end) || K <- Keys], erase() end}],
    [io:format("~-26s ~6.2f ms~n", [Name, best(F) / 1000]) || {Name, F} <- Cases],
    T = ets:new(t, [set]),
    [ets:update_counter(T, K, 1, {K, 0}) || K <- Keys],
    Words = ets:info(T, memory),
    Size = ets:info(T, size),
    io:format("~w keys, ~w words, ~.1f words per key~n", [Size, Words, Words / Size]).

best(F) -> lists:min([element(1, timer:tc(F)) || _ <- lists:seq(1, 11)]).
$ escript count.erl
map, maps:update_with/4     19.50 ms
ets set, update_counter/4    9.75 ms
ets ordered_set             24.70 ms
dict:update_counter/3       34.69 ms
process dictionary           3.73 ms
43211 keys, 346060 words, 8.0 words per key

The set table counts twice as fast as the map. The ordered_set pays for its tree and is slower than the map. dict is the slowest. It is a growable hash table too, written in Erlang (its source credits Per-Åke Larsson’s dynamic hashing), and its documentation says to prefer maps for new code. The surprise is the process dictionary, the per-process key-value store behind put/2 and get/1, which is the fastest of the five. Its hash for a small integer key is the integer itself (erl_process_dict.c), and only its own process can see it, so it can’t do what ETS is for. The table holds 43,211 keys in 346,060 words, 8 words or 64 bytes per key including the table’s own overhead.

Shared between processes

What a map can’t do at all is be shared. Eight processes, each adding 1 to the same counter 100,000 times:

#!/usr/bin/env escript
main(_) ->
    C = ets:new(hits, [public, {write_concurrency, auto}]),
    Workers = [spawn_monitor(fun() ->
                                 [ets:update_counter(C, page, 1, {page, 0})
                                  || _ <- lists:seq(1, 100000)]
                             end) || _ <- lists:seq(1, 8)],
    [receive {'DOWN', Ref, _, _, _} -> ok end || {_, Ref} <- Workers],
    io:format("~p~n", [ets:lookup(C, page)]).
$ escript shared.erl
[{page,800000}]

No update is lost. The documentation guarantees that “all updates to single objects are guaranteed to be both atomic and isolated”, and update_counter does its read, add and write under one write lock. A read-then-insert from Erlang (lookup, add 1, insert) would give no such guarantee, which is why the function exists. Its documentation says it is there to update a counter “without the trouble of having to look up an object, update the object by incrementing an element, and insert the resulting object into the table again”.

Curious facts

  • A set and an ordered_set disagree about keys. In a set, 1 and 1.0 are different keys, because keys must match. In an ordered_set they compare equal, so the second insert replaces the first.

    #!/usr/bin/env escript
    main(_) ->
        S = ets:new(s, [set]), O = ets:new(o, [ordered_set]),
        [ets:insert(T, [{1, int}, {1.0, float}]) || T <- [S, O]],
        io:format("set:         ~p~nordered_set: ~p~n", [lists:sort(ets:tab2list(S)), ets:tab2list(O)]).
    
    $ escript keys.erl
    set:         [{1.0,float},{1,int}]
    ordered_set: [{1.0,float}]
    
  • '$end_of_table' can’t be used as a key. ets:first/1 and ets:next/2 return that atom to mark the end of the table.

  • ERL_MAX_ETS_TABLES and +e no longer limit the number of tables. The documentation says the number is “limited only by available memory”, and the setting is only a sizing hint for the index of named tables.

  • For bag tables, the order of objects with the same key inserted from one list was accidentally reversed in OTP 23.0 and fixed in OTP 25.3, the documentation of insert/2 notes.

  • update_counter has a wrap-around form: {Pos, Incr, Threshold, SetValue} resets the counter to SetValue once it passes Threshold.

History

The since attributes in ets.erl and the notes in the ets documentation give these versions:

  • OTP R14B: the read_concurrency option; R14B01: compressed.
  • OTP 18.0: update_counter/4, the form with a default object, and ets:take/2.
  • OTP 22.0: write_concurrency started to have an effect on ordered_set (STDLIB 3.7).
  • OTP 23.0: the decentralized_counters option, which spreads the table’s size and memory counters over several cache lines.
  • OTP 25.0: {write_concurrency, auto}, which the documentation now recommends.

Sources

ls erlang/