Skip to content
ETS Tables
step 1/4

Reading — step 1 of 4

Learn

~1 min readETS and Distribution

ETS (Erlang Term Storage) is a built-in in-memory key-value store with constant-time access. Each table can hold millions of entries with negligible overhead.

-module(main).
-export([main/1]).

main(_) ->
    %% Create a table
    Tab = ets:new(my_table, [set, public, named_table]),

    %% Insert
    ets:insert(my_table, {alice, 30}),
    ets:insert(my_table, {bob, 25}),
    ets:insert(my_table, {carol, 40}),

    %% Lookup
    [{_, Age}] = ets:lookup(my_table, alice),
    io:format("alice: ~w~n", [Age]),

    %% Iterate
    ets:foldl(fun({K, V}, Acc) -> [{K, V} | Acc] end, [], my_table),

    %% Delete
    ets:delete(my_table, bob),

    %% Cleanup
    ets:delete(my_table).

Table types:

  • set — unique keys (default)
  • ordered_set — keys in sorted order, can be iterated in order
  • bag — multiple values per key allowed (no duplicate {K,V})
  • duplicate_bag — even duplicate {K,V} allowed

Access modes:

  • private — only owner can read/write (default)
  • protected — owner writes, anyone reads
  • public — anyone reads/writes

named_table — refer to it by atom name across processes (instead of by Tid).

ETS is concurrent-safe — multiple processes can read/write without locking (atomic per-row).

Use cases:

  • Caches
  • In-memory state shared across processes (without GenServer overhead)
  • Session stores
  • Configuration / lookup tables

Limits:

  • All in RAM — for persistence, use Mnesia (its big sister) or external DB
  • Tables die when their owner process dies (unless heir option set)
  • Write-heavy contention can degrade — measure with ets:info

Mnesia is built on ETS+DETS — distributed, persistent, transactional. The Erlang DB.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…