Restore the State for a Node

Learn how we can capture and forward state and PID from old to new processes.

State loss problem

Our process graph nodes are supervised, which means that they get restarted when they error and die—which is a very handy thing. But there’s a gotcha. They get reborn as new blank nodes with no previous state. Another process will be set up to take over from the old process.

Obviously, we would like to capture any state from the old process and forward it to the new process—rather like a baton handover in a relay race.


As we know, we can make use of an agent to maintain process state at this handover point. The trick here is to push any process state onto the agent at process termination and to fetch that back at process initiation.

It’s time to fill out those do_init/0 and do_terminate/1 private functions that we introduced earlier in the genserver callbacks.

Process initiation

First, we deal with the process initiation case:

Get hands-on with 1200+ tech skills courses.