Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use an OTP behaviour instead of spawn?

I understand how a process works. And I understand how to implement OTP behaviours such as gen-server, etc.

But It's not clear to me when I would chose one approach over the other.

For instance, Cesarini et. al., in Erlang Programming, implement the database server on p 240 by spawning a process, writing a loop function, etc. Joe Armstrong's chat client on p 196 in Programming Erlang also spawns a process.

Why wouldn't these be better implemented as OTP gen-servers? Is it for educational purposes? Or are there sound technical reasons?

In other words, what rules of thumb would guide me to implement one approach over the other?

Many thanks.

like image 927
Lloyd R. Prentice Avatar asked Oct 02 '13 19:10

Lloyd R. Prentice


1 Answers

In the two examples above, simple spawned processes are preferred for educational purposes: this is simpler to explain, these authors do not have to explain OTP to convey what they want to teach, and it is important anyway to understand the concept of a process in Erlang. Even in a real-world application following OTP rules, not all processes are implemented with OTP behaviors and inserted in a supervision tree.

The rule of thumb is quite simple. Determine if you want to follow OTP design principles by reviewing what it brings (code changes, fault tolerance, etc.) or if you plan to integrate with OTP compliant code. Do follow OTP principles if you want any of the features it brings and avoid reinventing the wheel.

If you stick to OTP principles, and therefore use gen_* behaviors, you should do a simple spawn for any short-lived process that does not need to be supervised or code-upgraded. It shall not live longer than the time to deploy a release (otherwise, you would need soft_purge anyway). All other processes must be inserted in the supervision tree and probably implement a gen_* behavior.

like image 126
Paul Guyot Avatar answered Nov 07 '22 05:11

Paul Guyot