Metalinguistic Abstraction

Computer Languages, Programming, and Free Software

Archive for the ‘erlang’ Category

Large Binary Data is (not) a Weakness of Erlang

with 4 comments

Update: Good news in the comments, with some good details. To sum up:

split_binary/2 is the call to use. Binaries are also refcounted instead of garbage collected. The next release will fix large binary pattern matching due to improper handling of bignums in the current release. So the internet wins again and the original blog author should be happy.

Finally — even if we get all this bookkeeping right — we have to deal with the possibility of obscene wastage. Suppose someone loads five hundred megabytes of binary data into memory, takes a five hundred byte slice, and discards the old instance. We can’t deallocate just parts of an array with standard [mc]alloc(), so we have to make a decision on how many bytes of wastage is worth not copying the salient part of the array to a fresh, appropriately sized heap allocation. Sometimes it may be clear, but with lots of small-ish binary instances wasting some memory it may be less clear. Or I guess we could just call realloc() every time, which may be a little bit overkill but would be simple-ish and predictable…

One thing that does remain, however, is shrinking the region allocated for the binary memory. There is a danger of keeping big chunks of binary around when one has taken a tiny slice, so either some GC work needs to be put in place to realloc() properly or the user just needs to be cognizant and copy the binary if they feel that it may release a large chunk of memory and then let all previous references die.

Venturing onward on this posting should be reserved for archivists and the curious.

Read the rest of this entry »


Written by fdr

July 9, 2007 at 3:24 am

Posted in erlang, languages

A Case for Erlang

with 17 comments

Brief prelude on how I got to this topic for flavor and context: earlier this week I was having discussion from an old friend from Berkeley about methodologies in scaling, set off by a discussion rooted in a set of Motorola slides[0] comparing an Erlang, C plus Erlang, and C(++) telecom equipment code that I had forwarded to him. He was aware of Erlang and its general properties since I had been talking about Erlang some time back when I had been playing around with it as a way to coordinate and cluster nodes for KM[1].

He then remarked that he was working on some stuff that needed to be parallelized and support high concurrency and referred me to the SEDA research project as a guiding influence on his budding architecture. SEDA emphasized using event queues to send messages between parallel parts of the architecture with feedback loops for control and updates. I took a look at this and felt there were a few problems:

  1. SEDA is a mothballed research project, so there’s no up to date code
  2. No project I know of maintains a well proven, high quality implementation to abstract a comfortable amount of the mundane details away from me.
  3. Sometimes the model you are working with calls for a thread and not events.

Qualms one and two are strictly at practical and not at a ideological level. SEDA has some high level ideas that I have no strong crystallized negative reaction to and are probably good reading…but at a nuts and bolts level I am left unenthusiastic by the general prospect of not having powerful abstractions readily available to achieve these aims.

Qualm three is much more philosophical and meaty. I have seen a paper that pretty much sums up some of my feelings on the matter: sometimes, you don’t want an event-driven abstraction. The paper even mentions SEDA by name as an example of an event-oriented tool used by the authors to set up high-concurrency servers. Despite the fact that SEDA tried to make this easy (or easier) the authors felt that sometimes a thread was really what one wanted and the event-driven model was just not as clear or easy to write as the thread-oriented one. Not being as clear or easy to write means more bugs. However, not all is lost: the paper concludes that there’s no fundamental reason why events should be the only way to achieve high concurrency. There is some passing mention of Erlang, but nothing substantial. But what have we gained here? Validation of threads? Aren’t threads the road to madness? We can probably do better than just threads and synchronization constructs which themselves pose a substantial risk to program reliability.

With this background information it’s easy to imagine a relatively annoying scenario with a {C, Cpp, C#, Java, Python, Ruby, Lisp, Haskell, damn-near-anything} program: What happens when you write part of your system in a threaded manner (because it was natural feeling, and that’s not a necessarily a dirty instinct, as supported by the paper in qualm three) but then need to extract this threaded functionality because it needs to handle more concurrency or be made network-accessible to work over multiple machines? Generally you get to rewrite a lot of code to fit into the SEDA diagram, including re-writing threaded code to be event-driven and network-accessible, which also means having to take care of the network and protocol issues. Don’t forget to having to update your old code to use the event-driven version, a painful affair if you used synchronization constructs. Your only alternative to these rewrites is to defensively program everything with the intention of being event-driven which will only waste a lot of time and make your program less efficient unless you provide even more code to do shared-memory interactions as a secondary mode; otherwise, you will be stuck doing lots of serialization/serialization to interact with stuff on the same machine. Let’s not even mention that code that could have been handled more gracefully with context switches rather than event handling will end up being maddening to write and more opaque than one feels it should be. Welcome to Tartarus, enjoy your stay.

So now we finally talk about Erlang. Erlang attacks a lot of these problems on many fronts including in its implementation, syntax, and semantics. Yet, people seem to be unfazed by the idea of re-inventing Erlang’s wheels when it comes to Erlang’s choice application domain, and I suspect a large part of the reason for this is that most people who are vaguely aware of Erlang and its reputation don’t know what wheels have already been invented in Erlang. Included in those are some wheels that they probably haven’t thought of yet when starting out and could use to assist implementation, others are wheels (some quite elaborate) that they’d be forced to implement, test, and maintain on their own otherwise or suffer from something painful.

Here is a list of some of the more important things that came to my mind that you get “for free” for using Erlang:

  • A generally expressive syntax that reduces the amount of code from somewhere between one tenth and one forth of the roughly equivalent code in C/C++[3]. Error density was seen to be about the same, so that also means about a fourth to a tenth of the number of bugs.
  • A virtual machine that itself supports kernel event polling (at least under Linux) to allow you to easily handle tens of thousands of persistent connections (such as TCP streams) modeled with a simple one-context-per-connection abstraction[4]. This is not the default and can be enabled with “+K true” when starting the “erl” interpreter.
  • The overhead of a process is 318 machine words.
  • A virtual machine that can efficiently automatically handle SMP (at least under Linux) and distribute processes between nodes
  • Semantically simple process-oriented concurrency (which avoids a lot of bugs seen with shared-state threads) with high-speed message passing and process scheduling (how else could it handle 80,000 processes?), thanks in large part to no-mutate language semantics
  • Extensive heap sharing between processes to avoid message copying, once again from no-mutate language semantics. (used the “-shared” switch)
    • This is not the default behavior: otherwise, per-process heaps and full-copies are used to maintain short GC pauses for real-time applications
  • Network-transparency between processes, even when passing higher-order objects like closures(!)
    • Some of the more “leaky” abstractions made for performance such as ETS or process tables that allow for mutation can have opaque continuation returns that cannot be serialized in this way. In any case, it’s in a very small minority.
  • Node and process monitoring and restart strategies to allow you to write robust, idiomatic, fault-tolerant programs
  • Automatic transitive closing of Erlang nodes for maximum reliablity/message passing speeds as well as (when that full-connectivity is impossible) message routing between intermediate nodes.
  • Pattern-matching of several data types. Not only the obvious tuples, but also for binary streams, largely eliminating temptations to use inefficient ASCII-based wire protocols.
  • Distributed synchronization constructs
  • Safe local and global name registration
  • A powerful distributed database, MNesia
  • Code hot-swapping
  • Application versioning and packaging support
  • Metaprogramming using the AST, so Lispish-style macros exist. NOTE: in Erlang parlance, this is called the “parse_transform” procedure. “Macros” in Erlang lexicon refer to something more like the C preprocessor.
  • Generic constructs for common tasks: finite state machines, event-driven (for when they are the most natural model), and the ever-useful and flexible “generic server” (gen_server) behavior.
  • A community that is focused on reliability, performance, and distributed applications
  • More community that is trying to give Erlang some more tools with “general appeal” such as a web application framework
  • Heavy documentation, both of the libraries and of methodology refined by twenty years of language development, research, and application

Let’s revisit the scenario above, where you were stuck in Tartarus re-writing your threads into events and making them accessible via network, but now starting out with an Erlang code.

Once again, as before, some of your code which you had written using a process-oriented model has outgrown its britches and needs to be made scalable and concurrent. The latter part of that is mostly taken care of for you: simply spawn a process for every work item, as you were before. Thanks to the Erlang VM, your eight-processes turned eight-thousand are having no problem handling the flood of work and utilizing as many machine resources as as possible. You don’t need to coerce yourself into writing an event-based server, introducing bugs and obfuscating code as you go, a huge win already.

Now you get to worry about making things distributed, which is a little more complicated. Your first attempt is to allocate some dedicated machines to running the code in question for more power. Since message-passing is network-transparent, the changes to your code elsewhere in your application is minimal. A send is still a send, whether across a network or on the same node. You write some code to decide how to allocate those queries across these machine resources, which themselves may dynamically reallocate work, carrying along with it the process name to send the return message to to avoid centralized response multiplexing overhead[5]. Ultimately some node in the cluster sends the response or the requester times out. In many cases you are now done, you can just constantly add machines to this glob to get more power.

To spice up the story, let us suppose that you notice that there’s a lot of state-passing going on to synchronize nodes that’s just too network-intensive that wasn’t a problem when this was a single-node solution, so you rewrite some of your code to pass a closure that contains instructions on how to update the node’s state. This means you just avoided having to write some sort of fancy differential state transfer procedure; you’ve simply told the node at the other end how to compute the new state from an old one by sending the procedure itself on the wire instead of the finished product.

Finally, if you had followed some of the OTP design principles[6] to begin with (which is not uncommon, even when working in a single-node environment, they are exceedingly convenient abstractions) and used the gen_server (or likewise) behavior you can get (or might have already had) a supervision tree going that’ll make your application serving this stuff fight down till the last man. And so ends our tale.

Don’t make this glowing report make you think there aren’t difficulties here; there definitely are real tangible downsides to Erlang, not the least of which is recruiting programmers, questionable string handling, and the somewhat-warty records. It’s also considerably slower than C when it comes to sequential computation. However, consider that it is clearly not a toy, and that groups of programmers — not all of them Gods, I’m sure — have employed it to process unfathomable quantities of our telephony data with nine nines of reliability[7], all in two million lines of code[8]. Erlang is an artifact designed with a purpose and a vision and will be difficult to best in technical merit in its chosen problem domain without embarking on a project of similar or greater scope.


[0]: Gist: Erlang is more terse, has better degradation under high load conditions, better reliability. You know, what you might expect against hand-rolled C++ that’s significantly less complex and tested than Erlang’s implementation itself. (See Greenspun’s Tenth Rule, except with the obvious reapplication)

[1]: Yet unfinished. Actually, stalled for some other priorities. The clustering part of it is done, the missing section is writing the appropriate bindings between the Erlang nodes and the Lisp process, as well as a job allocator to decide on how to allocate work to the nodes. We also don’t yet have a lot of machines to run this thing on, a circumstance that may change in coming months. In the off chance that you are interested in contributing to a parallel, clustered knowledge base, let me know in the comments.

[2]: As opposed to full-blown Prolog style unification where everything is in terms of rules. That is, you can say sum(3, 4, A) and conclude A is 7, but you can also ask Prolog sum(A, B, 7), and constantly ask it for legitimate values of A and B, which it’ll happily return for as long as you’d like. This is why a simplistic fixed-size Sodoku solvers in Prolog look just like articulating the rules instead of actually finding the answers.

[4]: An oft cited “benchmark” of sorts showing an Erlang web server, YAWS, vs. Apache, which uses pthreads. Both of these servers are handing a trivial load — a slow “GET” request — so the main determination of who wins here is who is least choked by the massive number of requests. Since Apache uses a pthreads based server it is largely limited by the operating system’s threading implementation.

[5]: Notice the security problem here? Erlang by default will only communicate with other nodes with the same magic cookie, a simple and robust security mechanism to prevent “messages from strangers.” In case you were wondering: message encryption in Erlang is supported in case you don’t trust your link. It’s not as straightforward, but someone has written something about it.

[6]: See OTP Design Principles which discuss supervision trees, monitors, and links, among many other things. Also see Joe Armstrong’s Thesis; it’s easy to read and extremely informative as a perspective on writing reliable software, even if you are not writing Erlang.

[7]: An article written by Armstrong. He links to his thesis, but this is a little bit more conversational and brings out some highlights. I have excerpted the relevant portion for lazy clickers:

Does it work?

Yes. Erlang is used all over the world in high-tech projects where reliability counts. The Erlang flagship project (built by Ericsson, the Swedish telecom company) is the AXD301. This has over 2 million lines of Erlang.

The AXD301 has achieved a NINE nines reliability (yes, you read that right, 99.9999999%). Let’s put this in context: 5 nines is reckoned to be good (5.2 minutes of downtime/year). 7 nines almost unachievable … but we did 9.

Why is this? No shared state, plus a sophisticated error recovery model. You can read all the details in my PhD thesis.

[8]: In case you thought this was a piddly amount of code, a paper pegs the equivalent amount of C/C++ code at somewhere between four to ten times as much code to get the same stuff done. This is not a extraordinary claim considering Erlang’s advantages in automatic memory management and functional programming constructs such as the ever-useful map(). This is a huge win, despite what some people try to tell me…to be explored in a future blog post which I have tentatively named in my head “Verbosity is a valid complaint!,” or something like that.

Written by fdr

July 4, 2007 at 4:33 am

Posted in erlang, languages