Over a million developers have joined DZone.

Handling Websocket Connections in Erlang Application

DZone's Guide to

Handling Websocket Connections in Erlang Application

Check out how to handle websocket connections in an Erlang app, with a look at how to update app dependencies, configuring Cowboy, and more!

· Integration Zone ·
Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

Basically, when one needs an Erlang/OTP application to communicate with the World via HTTP or WebSockets it’s really great idea to use Cowboy web server. So, here are a couple of advantages of using it:

  • It’s modular, small but yet powerful. Cowboy includes different basic handlers for HTTP, REST, spdy, and websockets. All you need it just update your application dependencies, configure cowboy, create your own handler “inherited” from basic one.
  • Extremely fast. Cowboy starts custom handler as a separate Erlang process. So if you have a lot of HTTP or websocket connections they will be processed inside Erlang VM concurrently and it’s really awesome! In one of our projects, we have Cowboy handling 50k concurrent websocket connections on single Amazon instance with 4 CPU cores.
  • Can be easily embedded into another Erlang application. And while having selective dispatch and fastCGI support can redirect some requests to PHP, Ruby, and Python applications.

Update Application Dependencies

Here at Oxagile we use rebar as a build tool. Basically, it’s like a composer for PHP applications but much more advanced. So to add cowboy as a dependency we should update our rebar.config file by adding following row into deps section:

{deps, [
    {git, "https://github.com/extend/cowboy.git", {tag, "1.0.3"}}

  % other dependencies
    {git, "https://github.com/tel/mochijson2.git", {tag, "2.3.2"}}
    {git, "git://github.com/jbrisbin/amqp_client.git", {tag, "3.5.2"}}

Then just go to a console and run

$ rebar get deps

Then please update your *_app.src file by adding “cowboy” entry to applications section. Therefore, when you pack your application into release cowboy will be started automatically upon release launch.

{application, demo,
 {description, "ws demo app"},
 {vsn, "0.0.1"},
 {registered, []},
 {applications, [
 {mod, { demo_app, []}},
 {env, [  ]}

Configure Cowboy Inside Your Application

Let’s say that our application name is demo. So, you should have demo_app.erl file inside your src folder. Let’s modify it by adding some configuration for Cowboy. First of all, we will configure routing and ports cowboy will listen to.



-export([start/2, stop/1]).

start(_StartType, _StartArgs) ->

 Dispatch = cowboy_router:compile([
   {'_', [
       {"/ws", demo_cowboy_handler_ws, []},
       {"/auth/:token/:user", demo_cowboy_handler_rest, [auth]},

 {ok, _} = cowboy:start_http(http, 100, [{port, 8889}], [{env, [{dispatch, Dispatch}]}]),

stop(_State) ->

In the example above, we’ve added two routes with different handlers which should be implemented and told Cowboy to listen to 8889 port. Also, it’s possible to listen to multiple ports. All you need to do is just call cowboy:start_http multiple times but please note that first parameter of the function (listener name) should be different each time.

start(_StartType, _StartArgs) ->

 DispatchWs = cowboy_router:compile([
   {'_', [
       {"/ws", demo_cowboy_handler_ws, []}

 DispatchRest = cowboy_router:compile([
   {'_', [
       {"/auth/:token/:user", demo_cowboy_handler_rest, [auth]}

 {ok, _} = cowboy:start_http(ws, 100, [{port, 8889}], [{env, [{dispatch, DispatchWs}]}]),
 {ok, _} = cowboy:start_http(http, 100, [{port, 8888}], [{env, [{dispatch, DispatchRest}]}]),

Create Your Custom Cowboy Handler

The last thing left to do is just create a handler for websocket connections. It a regular Erlang module but in should be “inherited” from cowboy_websocket_handler. Erlang behaviours are great because they have a well-defined interface: a set of callback functions with custom implementation but with defined input and output. So, for cowboy_websocket_handler these functions are:

init – init websocket connection (see below)
websocket_init – inits state for the ws connection. It’s possible to pass some init parameters through cowboy_router:compile like that:

 DispatchWs = cowboy_router:compile([
   {'_', [
       {"/ws", demo_cowboy_handler_ws, [SomeConfigParams]}

and 3rd parameter Opts in websocket_init callback will contain these params;
websocket_info – handles Erlang messages. It’s possible to send messages to handler’s process like to any other erlang process i.e. WsPid ! {data, SomeData};
websocket_handle – handles frames received from client;
websocket_terminate – handles termination of ws connection. This function is called just before websocket termination;

Detailed callbacks specification can be found here. So here is the code for our demo handler:



   websocket_init/3, websocket_handle/3,
   websocket_info/3, websocket_terminate/3

init({tcp, http}, _Req, _Opts) ->
 {upgrade, protocol, cowboy_websocket}.

websocket_init(_TransportName, Req, Opts) ->
 {ok, Req, undefined_state}.

websocket_handle({text, Msg}, Req, State) ->
 {reply, {text, << "responding to ", Msg/binary >>}, Req, State, hibernate }.

websocket_info({data, SomeData}, Req, State) ->
 {reply, {text, SomeData}, Req, State};
websocket_info(_Info, Req, State) ->
 {ok, Req, State, hibernate}.

websocket_terminate(_Reason, _Req, _State) ->

Basically, that’s it with websockets. Cowboy make things much easier and allows us to take care of application logic. For a better understanding of cowboy_websocket_handler behavior please refer to the documentation where you can find a detailed explanation of callback functions’ inputs and outputs. In our opinion, only one small issue exists in Cowboy websocket handler: one can’t terminate (with or without message) WS connection in websocket_init callback, but this can be easily solved by sending Erlang message to WS process and handling it with websocket_info callback.

Kind of Conclusion

Let’s say we have a software solution which includes number of modules implemented using different technologies like in example below:

Handling Websocket Connections in Erlang Application

So, we have WebSocket Clients and PHP App clients (most likely these are 2 parts of one JavaScript application). This application makes HTTP request via 8080 port and uses 8089 port to establish WS connections. In order to handle these connections, we have 2 separate Cowboy handlers created. All other connections are forbidden by the firewall. But, inside our cluster (LAN) we have all the connections allowed. So our internal application can make requests to Cowboy and it’s rest handler which is hidden from the World.

With SnapLogic’s integration platform you can save millions of dollars, increase integrator productivity by 5X, and reduce integration time to value by 90%. Sign up for our risk-free 30-day trial!

erlang ,websockets ,apps

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}