RDB with :erlang.term_to_binary

:erlang.term_to_binary serialises any Elixir term to a BEAM-native binary. No schema, no codegen, no Marshal_to_json incantation. The inverse :erlang.binary_to_term reads it back. Fast, but BEAM-specific.

06-rdb-snapshots/server.exs
elixir
def handle_call(:snapshot, _from, s) do
  snap = s.store
  spawn(fn ->
    tmp = "#{@rdb_path}.tmp"
    File.write!(tmp, :erlang.term_to_binary(snap))
    File.rename!(tmp, @rdb_path)
  end)
  {:reply, :ok, s}
end

spawn for the save; the GenServer keeps serving. Immutable state means the snapshot is safe even without copying.

The cleanest copy-on-write you can get without forking. Immutable data means snap = s.store is a free reference; later updates create a new map; the old one stays available to the spawned writer.

Immutable snapshot via spawn

No locks, no dup, just a reference to the current map.

Quiz: Quiz

Loading practice…