Posted by: fdmanana | December 8, 2010

Adding posix_fallocate to Erlang/OTP

posix_fallocate is a POSIX optional system call that allows to reserve space for a file. It guarantees that subsequent writes will not fail if the total written amount doesn’t exceed the allocated amount of space.

Its big advantage is that when the space is allocated, the kernel tries to allocate contiguous disk blocks, which will speed up IO operations.

It was recently submitted and accepted to Erlang/OTP:

Posted by: fdmanana | October 5, 2010

Purely Functional Data Structures

A good finding at google books, “Purely Functional Data Structures” by Chris Okasaki:

Purely Functional Data Structures (Chris Okasaki)

Now in my TOREAD list.

Posted by: fdmanana | September 27, 2010

Streaming the body of HTTP POST/PUT requests with Erlang OTP

Yesterday I submitted a patch to the Erlang OTP erlang-patches mailing list to add a feature, to the httpc module, that has been lacking for a long time:

Streaming the body of HTTP PUT and POST requests.

It has just been merged into OTP’s pu branch:

Hopefully it will get into the next R14 release.

UPDATE: A few days after I submitted another patch on top of that one:

It adds support for automatically chunking (HTTP chunked Transfer-Encoding) the payload based on what the streaming function returns on each call.

UPDATE: Did some simplifications to the implementation and API when it automatically adds chunked-transfer encoding headers. The new full patch:

Posted by: fdmanana | September 24, 2010

The new SSL implementation in Erlang OTP

Recently, I was trying the new SSL implementation of OTP. This new implementation appeared in the R12 series and is now the default one in R14. Unlike the “old” implementation, this one is mostly done in Erlang (instead of being basically a wrapper around the OpenSSL library) and only uses the cryptographic functions that the OpenSSL library provides.

The motivation to try it out, was that I was having often (but not very often) errors like the following from the “old” SSL implementation:

** {error,{badinfo,{tcp,#Port,

(Yes, this was CouchDB related). So I tried the following code in OTP R13B03 and R13B04:

test() ->
    Body = iolist_to_binary([
        "GET / HTTP/1.1\r\n",
        "Host: ", ?HOST, "\r\n",
        "Accept: */*\r\n",
        "Connection: close\r\n", "\r\n"
    Options = [
                {ssl_imp, new},
                {nodelay, true},
                {active, false},
                {verify, verify_peer},
                {depth, 3},
                {cacertfile, "/etc/ssl/certs/ca-certificates.crt"}
    {ok, S} = ssl:connect(?HOST, 443, Options),
    ok = ssl:send(S, Body),

loop(S) ->
    ssl:setopts(S, [{active, once}]),
    {ssl, S, Data} ->
        io:format("received data:  ~p~n", [Data]),
    {ssl_closed, S} ->
        io:format("socket closed", []);
    {ssl_error, S, Error} ->
        io:format("socket error:  ~p", [Error])

And I was getting the following stack trace when ssl:connect/3 was called:

=ERROR REPORT==== 17-Sep-2010::18:33:04 ===
SSL: 1056: error:{error,
                     {'Type not compatible with table constraint',
                        {ssl_certificate_db,add_certs,3}]}}}}}} /etc/ssl/certs/ca-certificates.crt

I was finding it weird, since the trusted certificates files I was providing was in the PEM format (supported according to the man page) and it worked with the “old” SSL implementation.

I posted a message to the erlang-bugs mailing list reporting the issue, since it seemed to me that it was a regression:

It turned out to be a true regression.
Fortunatelly, Ingela Anderton Andin, from the OTP team, quickly responded and worked on a few patches against the R14B release that I tried out until it worked. Those patches are all available at her github account:

(I must say github is one of my favourite free services on the Web, congratulations to the creators and maintainers).

A special thanks to Ingela for her quick response.
I squashed the relevant commits into a single patch to apply against R14B and it’s available here:

Since Ubuntu is using R13B03 and can not update to R14B so soon (it’s a very recent release and besides desktopcouch/couchdb, they have other Erlang OTP dependents), I prepared them an equivalent patch to apply against R13B03 (the ssl and public_key code has quite a lot of diferences between R13 and R14), available in the following github gist:

Also, as part of that same erlang-bugs thread, it was also proposed a suggestion for adding an extra possible value passed to the certificate validation chain function (option verify_fun) that allows for distinguishing between unknown CAs (not listed in the trusted certificates file) and certificates self-signed by the peer (something common in intranets). This because currently, as of R14B, the term {bad_term, unknown_ca} is used to signal both cases (unknown CA and self-signed ceritificate.

It turns out that the suggestion was accepted by the OTP team and is now available in development branches (will make it into the next OTP R14 series release):

After that commit, an unknown CA error is still represented by the term {bad_cert, unknown_ca} and a self-signed certificate is now represented by the term {bad_cert, selfsigned_peer} (the “old” SSL implementation allowed to distinguish both cases as well).


If you use the new SSL implementation (default on R14), don’t except to be able to use the certificates file in a Ubuntu system (and also in a Linux Caixa Mágica system). You’ll have to apply one of those patches available in the gists mentioned above.

I’m a bit surprised that I was the first one finding and reporting this issue/regression.

A big thanks to Ingela Andin from the OTP team for the quick response.

Posted by: fdmanana | September 2, 2010

List concatenation in Erlang

Recently I looked at the myth that tells us that the list concatenation operator in Erlang is inefficient.
This is mentioned at The Eight Myths of Erlang Performance section 2.4.

The meaning of “inefficient” here is in comparison with other approaches. A common approach I see very often in Erlang code is:

lists:flatten( [ List1, List2 ] )

I decided to write a little performance test that compares the following approaches:

  • List1 ++ List2
  • lists:flatten( [ List1, List2 ] )
  • lists:append( List1, List2 )
  • lists:append( [ List1, List2 ] )

The tests’ code is:


-define(ITERS, 100).
-define(LIST_SIZE, 1000000).

concat_plus_plus(L1, L2) -> L1 ++ L2.

run() ->

    {ok, T1, Dev1} = run_test(?ITERS, ?MODULE, concat_plus_plus, fun gen_args_2/0),
    io:format("Operator ++: ~p iterations, each list with ~p elements, "
        "average time of ~p milisecs, standard deviation: ~p~n",
        [?ITERS, ?LIST_SIZE, T1, Dev1]),

    {ok, T2, Dev2} = run_test(?ITERS, lists, flatten, fun gen_args_1/0),
    io:format("lists:flatten: ~p iterations, each list with ~p elements, "
        "average time of ~p milisecs, standard deviation: ~p~n",
        [?ITERS, ?LIST_SIZE, T2, Dev2]),

    {ok, T3, Dev3} = run_test(?ITERS, lists, append, fun gen_args_2/0),
    io:format("lists:append(L1, L2): ~p iterations, each list with ~p elements, "
        "average time of ~p milisecs, standard deviation: ~p~n",
        [?ITERS, ?LIST_SIZE, T3, Dev3]),

    {ok, T4, Dev4} = run_test(?ITERS, lists, append, fun gen_args_1/0),
    io:format("lists:append( [L1, L2] ): ~p iterations, each list with ~p elements, "
        "average time of ~p milisecs, standard deviation: ~p~n",
        [?ITERS, ?LIST_SIZE, T4, Dev4]).

run_test(Times, Mod, Fun, GenArgs) ->
    Ts = lists:foldl(        
        fun(_, Acc) ->
           Args = GenArgs(),
           {T, _} = timer:tc(Mod, Fun, Args),
           [T | Acc]
        [], lists:seq(1, Times)),
    Avg = lists:sum(Ts) / length(Ts),
    {ok, round(Avg / 1000), round(std_dev(Ts, Avg) / 1000)}.

std_dev(Values, Avg) ->
    Sums = lists:foldl(
        fun(V, Acc) -> D = V - Avg, Acc + (D * D) end,
        0, Values),
    math:sqrt(Sums / (length(Values) - 1)).

gen_args_2() ->
    L1 = binary_to_list(crypto:rand_bytes(?LIST_SIZE)),
    L2 = binary_to_list(crypto:rand_bytes(?LIST_SIZE)),
    [L1, L2].

gen_args_1() ->
    L1 = binary_to_list(crypto:rand_bytes(?LIST_SIZE)),
    L2 = binary_to_list(crypto:rand_bytes(?LIST_SIZE)),
    [[L1, L2]].

Running the tests 3 times in a row:

Erlang R13B04 (erts-5.7.5)  [64-bit] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> c(teste).
2> teste:run().
Operator ++: 100 iterations, each list with 1000000 elements, average time of 32 milisecs,
standard deviation: 23
lists:flatten: 100 iterations, each list with 1000000 elements, average time of 138 milisecs,
standard deviation: 39
lists:append(L1, L2): 100 iterations, each list with 1000000 elements, average time of 59 milisecs,
standard deviation: 6
lists:append( [L1, L2] ): 100 iterations, each list with 1000000 elements, average time of 82 milisecs,
standard deviation: 18
3> teste:run().
Operator ++: 100 iterations, each list with 1000000 elements, average time of 66 milisecs,
standard deviation: 22
lists:flatten: 100 iterations, each list with 1000000 elements, average time of 151 milisecs,
standard deviation: 51
lists:append(L1, L2): 100 iterations, each list with 1000000 elements, average time of 34 milisecs,
standard deviation: 22
lists:append( [L1, L2] ): 100 iterations, each list with 1000000 elements, average time of 98 milisecs,s
tandard deviation: 38
4> teste:run().
Operator ++: 100 iterations, each list with 1000000 elements, average time of 35 milisecs,
standard deviation: 26
lists:flatten: 100 iterations, each list with 1000000 elements, average time of 155 milisecs,
standard deviation: 52
lists:append(L1, L2): 100 iterations, each list with 1000000 elements, average time of 63 milisecs,
standard deviation: 15
lists:append( [L1, L2] ): 100 iterations, each list with 1000000 elements, average time of 89 milisecs,
standard deviation: 34

So in the end either the ++ operator or the lists:append function are the best approaches.

I’m wondering if this applies to Caml as well (operator @ versus functions in the List module).
The List module man page for Caml explicitily says that the implementation for the functions append, concat and flatten are not tail recursive. This gives me the idea that underneath they’re not implemented in C but in pure Caml.
My Caml skills are now too rusty, and would need some time to write similar test code in Caml.
Maybe I’ll do it for a future post.

Posted by: fdmanana | July 14, 2010

My CouchDB retrospective

This is a summary about how I got into the Apache CouchDB community.

By late summer 2009, my friend Sérgio Veiga told me he was using Erlang for his job and how cool the language is as well as the Erlang OTP platform. He knew I was a fan of OCaml and Prolog back in the academic years, and so I would immediately embrace Erlang.

I started by reading Joe Armstrong’s book Programmning Erlang. Then I was thinking about creating some Erlang project but hadn’t ideas for creating something useful and original and I didn’t felt like porting some library or framework from some other language. So I decided to google for existing open source projects done in Erlang. Amongst the first I found was CouchDB.

Back then I was not familiar at all with NoSQL. The closest thing I knew about was probably memcached . At the moment my job was related to Java enterprise (J2EE, Spring, Hibernate, etc), so I immediately started to sympathize with CouchDB’s simplicity and base principles. I started to realize how unnecessarily complex (and counter productive) the Java enterprise + Oracle + Hibernate world is.

So I decided to start contributing to CouchDB. I started searching for the simplest tasks in the Apache Software Foundation’s issue tracking system (JIRA) just to get to know better CouchDB. The first issue I tackled was for Futon, the administration Web UI. This task only involved JavaScript, CSS and HTML. It very straightforward.

Afterwards I started looking into issues involving the Erlang side of CouchDB. The first JIRA issue involving Erlang that I solved was in fact a minor new feature for the CouchDB 0.11 release. This issue was a challenge at the time because it implied understanding the existing HTTP server layer code, some HTTP details I was not aware of (chunked transfer encoding, Content-MD5 header, content encodings) and the code for streaming attachments into a DB (forced me to learn how the core DB code words, the storage details). Paul Davis helped me improving the patch and getting it committed (thanks Paul). That feature also originated a small patch for the Mochiweb project.

Those 2 patches (CouchDB ticket 558 and Mochiweb) were the first real Erlang code I ever wrote.

I then started looking for more (complex) issues to solve in their JIRA system and started following the development mailing list and the IRC channel. By far most of the contributions I gave were targeted at solving existing bugs or implementing features requested by the community. Bringing completely new ideas to the project was never easy, as I had never developed an application using CouchDB (not even today), yet I was able to contribute with code.

Last month I was elected committer and today Apache CouchDB 1.0.0 was released. For me it has been a very rewarding experience for 2 reasons:

  • Technically I learned a LOT – from Erlang and OTP principles to an alternative paradigm for data modeling and storage, many HTTP REST details and a new vision of JavaScript and its potential (CouchApps and CouchDB related projects implemented with node.js). This learning was not just a result from reading existing code and writing new code but it was also a result from the interaction with the committers and other developers.
  • The community. CouchDB’s community is very friendly, helpful and dedicated. This community has been growing fast.

CouchDB is growing and taking a unique direction towards data modeling, replication and Web applications.

Posted by: fdmanana | June 24, 2010

Embracing Concurrency at Scale

A very good talk about distributed systems and high concurrency given by Justin Sheehy:

Posted by: fdmanana | June 21, 2010


I’m now reading all (or most of) the OAuth implementation details:

It was about time to read it…

Posted by: fdmanana | June 16, 2010

2 interesting articles

Today Wout Mertens sent a mail to CouchDB’s development mailing list pointing to 2 interesting articles:


Just found this interesting article:

Older Posts »