N2O: Web Framework for Erlang/OTP

Nitrogen 2 Optimized, N2O was started as the first Erlang Web Framework that relies completely on WebSocket transport. Great compatibility with Nitrogen was retained and many improvements were made, such as binary page construction, binary data transfer, all events transmitted over WebSocket channel, minumum process spawns, work within Cowboy processes. N2O page renderer is several times faster than the original one.

Wide Coverage

N2O is an unusual framework that solves problems in different web development domains while staying small and concise at the same time. Started off as a Nitrogen concept of server-side framework it can also build client-side offline applications using same site sources. This becomes possible with the powerful Erlang JavaScript Parse Transform which extends Erlang language to JavaScript platform with two-side interoperability. You can as well use Elixir, LFE and Joxa languages to develop your back-end.

It also combines DSL and HTML templates approaches allowing to build JavaScript control elements using Erlang language and use inline rendering with DSL using the same code for both client and server sides! You decide how to use N2O, whether for mobile applications development using server-side rendering for HTML and JavaScript saving CPU power on mobile devices or for creating rich desktop offline applications with Erlang JavaScript compiler.

Why Erlang in Web?

We’ve measured all the existing modern web frameworks built with functional languages and Cowboy is still the king. On the chart below you can see raw HTTP performance of functional and C-like languages with concurrent primitives (Go, D and Rust) on VAIO Z notebook with i7640M processor.


Web-Servers raw performance grand congregation

Erlang was built for low latency binary data streaming in telecom systems. It was designed with extreme manageability, scalability and concurrent processing in mind. Assuming WebSocket channels are binary telecom streams and web pages are user binary sessions helps for better undestanding the choice of Erlang for the Web.

Using Erlang for the web allows you to unleash the full power of telecom systems for web-scale, asynchronuous, non-blocking, sharded, event-driven, message-passing, NoSQL, reliable, highly-available, high-performance, secure, qualative, real-time, clusterable applications. See Erlang: The Movie II.

N2O outperforms full Nitrogen stack with only 2X raw HTTP Cowboy performance downgrade thus upgrading rendering performance several times compared to any other functional web framework. And sure it’s faster than raw HTTP node.js performance.

Rich and Lightweight Applications

There are two approaches for designing client/server communication. The first one is called ’data-on-wire’. With this approach only JSON, XML or binary data are transfered over RPC and REST channels. All HTML rendering is performed on the client-side. This is the most suitable approach for desktop applications. Examples include Chaplin/CoffeeScript, Meteor/JavaScript and ClojureScript.

Another approach is sending pre-rendered parts of pages and JavaScript and then only replacing HTML and executing JavaScript on the client-side. This approach is better suited for mobile applications development since the client doesn’t have much resources.

With N2O you can create both types of applications: using N2O REST framework for the first type of application based on Cowboy REST API along with DTL templates for initial HTML renderings. And also Nitrogen DSL-based approach to model parts of the pages as widgets and control elements thanks to rich Nitrogen elements collections provided by Nitrogen community.

In cases where your system is built around Erlang infrastructure, N2O is the best choice you can make for the fast web prototyping, simplicity of use and codebase clarity. Despite HTML transfers over the wire, you will still have access to all your Erlang services directly.

You can also create off-line clients using Erlang JavaScript compiler just the way you’d use ClojureScript, JScala, Elm, WebSharper or similar tools. N2O covers: REST micro-frameworks, server-side rendering, client-side rendering, WebSocket events streaming, JavaScript generation and JavaScript macro system along with AVZ authorization library (Facebook, Google, Twitter, Github, Microsoft), key-value storages access library KVS and MQS Message Bus client library (GProc, RabbitMQ).

JSON and BERT

N2O uses JSON and BERT. All messages passed over WebSockets are encoded with native Erlang External Term Format. It is easy to parse it in JavaScript with Bert.decode(msg) and it helps to avoid complexity on server side. Please refer to http://bert-rpc.org for more information.

DSL and Templates

We liked Nitrogen for the simple and elegant way of constructing typed HTML with internal DSL which is analgous to Scala Lift, OCaml Ocsigen and Haskell Blaze approach. It enables you developing re-usable control elements and components in the host language.

Template-based approach requires programmers to deal with raw HTML, like with Yesod, ASP, PHP, JSP, Rails, Yaws and ChicagoBoss. It allows defining pages in terms of top-level controls, playholders and panels. Thus N2O combines both approaches.

The main N2O advantage is fast prototyping. But we also use it for large scale projects. Below is the complete Web Chat implementation using WebSockets. It demonstrates Templates, DSL and async interprocesses communication.

Listing 1: chat.erl


-module(chat). -compile(export_all). -include_lib("n2o/include/wf.hrl"). main() -> [ #dtl { file="index", bindings=[{title,"Chat"},{body,body()}] } ]. body() -> {ok,Pid} = wf:async(fun() -> loop() end), [ #span { id=title, body="Your chatroom name: " }, #textbox { id=userName, body="Anonymous" }, #panel { id=chatHistory, class=chat_history }, #textbox { id=message }, #button { id=sendButton, source=[userName,message], body="Send", postback={chat,Pid} } ]. event({chat,Pid}) -> Username = wf:q(userName), Message = wf:q(message), Terms = [ #span { text="Message sent" }, #br{} ], wf:reg(room), Pid ! {message, Username, Message}. loop() -> receive { message, Username, Message} -> Terms = [ #span { body=Username }, ": ", #span { body=Message }, #br{} ], wf:insert_bottom(chatHistory, Terms), wf:flush(room) end, loop().

You should try to build that with your favorite language/framework!

Changes from Nitrogen

We feel free to break some of the compatability with the original Nitrogen framework, mostly because we want to have a clean codebase and fastest speed. However, it’s still possible to easily port Nitrogen web sites to N2O. E.g., N2O returns id and class semantics of HTML and not html_id.

We simplified HTML rendering by not using html_encode which should be handled by application layer.

Nitrogen.js originally created by Rusty Klophaus was removed because of the pure WebSocket nature of N2O which doesn’t require XHR helper methods on the client. We added XHR fallback handling by using ’Bullet’ library written by Loïc Hoguin.

We also removed simple_bridge and optimized N2O at every level to achieve the maximum performance and simplicity. We hope you’ll enjoy using N2O. We are fully convinced it’s the most efficient way to build Web applications in Erlang.

Original Nitrogen was tested in production under high-load and we decided to remove nprocreg process registry along with action_comet heavy process creation. N2O creates a single process for async websocket handler, all async operations are handled within Cowboy processes.

N2O in Production

In this framework, most of all I liked the fact that most of the tasks solving in one code, in one language. And is not spread to the front-end & back-end.
Alex Radetsky, PearlPBX
Writing asynchronous web-applications has never been so easy for me. Now I really like to push data to client!
Max Treskin, Metachord
N2O is the easiest way how to write different webapps. It just works.
Alexander Karpich, RON-Telecom CJSC

Erlang Trendsetters on N2O

Excited to see these guys pushing boundaries; that's exactly what inspired Nitrogen in the first place. My hat is off to the synrc.com team for their work on N2O...
Rusty Klophaus, Nitrogen author, Basho Technologies, Inc.
N2O is one of the most interesting Cowboy based frameworks.
Loïc Hoguin, Cowboy, Nine Nines


comments powered by Disqus

 

synrc uses HEVEA
Сontinuous Integration | Events | Erlang PaaS | Music
Privacy Policy | Feedback | Brandbook
Copyright © 2005–2013 Synrc Research Center s.r.o.