Recover the State After a Crash
Learn how to hang on to a specific state and restore it if a process happens to exit abnormally.
We'll cover the following
Fault tolerance
This is where we fulfill the promise of fault tolerance. It’s one thing to restart a process if it crashes and then move on. It’s another thing entirely to restart it and restore the last known good state.
The way we do this is to save a copy of the data outside the current process, or any other process the current one is linked to. We do this when we initialize the process, and then again whenever the state changes.
Whenever we start a new process or restart a crashed process, we check for that saved state. If it exists, this means we’re restarting, so we’ll use the saved version. If it doesn’t exist, that means it’s a new process, so we’ll use a fresh state.
ETS tables
ETS is the storage engine we use. ETS is short for Erlang Term Storage. ETS comes with OTP, and ETS allows us to store data in in-memory tables as two-element tuples. The first element of each tuple is the key. The value is the second element.
ETS tables offer a number of different options to choose from. These options specify how they store data and which processes can access it.
Types of ETS
There are four different types of ETS tables:
:set
is the default type, and:set
tables store exactly one value per key.:ordered_set
tables behave the same as:set
tables, except that they order the keys.:bag
tables store multiple values under the same key, as long as the values are not exact duplicates.:duplicate_bag
tables store multiple values under the same key, even if they are exact duplicates.
Levels of privacy
There are three levels of privacy:
:private
means that only the process that starts the table can read to or write from it.:protected
is the default. Using:protected
means the process that starts the table can read from and write to the table. All other processes can only be read from it.:public
means that all processes can read from and write to the table.
There is also :named_table
option. This option allows us to reference that table by name instead of needing to keep track of itsreference.
Get hands-on with 1400+ tech skills courses.