TIL you can globally lock a callback to be called on a single BEAM node at once

May 25, 2024 1 min read

Erlang Elixir

If you have multiple BEAM nodes and want to ensure that a callback is only called once at a time across the cluster, you can use :global.trans/3 to create a global lock on a given ID.

def put_transaction(key, value) do
  :global.trans(key, fn ->
    put(key, value)
  end, 0)
end

Fly.io uses this to build a simple Key Value Database without data race.

Back to TIL

Erlang Elixir
Phil-Bastian Berndt

Phil-Bastian Berndt
Tech Lead at Naymspace