[erlang-questions] When to use gen_server?

Garrett Smith g@REDACTED
Wed Jan 11 23:32:44 CET 2012


On Wed, Jan 11, 2012 at 4:17 PM, Navin Parray <navinparray@REDACTED> wrote:
>
> Hello everyone,
>
> I'm developing a backend with Erlang/OTP and I need advice on the type of
> behaviours I should use for the various applications. The code is broken
> into four areas. One is a webmachine REST interface called myapp_webapi.
> This calls an application called myapp_core. myapp_core provides an
> abstraction of the data access layer. The data access layer consists of two
> applications, myapp_store and myapp_indexer. myapp_store connects to a Riak
> database while myapp_indexer connects to an ElasticSearch engine.
>
> My confusion lies in not knowing what type of behaviour the various layers
> should implement. Should the myapp_core be a gen_server or a basic
> application? Similarly, what about the myapp_store and myapp_indexer
> applications? I'd like to understand the reason I would chose one over the
> other in this situation.
>
> I could do this by simply calling modules in the webmachine application but
> I want to keep the areas separated because I will need to provide a second
> REST interface for another application. This would use the same data but
> only required read access to a couple data points and would be used by the
> public whereas myapp_webapi is used by my frontend applications only. I
> would need to call myapp_core from that application also.

Your overall project is probably one OTP application. If you're using
rebar to build your project, you already have that setup (thanks
rebar!)

The components you're talking about are either registered gen_server
processes or they're just modules, depending on how your data access
is implemented.

If you data access layer (some Riak client interface?) supports
concurrent access (e.g. multiplexing, connection pools, etc.) there's
no need to use gen_servers as intermediaries. The gen_server will
serialize your requests and become a bottleneck in your application.
If your database libraries can be used directly by your web tier, I
think you're just talking about a module abstraction layer to give you
a clean API.

gen_servers are just fancy interfaces to Erlang processes. Each
process has a mailbox and communicates with the outside by sending and
receiving messages.  If you don't need to serialize your data
processing requests, don't bother with all that.

While you could implement some pretty fancy things using multiple
coordinated processes, I'm betting that's already in your database
client.

Garrett



More information about the erlang-questions mailing list