Tag

process registry

2 articles
chairs-2

A journey to Syn v2, a better Erlang & Elixir Process Registry and Group manager

For those who don't know it, Syn (short for synonym) is a global Process Registry and Process Group manager for Erlang and Elixir that I've written a few years back. It has been around for some time now, and it has served me well on many occasions. Through the years, I've built up a series of considerations and ideas for improvement, and now the time has come to put all of these back into Syn.

Syn v2 has been rewritten from the grounds up, and I'd like to share the reasoning and the architectural choices behind this work. Since Syn is written in Erlang, the few portions of the code here below will show Erlang syntax. Don't let that discourage you if you are an Elixir developer though, as the same principles apply.

The analysis

Things I wanted to keep

I've always treated a Process Registry as a specialized subset of a Key / Value store. Yes, the Key is the process registered name and the Value is the pid(), but the important bit here is that a process inherently belongs to a node - because it runs there. This changes the game quite significantly.

Contrary to standard Key / Value stores where you want to keep all of your data when a node leaves or crashes, why would you want to keep the name reference to a process, if that process runs on the node that left, or worse, crashed (and the process with it)? If a node gets added, why would you want to handoff a running process' registration handling to this new node (so, not the node the process is running on)? In general, why would you want to decouple the node that handles the registered name of a process from the process itself?

If your answer is that in case of nodes leaving / crashing you need to keep the process' information, then what you need is a persistent data storage, not a Process Registry. If your answer is that you want to spawn and load balance processes across a cluster (i.e. workers, that also happen to end up registered by name), then maybe what you need is a Job Queue, not necessarily a Process Registry.

Now, if what you want from your Process Registry is to register existing processes, then maybe you can agree that a process' registration is strongly tied to the node the process runs on. If the node dies, then the process dies as well, and keeping its registration name around probably doesn't make much sense. If you agree to this, then my suggestion is that in a distributed registry every node should be handling the registration of the processes that run on it.

In this scenario, we have ourselves a different paradigm from the ones of standard Key / Value stores. For instance, you do not need a Hash Ring to load balance the processes in your cluster and create replicas for fault tolerance of data: if a process or the node it runs on dies, you want to let its registration name go. You could still consider using a hash ring or consensus algorithms such as Raft to register a name, because you might experience race conditions for the same name being registered simultaneously on different nodes. However, Syn takes the approach of using a similar conflict resolution mechanism used to resolve net splits for these cases.

This is even more true in the context where Syn was born. In IoT applications, you generally have a process that handles an external (TCP/UDP) socket to a physical device. It only makes sense that the process runs on the same node of the socket it handles, because in this scenario (maybe it's just me) I cannot see the sense of having an external socket being managed by a process that runs on a different node:

  • If the node the socket runs on dies, you most probably want the process that handles it to die as well.
  • Reciprocally, if the socket handler process dies, you'd loose all of its state and you'd probably would want to disconnect the device from the socket anyway.

To sum it up, I wanted to keep Syn v1 paradigm which is: every node is the authority for registering the processes that run on it. Load balancing is not part of this Process Registry, and it rather has to do with whatever causes processes to be spawned in the first place (i.e. external sockets get created on a specific node based on TCP Load Balancing mechanisms).

Finally, I wanted also to keep a full registry replica on every node of the cluster, so that Syn is optimized for read-intensive operations rather than write-intensive ones. This also seems to make sense, since if you do want to register a process by a name it's probably because you want it to live long enough for it to have an alias and keep track of it system-wide.

Things I wanted to improve

1. Dynamic node membership

Contrary to what some forum users seem to think, Syn v1 does manage dynamic node addition pretty well. The only caveat is that Syn v1 needs to be initialized on a node after a node joins a cluster: your application needs to have the logic to connect to the other nodes, and only then issue a call to syn:init/0 which initializes the mnesia tables on the node. This is because Syn v1 uses mnesia's replication features, and mnesia enforces a specific instructions' order when creating / adding a node to existing replicated tables.

For instance, the call to mnesia:change_config/2 to configure extra_db_nodes needs to happen before the creation of a table (via mnesia:create_table/2) or the addition of a node to existing replicated tables (via mnesia:add_table_copy/3). If you're curious about this process, you can head to syn_backbone.erl where you can get the gist on how Syn v1 sets up dynamic replication via mnesia.

This could also potentially lead to a rare race condition, which BTW never happened to me in all of these years. If two nodes of a cluster were to be started during a net split so that they do not see each other on boot, they would initialize mnesia separately which would result in them having their own version of Syn tables, with their own fingerprint, that cannot be merged afterwards (due to mnesia internals).

Finally, while mnesia does support node addition, it does not as easily support node removal. The equivalent command to remove a table copy, mnesia:del_table_copy/2, has some other caveats (for example it requires mnesia to be stopped). It is certainly doable though, but the question here would be when to do it in an automated way. For instance, a node could get notified that another node left the cluster, but should it then remove the missing node's table copy? To do that, it would first have to stop mnesia - and lose all of the ram data - and then, what if the other node was simply down due to a temporary network failure that caused a net split? For these reasons, node removal was never implemented in Syn v1. If a node left, the local mnesia tables would still have it included in extra_db_nodes that mnesia uses for replication, which is not a big deal.

Therefore, even if Syn v1 does support dynamic node addition, there are these caveats to keep in mind - and I can see why some users might have misinterpreted them.

2. Net Splits

Even though these events are rare, they do happen. Moreover, I felt that a mechanism that would solve those would also basically implement a fully working dynamic addition / removal of nodes.

Mnesia does not handle net splits very well. To give some support to this issue, Ulf Wiger experimented and created his unsplit framework (he talks about it in this post on the Erlang questions mailing list). However, I've had mixed results with the mechanism that he uses in there.

Basically, Ulf's solution works by first subscribing to mnesia events. If mnesia triggers an inconsistent database event for a remote node (so it is running a partitioned network), the unsplit code will check whether the remote node is already part of mnesia's local running nodes. If it is not, it will manually connect the local to the remote node using the undocumented mnesia_monitor:connect_nodes/1 method; while doing so, it will inject some custom resolution code that performs dirty read & write operations to the local and to the remote node's mnesia tables. I took this mechanism and made a specialized and simplified version for Syn v1, and if you're up for it you can check this implementation in syn_consistency.erl.

While it works nicely in a 2 nodes cluster, I have unfortunately encountered an inconsistent behavior in bigger clusters. In a cluster of 3 nodes I would see the inconsistent database events triggered correctly by mnesia, but unfortunately mnesia would randomly consider the remote node that triggered the event as already part of its local running nodes. Thus, the resolution part of the code that would perform the read & write operations and solve the split brain situation wouldn't get a chance to run. My hunch is that mnesia is able to reconnect to parted nodes in a way that may happen before all of this mechanism gets the chance to be called, especially in partial net splits scenarios. I've also tried forcing the resolution code to run without the checks, but I got the error not_merged as the result of the merge fun in mnesia_controller:connect_nodes/1, more precisely here.

I don't know whether this incapacity of randomly solving net splits in bigger clusters results from using mnesia's in a non-intended way by taking advantage of Ulf's mechanism (it seems that Ulf wanted to test it with more than 2 nodes himself), or if I might have missed something in my implementation version. That said, handling net splits is not an immediate task especially if you're using a library that is not meant to do so. The feeling is that mnesia replication mechanisms are not intended to handle them, and hacking your way through might have unexpected results.

3. Behavior and customization

Syn v1 allows to register a process with one name at a time, a behavior consistent with Erlang's global module. However, I felt this as a limitation and I wanted to allow multi-aliases process registration.

Also, I wanted a more clean approach to support customization callbacks, i.e. a single callback module with its syn_event_handler behavior that would be triggered depending on a developer's choices.

Finally, in case of registry conflicts during a net split resolution (i.e. when two processes have registered the same name on different nodes during the net split), Syn v1 decides which process to keep and which one to discard. I wanted to provide developers with the ability of defining their own conflict resolution method. The developers could, for instance, save vector clocks data into the meta data of each process and use those to choose which process to keep in case of conflict.

The rewrite

Given all of the above, the choices were simple and clear - and so the implementation.

Generic Register / Unregister operations' flow

  • When a registration request comes in for a Name and Pid, this request is routed to the node that the Pid is running on. In most cases, a registration request will be done from a process itself, which means that communication stays on the same node.
  • Every registration request is treated by a single (gen server) process (the registry process) on every node. This registry process starts monitoring the newly registered process, and also guarantees that registration / unregistration requests are necessarily consistent - since there's a per-node single registry process authority that sequentially treats them.
  • The registry process writes to a local (not replicated) mnesia table (Edit in v2.1) local ETS tables the Name and related Pid. This is an in-memory only table that gets created on application start and killed on application stop. I still use mnesia only because of its secondary index feature, as I need to be able to search for table entries both by Name and by Pid.
  • The registry process then sends the registration / unregistration information to all of the other nodes in the cluster. This is not done by sending a message to the registry processes of the other nodes, rather it issues a remote procedure call (RPC) that directly writes in the local ETS tables of the remote nodes. This allows the other registry processes to be free from all intra-nodes syncing operations.
  • Edit in v2.0.1 --->
  • When a node receives a registration information from another node, it checks locally whether there's a name conflict. If one is found, the node will try to gain a global lock for the conflicting name to run a specific portion of code that merges the conflicting data, since other registry processes might see this conflict as well.
  • The registry process that succeeds in gaining the lock will compare the received registration data and will resolve the conflict between itself and the node that sent the registration information.
  • Once done, the registry process will free the lock, and all the other nodes that eventually experienced the same name conflict will resolve the same conflict.

Nodes' addition

  • When a node joins a cluster, all the registry processes of the nodes in the cluster receive a NODE UP event for that node. Simultaneously, the joining node's registry process receives a NODE UP event for all of the existing nodes in the cluster.
  • Every registry process that receives a NODE UP event for a remote node will try to gain a global lock to run a specific portion of code that deals with merging remote data.
  • The registry process that succeeds in gaining the lock will issue a RPC on the remote node and request the registry data for all of the processes that run on it, for which the remote node is the authority. It will then write this information on its local ETS tables. If this happens after a net split, some naming conflicts might happen at this moment, and a choice on which process to keep will be made depending on the specified logic. By default, Syn will keep the local process, kill the remote process and remove the latter from the ETS tables on the remote node (via a RPC).
  • Once done, the registry process will free the lock. It will not send its data, as it will be requested from the other registry processes when they get their turn to grab the lock.
  • The code for all of this at the time of writing can be seen here.

Nodes' removal

  • When a node leaves a cluster (voluntarily, because it crashed or because of a net split), all the registry processes of the nodes in the cluster receive a NODE DOWN event for that node.
  • The registry processes that receive this event proceed to remove from their local mnesia tables all of the processes that ran on the disconnected node.
  • This works well also in context of partial net splits (A <--> B <--> C where node A can see B, B can see A and C, and C can only see B), since every node keeps locally only the information of the nodes it can see.

Results

These are the results of the rewrite.

  • Addition & removal of nodes in a cluster is done in a completely dynamic and transparent way, with no caveats.
  • Automated repairing from net splits has now been taken to a new level. You can check the existing test suites to see what is being covered.
  • Finally, there now is a single callback module with the syn_event_handler behavior, and the ability for the developer to use a custom function to resolve naming conflicts after net splits.

There still might be corner cases that I haven't considered in terms of consistency, if some arise I will do my best to tackle any of those in future improvements of Syn.

You can grab your copy of Syn v2 on Hex or Github. Happy registering!

Continue Reading…
chairs

An evaluation of Erlang global process registries: meet Syn

Due to my personal interests and history, I often find myself building applications in field of the Internet Of Things. Most of the times I end up using Erlang: it is based on the Actor's Model and is an ideological (and practical) perfect match to manage IoT interactions.

I recently built an application where devices can connect to, and interact with each other. Every device is identified via a unique ID (its serial number) and based on this ID the devices can send and receive messages. Nothing new here: it's a standard messaging platform, which supports a custom protocol.

Due to the large amount of devices that I needed to support, this application runs on a cluster of Erlang nodes. Once a device connects to one of those nodes, the related TCP socket events are handled by a process running on that node. To send a message to a specific device, you send a message to the process that handles the devices's TCP socket.

While building this application, I was early in the process faced with a very common problem: I needed a global process registry that would allow me to globally register a process based on its serial number, so that messages can be sent from anywhere in the cluster. This registry would need to have the following main characteristics:

  • Distributed.
  • Fast write speeds (>10,000 / sec).
  • Handle naming conflict resolution.
  • Allow for adding/removal of nodes.

Therefore I started to search for possible solutions (which included posting to the Erlang Questions mailing list), and these came out as my options:

The Stress Test

I decided to evaluate every one of these solutions based on a variety of considerations. However, I also wanted to see how they would perform when submitted to some kind of a stress test. Therefore, I defined and wrote a simple one that:

  1. Launches a certain number of processes per node (for example, 25,000 processes per node).
  2. Registers these processes (25,000 processes per node), each with a globally unique Key.
  3. Waits for those Keys to be propagated to all the nodes.
  4. Unregisters all of these processes.
  5. Waits for those Keys to be removed from all the nodes.
  6. Re-registers all of the processes, to check for unwanted effects of subsequent add/remove operations.
  7. Again, waits for those Keys to be propagated to all the nodes.
  8. Kills all the processes (this time, without previously unregistering them).
  9. Waits for those Keys to be removed from all the nodes (to check for process monitoring).

The test measures how long each one of these steps takes.

The following is the code for this stress test. You can see that it defines a behaviour: this is to implement callback modules that match the different syntax used by the different libraries.

ERLANG
-module(process_registry_bench).

-export([start/3]).
-export([register/2, unregister/2]).
-export([register_on_node/2, unregister_on_node/2]).

-callback init() -> term().
-callback register(Key :: string(), pid()) -> term().
-callback unregister(Key :: string(), pid()) -> term().
-callback retrieve(Key :: string()) -> pid() | undefined.
-callback process_loop() -> any().

-define(MAX_RETRIEVE_WAITING_TIME, 60000).


start(CallbackModule, ProcessesCount, Nodes) ->
	%% connect
	connect_nodes(Nodes),

	%% callback init
	CallbackModule:init(),

	%% launch processes
	{UpperKey, PidInfos} = launch_processes(CallbackModule, ProcessesCount),

	%% benchmark: register
	{TimeReg, _} = timer:tc(?MODULE, register, [CallbackModule, PidInfos]),
	io:format("Registered processes in ~p sec, at a rate of ~p/sec~n", [
		TimeReg/1000000,
		ProcessesCount/TimeReg*1000000
	]),

	%% benchmark: registration propagation
	{RetrievedInMs1, RetrieveProcess1} = retrieve(pid, CallbackModule, UpperKey),
	io:format("Check that process with Key ~p was found: ~p in ~p ms~n", [
		UpperKey, RetrieveProcess1, RetrievedInMs1
	]),

	%% benchmark: unregister
	{TimeUnreg, _} = timer:tc(?MODULE, unregister, [CallbackModule, PidInfos]),
	io:format("Unregistered processes in ~p sec, at a rate of ~p/sec~n", [
		TimeUnreg/1000000,
		ProcessesCount/TimeUnreg*1000000
	]),

	%% benchmark: unregistration propagation
	{RetrievedInMs2, RetrieveProcess2} = retrieve(undefined, CallbackModule, UpperKey),
	io:format("Check that process with Key ~p was NOT found: ~p in ~p ms~n", [
		UpperKey, RetrieveProcess2, RetrievedInMs2
	]),

	%% benchmark: re-registering
	{TimeReg2, _} = timer:tc(?MODULE, register, [CallbackModule, PidInfos]),
	io:format("Re-registered processes in ~p sec, at a rate of ~p/sec~n", [
		TimeReg2/1000000,
		ProcessesCount/TimeReg2*1000000
	]),

	%% benchmark: re-registration propagation
	{RetrievedInMs3, RetrieveProcess3} = retrieve(pid, CallbackModule, UpperKey),
	io:format("Check that process with Key ~p was found: ~p in ~p ms~n", [
		UpperKey, RetrieveProcess3, RetrievedInMs3
	]),

	%% benchmark: monitoring
	io:format("Kill all processes~n", []),
	kill_processes(PidInfos),
	{RetrievedInMs4, RetrieveProcess4} = retrieve(undefined, CallbackModule, UpperKey),
	io:format("Check that process with Key ~p was NOT found: ~p in ~p ms~n", [
		UpperKey, RetrieveProcess4, RetrievedInMs4
	]).

connect_nodes(Nodes) ->
    [true = net_kernel:connect_node(Node) || Node <- Nodes].

launch_processes(CallbackModule, ProcessesCount) ->
	%% return the processes info in format [{Node, [{Key, Pid}]}, ...]
	Nodes = [node() | nodes()],
	ProcessesPerNode = round(ProcessesCount / length(Nodes)),
	UpperKey = integer_to_list(ProcessesPerNode * length(Nodes)),
	F = fun(Node, Acc) ->
		StartingKey = length(Acc) * ProcessesPerNode,
		Pids = launch_processes_on_node(CallbackModule, ProcessesPerNode, StartingKey, Node),
		[{Node, Pids} | Acc]
	end,
	{UpperKey, lists:foldl(F, [], Nodes)}.
launch_processes_on_node(CallbackModule, ProcessesPerNode, StartingKey, Node) ->
	%% return the key and process in a list of format [{Key, Pid}, ...]
	Seq = [
		integer_to_list(Key)
		|| Key <- lists:seq(StartingKey + 1, ProcessesPerNode + StartingKey)
	],
	[{Key, spawn(Node, CallbackModule, process_loop, [])} || Key <- Seq].

register(CallbackModule, PidInfos) ->
	%% register in parallel on all nodes
	F = fun({Node, NodePidInfos}, Acc) ->
		RpcKey = rpc:async_call(Node, ?MODULE, register_on_node, [
			CallbackModule, NodePidInfos
		]),
		[{Node, RpcKey} | Acc]
	end,
	RpcKeys = lists:foldl(F, [], PidInfos),
	%% wait for registration to complete on all nodes
	FResult = fun({Node, RpcKey}) ->
		Registered = rpc:yield(RpcKey),
		io:format("Registered ~p processes on node ~p~n", [Registered, Node])
	end,
	lists:foreach(FResult, RpcKeys).
register_on_node(CallbackModule, NodePidInfos) ->
	F = fun({Key, Pid}) ->
		CallbackModule:register(Key, Pid)
	end,
	lists:foreach(F, NodePidInfos),
	length(NodePidInfos).

retrieve(Expected, CallbackModule, Key) ->
	StartTime = epoch_time_ms(),
	retrieve(Expected, CallbackModule, Key, StartTime).
retrieve(pid, CallbackModule, Key, StartTime) ->
	%% wait for a pid to be returned
	case CallbackModule:retrieve(Key) of
		undefined ->
			timer:sleep(50),
			case epoch_time_ms() > StartTime + ?MAX_RETRIEVE_WAITING_TIME of
				true -> {error, timeout_during_retrieve};
				false -> retrieve(pid, CallbackModule, Key, StartTime)
			end;
		{error, Error} ->
			{error, Error};
		Pid ->
			RetrievedInMs = epoch_time_ms() - StartTime,
			{RetrievedInMs, Pid}
	end;
retrieve(undefined, CallbackModule, Key, StartTime) ->
	%% wait for undefined to be returned
	case CallbackModule:retrieve(Key) of
		undefined ->
			RetrievedInMs = epoch_time_ms() - StartTime,
			{RetrievedInMs, undefined};
		{error, Error} ->
			{error, Error};
		_Pid ->
			timer:sleep(50),
			case epoch_time_ms() > StartTime + ?MAX_RETRIEVE_WAITING_TIME of
				true -> {error, timeout_during_retrieve};
				false -> retrieve(undefined, CallbackModule, Key, StartTime)
			end
	end.

unregister(CallbackModule, PidInfos) ->
	%% unregister in parallel on all nodes
	F = fun({Node, NodePidInfos}, Acc) ->
		RpcKey = rpc:async_call(Node, ?MODULE, unregister_on_node, [
		CallbackModule, NodePidInfos
		]),
		[{Node, RpcKey} | Acc]
	end,
	RpcKeys = lists:foldl(F, [], PidInfos),
	%% wait for unregistration to complete on all nodes
	FResult = fun({Node, RpcKey}) ->
		Unregistered = rpc:yield(RpcKey),
		io:format("Unregistered ~p processes on node ~p~n", [Unregistered, Node])
	end,
	lists:foreach(FResult, RpcKeys).
unregister_on_node(CallbackModule, NodePidInfos) ->
	F = fun({Key, Pid}) ->
		CallbackModule:unregister(Key, Pid)
	end,
	lists:foreach(F, NodePidInfos),
	length(NodePidInfos).

kill_processes(PidInfos) ->
	F = fun({_Node, NodePidInfos}) ->
		[exit(Pid, kill) || {_Key, Pid} <- NodePidInfos]
	end,
	lists:foreach(F, PidInfos).

epoch_time_ms() ->
    {Mega, Sec, Micro} = os:timestamp(),
    (Mega * 1000000 + Sec) * 1000 + round(Micro / 1000).

To run this stress test:

ERLANG
process_registry_bench:start(CallbackModule, ProcessCount, Nodes).

For instance, to launch it with the callback module global_bench for 100,000 processes running on a cluster of 4 nodes ['1@127.0.0.1', '2@127.0.0.1', '3@127.0.0.1', '4@127.0.0.1']:

ERLANG
process_registry_bench:start(global_bench, 100000, [
    '1@127.0.0.1',
    '2@127.0.0.1',
    '3@127.0.0.1',
    '4@127.0.0.1'
]).

Running this test returns an output similar to:

Registered 25000 processes on node '1@127.0.0.1'
Registered 25000 processes on node '2@127.0.0.1'
Registered 25000 processes on node '3@127.0.0.1'
Registered 25000 processes on node '4@127.0.0.1'
Registered processes in 6.385835 sec, at a rate of 15659.659230155492/sec
Check that process with Key "100000" was found: <6218.25065.0> in 0 ms
Unregistered 25000 processes on node '1@127.0.0.1'
Unregistered 25000 processes on node '2@127.0.0.1'
Unregistered 25000 processes on node '3@127.0.0.1'
Unregistered 25000 processes on node '4@127.0.0.1'
Unregistered processes in 4.481706 sec, at a rate of 22312.93172733776/sec
Check that process with Key "100000" was NOT found: undefined in 0 ms
Registered 25000 processes on node '1@127.0.0.1'
Registered 25000 processes on node '2@127.0.0.1'
Registered 25000 processes on node '3@127.0.0.1'
Registered 25000 processes on node '4@127.0.0.1'
Re-registered processes in 4.943493 sec, at a rate of 20228.611631492146/sec
Check that process with Key "100000" was found: <6218.25065.0> in 0 ms
Kill all processes
Check that process with Key "100000" was NOT found: undefined in 0 ms
ok

The Process Registry Libraries

The following are the considerations that I made for every solution.

1. Erlang's native global module

Considerations

The Erlang global module has native functionalities to support a global process registry. I was not particularly attracted to it, because:

  • I always think that this module should be used to identify application's long-running services.
  • I didn't know if millions of entries can be supported. This module wasn't built with my use case in mind: as per my previous point, it is generally used to register long-running processes.
  • It has a locking mechanism to ensure that the registration is atomic. I felt this could become a serious bottleneck to the registration of processes.

However, this is a native Erlang module, which also allows to define a resolve function to be used for conflict resolution (i.e. in case of race conditions, or during net splits, when a Key gets registered simultaneously on two different nodes). It is able to satisfy the distributed requirements out of the box, with no need for additional libraries.

Stress Test

I gave it a go at my stress test, with the following callback module:

ERLANG
-module(global_bench).
-behaviour(process_registry_bench).

-export([init/0]).
-export([register/2, unregister/2]).
-export([retrieve/1]).
-export([process_loop/0]).

init() ->
	ok.

register(Key, Pid) ->
	yes = global:register_name(Key, Pid).

unregister(Key, _Pid) ->
	global:unregister_name(Key).

retrieve(Key) ->
	global:whereis_name(Key).

process_loop() ->
	receive
		_ -> ok
	end.

Note that process_loop (which is the loop running in the processes) does nothing, except keeping the process alive.

The results of the stress test are:

[table colalign="left|right|right|right|right"]
,1 Node,2 Nodes,3 Nodes,4 Nodes
Reg / second,"27,233","2,673","1,997","1,579"
Retrieve registered Key (ms),0,0,0,0
Unreg / second,"29,491","2,908","2,206","1,596"
Retrieve unregistered Key (ms),0,0,0,0
Re-Reg / second,"27,149","2,993","2,131","2,542"
Retrieve re-registered Key (ms),0,0,0,0
Retrieve Key of killed Pid (ms),0,timeout,timeout,timeout
[/table]

Conclusions

  • The locking mechanism heavily influences the decrease in performance that can be seen when adding nodes. With a cluster of 2+ nodes we already are under the spec of 10,000 registrations / second.
  • The monitoring of processes is slow. After having killed all the processes, in a cluster of 2+ nodes it takes more than 60 seconds to have global:whereis_name/1 return undefined (this is what timeout means in the table here above). I had to decrease the number of processes to around 80,000 to have the stress test pass in a cluster of 4 nodes, and it would take around 55 seconds for a killed process' Key to be removed from the registry.

For these reasons, it didn't look like I could use this module.

2. Erlang's native pg2 module

Considerations

Erlang pg2 module has native functionalities to support a global process registry. I was not particularly attracted to it, because:

  • This library handles Process Groups, which is very different from handling unique Registered Names. We can use it for our purpose though, by basically creating Groups with a single entry. These groups are named according to our Keys, and every Group has a single entry: the Pid that we are registering. This is kind of a trick, but it's not a showstopper.
  • Having Process Groups basically means that conflict resolution isn't covered. If two processes are registered on different nodes with the same Key (because of race conditions or during a net split) this will result in having a Process Group with two elements instead of one. Sometimes this is fine; however, I wanted to ensure that there would be a clearly identified single Pid per device in the whole system. Not a showstopper either, but a turn-off.
  • I didn't know if millions of entries can be supported. This module wasn't built with my use case in mind.
  • Here too, it has a locking mechanism to ensure that the registration is atomic which could become a bottleneck to the registration of processes.

Stress Test

Here's the callback module:

ERLANG
-module(pg2_bench).
-behaviour(process_registry_bench).

-export([init/0]).
-export([register/2, unregister/2]).
-export([retrieve/1]).
-export([process_loop/0]).

init() ->
	ok.

register(Key, Pid) ->
	ok = pg2:create(Key), %% create group
	ok = pg2:join(Key, Pid). %% add pid

unregister(Key, _Pid) ->
	ok = pg2:delete(Key).

retrieve(Key) ->
	case pg2:get_members(Key) of
		{error, {no_such_group, Key}} -> undefined;
		[] -> undefined;
		[Pid] -> Pid
	end.

process_loop() ->
	receive
		_ -> ok
	end.

The results of the stress test are:

[table colalign="left|right|right|right|right"]
,1 Node,2 Nodes,3 Nodes,4 Nodes
Reg / second,"25,062","3,823","2,914","1,862"
Retrieve registered Key (ms),0,0,0,0
Unreg / second,"39,522","6,903","5,191","3,425"
Retrieve unregistered Key (ms),0,0,0,0,
Re-Reg / second,"25,701","3,794","2,783","1,817"
Retrieve re-registered Key (ms),0,0,0,0
Retrieve Key of killed Pid (ms),timeout,timeout,timeout,timeout
[/table]

Conclusions

  • The locking mechanism heavily influences the decrease in performance that can be seen when adding nodes. With a cluster of 2+ nodes we already are under the spec of 10,000 registrations / second.
  • The monitoring of processes is slow. After having killed all the processes, even on a single nodes it takes more than 60 seconds to have pg2:get_members/1 return that the group no longer exits. I had to decrease the number of processes to around 45,000 to have the stress test pass in a cluster of 4 nodes, and it would take a little less than 60 seconds for a killed process' Key to be removed from the registry.

For these reasons, it didn't look like I could use this module.

3. Gproc

Considerations

gproc is a well-known process registry which is normally used for the additional features that it provides on top of Erlang's native process dictionary (for instance, it is able to provide pub/sub patterns). It is a solid and well-supported library, and you can often see Ulf Wiger (one of the library's authors) generously providing support for it.

However, there were some concerns I had:

  • For the distributed part it relies on gen_leader, on which I've heard too many horror stories (maybe that's not a thing anymore). Ulf pointed me to a gproc branch that uses locks_leader, where he is mainly concentrating his efforts for gproc's support for distributed operations.
  • I felt that the main purpose of this library is not to provide a distributed process registry as much as extending the existing Erlang registration mechanisms with some additional features. The README in gproc's Github page clearly depicts it as being an "Extended process dictionary"; it just felt that the distributed part hasn't been the primary focus in the development of this library.
  • I could not understand how conflict resolution is managed in a distributed environment.

Stress Test

Here's the callback module:

ERLANG
-module(gproc_bench).
-behaviour(process_registry_bench).

-export([init/0]).
-export([register/2, unregister/2]).
-export([retrieve/1]).
-export([process_loop/0]).

init() ->
	%% start app on every node
	Nodes = [node() | nodes()],
	F = fun(Node) ->
		rpc:call(Node, application, ensure_all_started, [gproc]),
		rpc:call(Node, gproc_dist, start_link, [Nodes])
	end,
	lists:foreach(F, Nodes).

register(Key, Pid) ->
	Pid ! {self(), reg, Key},
	receive
		done -> ok
	end.

unregister(Key, Pid) ->
	Pid ! {self(), unreg, Key},
	receive
		done -> ok
	end.

retrieve(Key) ->
	case catch gproc:lookup_pid({n, g, Key}) of
		{'EXIT', _} -> undefined;
		Pid -> Pid
	end.

process_loop() ->
	receive
		{Sender, reg, Key} ->
			gproc:reg({n, g, Key}, ignored),
			Sender ! done,
			process_loop();
		{Sender, unreg, Key} ->
			gproc:unreg({n, g, Key}),
			Sender ! done,
			process_loop()
	end.

Note: in gproc, to ensure thread safety, a process can only set its own values. That's why the register/2 and unregister/2 callbacks here above send messages to the processes, which then register or unregister themselves (see process_loop). As you can see here above I've decided to provide a locking call for these functions (by using a receive block), to emulate the locking calls that I've used in the other libraries.

The results of the stress test are:

[table colalign="left|right|right|right|right"]
,1 Node,2 Nodes,3 Nodes,4 Nodes
Reg / second,"67,011","19,111","22,048","15,659"
Retrieve registered Key (ms),0,0,0,0
Unreg / second,"118,228","22,845","24,282","22,312"
Retrieve unregistered Key (ms),0,0,0,0
Re-Reg / second,"127,200","22,115","25,884","20,228"
Retrieve re-registered Key (ms),0,0,0,0
Retrieve Key of killed Pid (ms),178,"1,890","7,584","10,600"
[/table]

Conclusions

  • These are overall very good results.
  • I didn’t need to reduce the process count to make all of the test pass.
  • The monitoring of processes can be optimized. After having killed all the processes, on a cluster of 4 nodes it takes >10 seconds for gproc:lookup_pid/1 to not find the Pid once a process has exited.
  • Unfortunately, I had some inconsistent results running this test in a cluster of 2+ nodes. Often, the test could not retrieve the registered Key (after the first registration round) in less than 60 second, and timed out.

I was a little skeptical though on the inconsistency that I saw in the test results, which might be related to the gen_leader  issues that I've occasionally heard about. The author's choice to move towards locks_leader might be a sign of this. Despite these thoughts, this looked like a good potential candidate.

4. CloudI Process Groups

Considerations

cpg is an actively maintained library, and his main author Michael Truog is often very available to discuss his choices and provide support. cpg deals with Process Groups and not unique Registered Names, therefore my concerns where similar to the ones I had with pg2:

  • Handling Process Groups is very different from handling unique Registered Names. We can use the same trick used with pg2, i.e. creating Process Groups named with Key, with a single entry (the Pid).
  • Here too, having Process Groups basically means that conflict resolution isn't covered. This made me a little uncomfortable because I wanted to ensure that there would be a clearly identified single Pid per device in the whole system.

Stress Test

Here's the callback module:

ERLANG
-module(cpg_bench).
-behaviour(process_registry_bench).

-export([init/0]).
-export([register/2, unregister/2]).
-export([retrieve/1]).
-export([process_loop/0]).

init() ->
	%% start app on every node
	Nodes = [node() | nodes()],
	[rpc:call(Node, reltool_util, application_start, [cpg]) ||  Node <- Nodes].

register(Key, Pid) ->
	ok = cpg:join(Key, Pid).

unregister(_Key, Pid) ->
	ok = cpg:leave(Pid).

retrieve(Key) ->
	case catch cpg:get_members(Key) of
		{ok, Key, [Pid]} -> Pid;
		{error, {no_such_group, Key}} -> undefined;
		Error -> {error, Error}
	end.

process_loop() ->
	receive
		_ -> ok
	end.

The results of the stress test are:

[table colalign="left|right|right|right|right"]
,1 Node,2 Nodes,3 Nodes,4 Nodes
Reg / second,"110,198","42,680","20,703","8,488"
Retrieve registered Key (ms),0,0,0,0
Unreg / second,"109,374","32,264","25,599","15,128"
Retrieve unregistered Key (ms),0,1,0,0
Re-Reg / second,"126,791","30,862","32,138","20,791"
Retrieve re-registered Key (ms),0,0,0,0
Retrieve Key of killed Pid (ms),error,error,error,error
[/table]

Conclusions

  • These are overall very good results.
  • I was surprised of the major drop in a cluster of 4 nodes. I run this test multiple times and it always returned similar results.
  • The monitoring of processes didn't work appropriately. Even on a single node, the test experienced an internal timeout:
{'EXIT',
 {timeout,
  {gen_server,
   call,
   [cpg_default_scope,
    {get_members,
     "100000"}]}}}

I had to decrease the number of processes to around 25,000 to have the stress test pass in a cluster of 4 nodes. The monitoring issue didn't make me feel particularly at ease, however this library did look like a potential candidate.

5. Custom Solution: Syn

Considerations

Since it became clear that I could not use Erlang's native global or pg2 modules, and that the two other libraries I looked into were candidates but each one with their own little twerks, I decided to try a custom solution, which I called syn  (short for synonym).

In any distributed system you are faced with a consistency challenge, which is often resolved by having one master arbiter performing all write operations (chosen with a mechanism of leader election), or through atomic transactions. As said here above, I needed a global process registry for an application of the IoT field. In this context, Keys used to identify a process are often the physical object's unique identifier (for instance, its serial or mac address), and are therefore already defined and unique before hitting the system. The consistency challenge is less of a problem in this case, since the likelihood of concurrent incoming requests that would register processes with the same Key is extremely low and, in most cases, acceptable.

Therefore, Availability has been chosen over Consistency and Syn is eventually consistent.

Under the hood, Syn performs dirty reads and writes into a distributed in-memory Mnesia table, replicated across all the nodes of the cluster. This made me feel comfortable that I wouldn't need to reinvent the replication mechanisms of Erlang's native DB, however I needed a way to handle conflict resolution and net splits. For this reason, Syn can automatically manage conflict resolution by implementing a specialized and simplified version of the mechanisms used in Ulf Wiger's unsplit framework.

You can read more about Syn in its github repo.

Stress Test

Here's the callback module:

ERLANG
-module(syn_bench).
-behaviour(process_registry_bench).

-export([init/0]).
-export([register/2, unregister/2]).
-export([retrieve/1]).
-export([process_loop/0]).

init() ->
	%% start app on every node
	Nodes = [node() | nodes()],
	F = fun(Node) ->
		rpc:call(Node, syn, start, []),
		rpc:call(Node, syn, init, [])
	end,
	lists:foreach(F, Nodes).

register(Key, Pid) ->
	ok = syn:register(Key, Pid).

unregister(Key, _Pid) ->
	ok = syn:unregister(Key).

retrieve(Key) ->
	syn:find_by_key(Key).

process_loop() ->
	receive
		_ -> ok
	end.

The results of the stress test are:
[table colalign="left|right|right|right|right"]
,1 Node,2 Nodes,3 Nodes,4 Nodes
Reg / second,"106,324","52,792","60,958","40,929"
Retrieve registered Key (ms),0,0,0,56
Unreg / second,"105,506","50,591","67,042","42,896"
Retrieve unregistered Key (ms),0,0,0,0
Re-Reg / second,"106,424","51,322","77,258","47,125"
Retrieve re-registered Key (ms),0,0,0,0
Retrieve Key of killed Pid (ms),719,995,"1,577","1,825"
[/table]

Conclusions

  • These are overall very good results. I'm not sure why Syn is performing better with 3 nodes than with 2 (and I've repeated this test more than once).
  • I didn't need to reduce the process count to make all of the test pass.
  • The monitoring of processes worked appropriately.

Final notes

I want to stress out how comparisons and these tests are difficult to perform. Every library behaves differently, and it is hard (if not impossible) to define some kind of a common stress test to allow for a better understanding of their performance levels. I gave it a go, but looking at the above definition of my stress test for instance I ask myself: "Why did I set the process count to 100,000? I can see that most libraries behave fine with lower numbers". Also, "What would happen if instead of registering processes sequentially in a single process per node, we had them register themselves simultaneously, therefore increasing the load on the registry?". More importantly, "Does this test represent some kind of real life scenario?".

This article wants to share my thoughts and how I ended up writing Syn. Sure, Syn performs well in the defined use case and stress test, but this does in no way mean that the other libraries here won't perform way better in other stress tests and scenarios. I'd actually be glad to know that someone else is willing to take the time to evaluate these, and other, global process registries. They are a kind of holy grail; and let's remember that anything distributed is never easy, nor given.

As a final note, I'd enjoy reading comments from the library authors or other Erlang enthusiasts. This is such a delicate matter that I'd love to have a healthy exchange of opinions, hopefully contributing to improving all of our experiences.

Continue Reading…