Mnesia

Mnesia is the database that ships with Erlang: tables with a schema, transactions and copies on more than one node, all in the standard installation and all called from Erlang terms. A DETS table is a file with keys, and Mnesia is what a program reaches for when it needs several tables that change together, a query over them, or a copy that survives the loss of a node. It is an OTP application, so it starts and stops like one, and its tables are announced in a schema.

A table in RAM

mnesia:start/0 starts the application, and mnesia:create_table/2 declares a table whose rows are records with the table name. With no storage option the table is a ram_copies table: fast, gone when the VM stops. Every change goes through a transaction, and a transaction that calls mnesia:abort/1 leaves the tables exactly as they were. The session writes two rows, queries them, and then aborts a third write:

erl

1> logger:set_primary_config(level, none). ok 2> mnesia:start(). ok 3> mnesia:create_table(person, [{attributes, [name, age]}]). {atomic,ok} 4> mnesia:transaction(fun() -> mnesia:write({person, ada, 36}) end). {atomic,ok} 5> mnesia:transaction(fun() -> mnesia:write({person, bob, 20}) end). {atomic,ok} 6> mnesia:dirty_read(person, ada). [{person,ada,36}] 7> mnesia:transaction(fun() -> mnesia:select(person, [{{person, '$1', '$2'}, [{'>', '$2', 30}], ['$1']}]) end). {atomic,[ada]} 8> mnesia:transaction(fun() -> mnesia:write({person, cid, 1}), mnesia:abort(bad) end). {aborted,bad} 9> mnesia:dirty_read(person, cid). [] 10> mnesia:table_info(person, size). 2 11> mnesia:stop(). stopped

Line 8 is the point of a transaction: the write of cid happened and then the abort threw the whole transaction away, so line 9 finds nothing and the table still holds two rows. A transaction that raises an exception aborts the same way, and Mnesia restarts it when the failure was a lock conflict rather than a bug, which is why the function of a transaction must be free of side effects outside the tables. The dirty_ calls skip the transaction and the locks, and are the tool for a read that does not need a consistent view.

A table on disk

A table that must survive the node needs a schema on disk and the disc_copies option. The schema is created with Mnesia stopped, because it is the file that says which tables exist and where their copies live. The first session builds it and writes one account:

erl

1> logger:set_primary_config(level, none). ok 2> mnesia:create_schema([node()]). ok 3> mnesia:start(). ok 4> mnesia:create_table(account, [{disc_copies, [node()]}, {attributes, [id, balance]}]). {atomic,ok} 5> mnesia:transaction(fun() -> mnesia:write({account, 1, 100}) end). {atomic,ok} 6> mnesia:sync_log(). ok 7> mnesia:stop(). stopped

The second session is a new VM in the same folder. Mnesia reads the schema from the Mnesia.<node> directory and loads the disc table, and mnesia:wait_for_tables/2 waits until it is ready to serve; without that call a transaction can arrive while the table is still loading and answer no_exists:

erl

1> logger:set_primary_config(level, none). ok 2> mnesia:start(). ok 3> mnesia:wait_for_tables([account], 5000). ok 4> mnesia:transaction(fun() -> mnesia:read(account, 1) end). {atomic,[{account,1,100}]} 5> mnesia:transaction(fun() -> mnesia:write({account, 2, 50}) end). {atomic,ok} 6> mnesia:dirty_read(account, 2). [{account,2,50}] 7> mnesia:stop(). stopped

The row of the first session is there, so the table outlived a full restart of the VM. The same mechanism copies a table to several nodes: {disc_copies, [node(), 'other@host']} keeps a copy on both, a write goes to all of them before the transaction commits, and a node that was down catches up from the log when it returns. That is also the hard part: a cluster that splits in two and both halves keep writing needs an operator decision about which side wins, and Mnesia does not make it for you.

When Mnesia

Mnesia is the right store when the data is Erlang terms, the program needs a transaction over more than one table, and the system is a handful of nodes that a release manages. It fits a configuration store, a session registry or an account ledger that a supervised application owns. It is the wrong store for a table of a few counters: an ETS table is faster and needs no application, and a DETS table is smaller when one file is enough. It is also the wrong store for data that outside programs must read, because a Mnesia table is only readable by an Erlang node that shares the cookie.

The operations a real application uses are few: mnesia:create_table/2 at start, mnesia:transaction/1 for a change, mnesia:read/2 and mnesia:select/2 inside one, mnesia:wait_for_tables/2 after a boot, and mnesia:backup/1 on a schedule. A table definition belongs in the start of a released application, not in a shell: the schema must be the same on every node that joins.

Questions

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

  1. What does mnesia:start/0 do?

    Answer

    Starts the Mnesia application

    Mnesia is an OTP application, and the call starts it with the schema it finds.

  2. What does a transaction answer when its function calls mnesia:abort(bad)?

    Answer

    {aborted, bad}

    The abort discards the writes of the transaction and answers the reason.

  3. What does the {disc_copies, [node()]} option make a table?

    Answer

    A table with a copy on disk and in memory

    The rows live in memory and are logged to disk, so the table survives a restart.

  4. Why call mnesia:wait_for_tables/2 after a start?

    Answer

    Because a disc table is still loading when start returns

    A transaction before the table is ready answers no_exists, and the wait closes that window.

  5. Which call reads a table without a transaction?

    Answer

    mnesia:dirty_read/2

    The dirty_ calls skip the transaction and the locks, and read the table as it is.

  6. When is Mnesia the wrong store?

    Answer

    For a few counters that one process owns

    A counter belongs in ETS: it is faster and needs no application or schema.

  7. What does this module print? -module(q1). -export([main/0]). main() -> logger:set_primary_config(level, none), ok = mnesia:start(), {atomic, ok} = mnesia:create_table(t, [{attributes, [k, v]}]), {atomic, ok} = mnesia:transaction(fun() -> mnesia:write({t, a, 1}) end), io:format("~p~n", [mnesia:dirty_read(t, a) =:= [{t, a, 1}]]).

    Answer

    true

    A dirty read answers the records of the key, and the record carries the table name.

  8. What does this module print? -module(q2). -export([main/0]). main() -> logger:set_primary_config(level, none), ok = mnesia:start(), {atomic, ok} = mnesia:create_table(t, [{attributes, [k, v]}]), R = mnesia:transaction(fun() -> mnesia:write({t, a, 1}), mnesia:abort(nope) end), io:format("~p ~p~n", [R, mnesia:dirty_read(t, a)]).

    Answer

    {aborted,nope} []

    The abort throws away the write of the transaction, so the table never holds the row.

  9. What does this module print? -module(q3). -export([main/0]). main() -> logger:set_primary_config(level, none), ok = mnesia:start(), {atomic, ok} = mnesia:create_table(t, [{attributes, [k, v]}]), {atomic, ok} = mnesia:transaction(fun() -> [mnesia:write({t, K, K}) || K <- [1, 2, 3]], ok end), io:format("~p~n", [mnesia:table_info(t, size)]).

    Answer

    3

    Three distinct keys are written in one transaction, so the table holds three rows.

  10. What does this module print? -module(q4). -export([main/0]). main() -> logger:set_primary_config(level, none), ok = mnesia:start(), {atomic, ok} = mnesia:create_table(t, [{attributes, [k, v]}]), {atomic, ok} = mnesia:transaction(fun() -> [mnesia:write({t, K, V}) || {K, V} <- [{a, 10}, {b, 20}, {c, 30}]], ok end), {atomic, Keys} = mnesia:transaction(fun() -> mnesia:select(t, [{{t, '$1', '$2'}, [{'>', '$2', 15}], ['$1']}]) end), io:format("~p~n", [lists:sort(Keys)]).

    Answer

    [b,c]

    The guard keeps the rows whose value is above 15, so b and c match.

The examples on this page were run in a shell with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev