<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">
  <title type="text">Snax</title>
  
  <link href="http://blog.evanweaver.com/" />
  
  <updated>2010-08-12T18:14:01Z</updated>
  <author>
    <name>Evan Weaver</name>
    <email>snax@evanweaver.com</email>
  </author>
  <id>http://blog.evanweaver.com/</id>
  <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/snax" /><feedburner:info uri="snax" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><subtitle type="html">Ruby performance.</subtitle><xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" /><entry>
  <title>distributed systems primer, updated
</title>
  <link href="http://feedproxy.google.com/~r/snax/~3/yio_1KP6eXY/distributed-systems-primer-update" />
  <id>http://blog.evanweaver.com/articles/2010/08/12/distributed-systems-primer-update</id>
  
  <updated>2010-08-12T17:03:11Z</updated>
  <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">
      <p>Well, it's been a long time. But! I have four papers to add to my original <a href="http://blog.evanweaver.com/articles/2009/05/04/distributed-systems-primer/">distributed systems primer</a>:</p>

<h2>coordination</h2>
<p style="margin-bottom: 2px;"><a href="http://pagesperso-systeme.lip6.fr/Marc.Shapiro/papers/RR-6956.pdf">CRDTs: Consistency Without Concurrency Control</a>, Mihai Letia, Nuno Preguiça, and Marc Shapiro, 2009.</p>
<p>Guaranteeing eventual consistency by constraining your data structure, rather than adding heavyweight distributed algorithms. <a href="http://github.com/twitter/flockdb">FlockDB</a> works this way.</p>

<h2>partitioning</h2>
<p style="margin-bottom: 2px;"><a href="http://www.cscs.umich.edu/~jmpujol/public/papers/scaling_sn_netdb.pdf">Scaling Online Social Networks Without Pains 
</a>, Josep M. Pujol, Georgos Siganos, Vijay Erramilli, and Pablo Rodriguez, 2010.</p>
<p>Optimally partitioning overlapping graphs through lazy replication. Think of applying this technique at a cluster level, not just a server level.</p><p>There's a better version of this paper titled "The Little Engines That Could"; I'll update the post when it's generally available.</p>

<p style="margin-bottom: 2px;"><a href="http://research.yahoo.com/files/sigmod278-silberstein.pdf">Feeding Frenzy: Selectively Materializing Users' Event Feeds</a>, Adam Silberstein, Jeff Terrace, Brian F. Cooper, and Raghu Ramakrishnan, 2010.</p>
<p>Judicious session management and application of domain knowledge allow for optimal high-velocity mailbox updates in a memory grid. Twitter's timeline system works this way.</p>

<h2>systems integration</h2>
<p style="margin-bottom: 2px;"><a href="http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en/us/archive/papers/dapper-2010-1.pdf">Dapper, a Large-Scale Distributed Systems Tracing Infrastructure</a>, Benjamin H. Sigelman, Luiz André Barroso, Mike Burrows, Pat Stephenson, Manoj Plakal, Donald Beaver, Saul Jaspan, and Chandan Shanbhag, 2010.</p>
<p>Add a transaction-tracking, sampling profiler to a reusable RPC framework and get full stack visibility without performance degradation.</p>

<p>Happy scaling. Make sure to read the <a href="http://blog.evanweaver.com/articles/2009/05/04/distributed-systems-primer/">original post</a> if you haven't.</p>
    <xhtml:img xmlns:xhtml="http://www.w3.org/1999/xhtml" src="http://feeds.feedburner.com/~r/snax/~4/yio_1KP6eXY" height="1" width="1" /></div></content>
<feedburner:origLink>http://blog.evanweaver.com/articles/2010/08/12/distributed-systems-primer-update</feedburner:origLink></entry>

<entry>
  <title>object allocations on the web
</title>
  <link href="http://feedproxy.google.com/~r/snax/~3/gS59gPKbuMg/object-allocations-on-the-web" />
  <id>http://blog.evanweaver.com/articles/2009/10/21/object-allocations-on-the-web</id>
  
  <updated>2009-10-22T11:45:40Z</updated>
  <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">
      <p>How many objects does a Rails request allocate? Here are Twitter's numbers:</p>
<ul>
<li><b>API</b>: 22,700 objects per request</li>
<li><b>Website</b>: 67,500 objects per request </li>
<li><b>Daemons</b>: 27,900 objects per action</li>
</ul>
<p>I want them to be lower. Overall, we burn 20% of our front-end CPU on garbage collection, which seems high. Each process handles ~29,000 requests before getting killed by the memory limit, and the GC is triggered about every 30 requests.</p>
<p>In memory-managed languages, you pay a performance penalty at object allocation time and also at collection time. Since Ruby lacks a generational GC (although there are <a href="http://github.com/authorNari/patch_bag/blob/master/ruby/gc_partial_longlife_r23386.patch">patches</a> available), the collection penalty is linear with the number of objects on the heap.</p>
<h2>a note about structs and immediates</h2>
<p>In Ruby 1.8, <code>Struct</code> instances <a href="http://eigenclass.org/R2/writings/object-size-ruby-ocaml">use fewer bytes</a> and allocate less objects than 
<code>Hash</code> and friends. This can be an optimization opportunity in circumstances where the <code>Struct</code> class is reusable.</p>
 <p>A little bit of code shows the difference (you need <a href="http://www.rubyenterpriseedition.com/">REE</a> or Sylvain Joyeux's <a href="http://rubyforge.org/tracker/download.php/426/1700/11497/2087/ruby-track-alloc.patch">patch</a> to track allocations):</p>
<pre>
GC.enable_stats
def sizeof(obj)
  GC.clear_stats
  obj.clone
  puts "#{GC.num_allocations} allocations"
  GC.clear_stats
  obj.clone
  puts "#{GC.allocated_size} bytes"
end
</pre>
<p>Let's try it:</p>
<pre>
&gt;&gt; Struct.new("Test", :a, :b, :c)
&gt;&gt; struct = Struct::Test.new(1,2,3)
=&gt; #&lt;struct Struct::Test a=1, b=2, c=3&gt;
&gt;&gt; sizeof(struct)
1 allocations
24 bytes

&gt;&gt; hash = {:a =&gt; 1, :b =&gt; 2, :c =&gt; 3}
&gt;&gt; sizeof(hash)
5 allocations
208 bytes
</pre>

<p>Watch out, though. The <code>Struct</code> class itself is expensive:</p>
<pre>
&gt;&gt; sizeof(Struct::Test)
29 allocations
1216 bytes
</pre>
<p>In my understanding, each key in a <code>Hash</code> is a <code>VALUE</code> pointer to another object, while each slot in a <code>Struct</code> is merely a named position.</p>
<p>Immediate types (<code>Fixnum</code>, <code>nil</code>, <code>true</code>, <code>false</code>, and <code>Symbol</code>) don't allocate, except for <code>Symbol</code>. <code>Symbol</code> is interned and keeps its string representations on a special heap that is not garbage-collected.</p>
<h2>your turn</h2>
<p>If you have allocation counts from a production web application, I would be delighted to know them. I am especially interested in Python, PHP, and Java.</p>
<p>Python should be about the same as Ruby. PHP, though, discards the entire heap per-request in some configurations, so collection can be 
dramatically cheaper. And I would expect Java to allocate fewer objects and have a more efficient collection cycle.</p>

    <xhtml:img xmlns:xhtml="http://www.w3.org/1999/xhtml" src="http://feeds.feedburner.com/~r/snax/~4/gS59gPKbuMg" height="1" width="1" /></div></content>
<feedburner:origLink>http://blog.evanweaver.com/articles/2009/10/21/object-allocations-on-the-web</feedburner:origLink></entry>

<entry>
  <title>scribe client
</title>
  <link href="http://feedproxy.google.com/~r/snax/~3/guI6Kxbbd-w/scribe-client-gem" />
  <id>http://blog.evanweaver.com/articles/2009/09/30/scribe-client-gem</id>
  
  <updated>2009-09-30T18:48:08Z</updated>
  <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">
      <p>I've released Scribe 0.1, a Ruby client for the <a href="http://sourceforge.net/apps/mediawiki/scribeserver/index.php?title=Main_Page">Scribe</a> 
remote log server.</p>
<pre>sudo gem install scribe</pre>
<p>Usage is simple:</p>
<pre>
client = Scribe.new
client.log("I'm lonely in a crowded room.", "Rails")
</pre>
<p>Documentation is <a href="http://blog.evanweaver.com/files/doc/fauna/scribe/files/README.html">here</a>.</p>
<h2>about scribe</h2>
<p>The primary benefit of Scribe over something like <a href="http://www.balabit.com/network-security/syslog-ng/">syslog-ng</a> is 
increased scalability, because of Scribe's fundamentally distributed architecture. Scribe also does away with the legacy 
<code>syslog</code>
alert levels, and lets you define more application-appropriate categories on the fly instead.</p>
<p>Dmytro Shteflyuk has <a href="http://kpumuk.info/development/installing-and-using-scribe-with-ruby-on-mac-os/">good article</a> about installing the Scribe 
server itself on OS X. It would be nice if someone would put it in MacPorts, but it may be blocked on the 
release of Thrift.</p>

    <xhtml:img xmlns:xhtml="http://www.w3.org/1999/xhtml" src="http://feeds.feedburner.com/~r/snax/~4/guI6Kxbbd-w" height="1" width="1" /></div></content>
<feedburner:origLink>http://blog.evanweaver.com/articles/2009/09/30/scribe-client-gem</feedburner:origLink></entry>

<entry>
  <title>ree
</title>
  <link href="http://feedproxy.google.com/~r/snax/~3/lx_GBmUVBMk/ree" />
  <id>http://blog.evanweaver.com/articles/2009/09/24/ree</id>
  
  <updated>2009-09-24T07:32:08Z</updated>
  <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">
      <p>We recently migrated Twitter from a custom Ruby 1.8.6 build to a <a href="http://www.rubyenterpriseedition.com/">Ruby Enterprise Edition</a> release candidate, courtesy of <a href="http://www.phusion.nl/">Phusion</a>. Our primary motivation was the integration of Brent's <a href="http://github.com/brentr/matzruby/tree/v1_8_7_72-mbari">MBARI patches</a>, which increase memory stability.</p>
<p>Some features of REE have no effect on our codebase, but we definitely benefit from the MBARI patchset, the Railsbench tunable GC, and the various leak fixes in 1.8.7p174. These are difficult to integrate and Phusion has done a fine job.</p>
<h2>testing notes</h2>
<p>I ran into an interesting issue. Ruby is faster if compiled with <code>-Os</code> (optimize for size) than with <code>-O2</code> or <code>-O3</code> (optimize for speed). Hongli pointed out that Ruby has poor instruction locality and benefits most from squeezing tightly into the instruction cache. This is an unusual phenomenon, although probably more common in interpreters and virtual machines than in "standard" C programs.</p>
<p>I also tested a build that included Joe Damato's <a href="http://timetobleed.com/fixing-threads-in-ruby-18-a-2-10x-performance-boost/">heaped thread frames</a>, but it would hang Mongrel in <code>rb_thread_schedule()</code> after the first GC run, which is not exactly what we want. Hopefully this can be integrated later.</p>
<h2>benchmarks</h2>
<p>I ran a suite of benchmarks via <a href="http://www.xenoclast.org/autobench/">Autobench/httperf</a> and plotted them with <a href="http://plot.micw.eu/">Plot</a>. The hardware was a 4-core Xeon machine with RHEL5, running 8 Mongrels balanced behind Apache 2.2. I made a typical API request that is answered primarily from composed caches.</p>
<div style="margin: 0; padding: 0;"><img src="http://blog.evanweaver.com/files/ree_benchmark.png" /></div>
<p>As usual, we see that <a href="http://blog.evanweaver.com/articles/2009/04/09/ruby-gc-tuning/">tuning the GC parameters</a> has the greatest impact on throughput, but there is a definite gain from switching to the REE bundle. It's also interesting how much the standard deviation is improved by the GC settings. (Some data points are skipped due to errors at high concurrency.)</p>
<h2>upgrading</h2>
<p>Moving from 1.8.6 to REE 1.8.7 was trivial, but moving to 1.9 will be more of an ordeal. It will be interesting to see what patches are still necessary on 1.9. Many of them are getting upstreamed, but some things (such as <a href="http://goog-perftools.sourceforge.net/doc/tcmalloc.html">tcmalloc</a>) will probably remain only available from 3rd parties.</p>
<p>All in all, good times in MRI land.</p>
    <xhtml:img xmlns:xhtml="http://www.w3.org/1999/xhtml" src="http://feeds.feedburner.com/~r/snax/~4/lx_GBmUVBMk" height="1" width="1" /></div></content>
<feedburner:origLink>http://blog.evanweaver.com/articles/2009/09/24/ree</feedburner:origLink></entry>

<entry>
  <title>memcached gem release
</title>
  <link href="http://feedproxy.google.com/~r/snax/~3/WOuAla7TWi8/memcached-gem-release" />
  <id>http://blog.evanweaver.com/articles/2009/08/04/memcached-gem-release</id>
  
  <updated>2009-08-05T02:10:03Z</updated>
  <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">
      <p>One of the hardest gems to install is no more. It's now easy to install!</p>
<p><a href="http://blog.evanweaver.com/files/doc/fauna/memcached">Memcached 0.15</a> features:</p>
<ul>
<li>Update to libmemcached 0.31.1</li>
<li>Bundle libmemcached itself with the gem (<a href="http://github.com/antifuchs">antifuchs</a>)</li>
<li>UDP connection support</li>
<li>Unix domain socket support (<a href="http://github.com/hellvinz/">hellvinz</a>)</li>
<li><code>AUTO_EJECT_HOSTS</code> bugfixes (<a href="http://github.com/mattknox">mattknox</a>)</li>
</ul>
<p>Install with <code>gem install memcached</code>. Since <a href="http://tangent.org/552/libmemcached.html">libmemcached</a> is bundled in, there are no longer any dependencies.</p>

<h2>on coordination</h2>

<p><a href="http://github.com/antifuchs">Andreas Fuchs</a> suggested several months ago that I include libmemcached itself in the gem, but at the time I resisted. I was wrong.</p>

<p>My opposition was based on the idea that libmemcached itself would be an integration point, so running multiple versions on a system would be bad.</p>

<p>In real life, the hash algorithm became the integration point, not the library itself. And since the library's ABI kept changing, the gem always required a very specific custom build. This annoyed the public and caused extra work for my operations team, who had to make sure to upgrade both the library and the gem at the same time.</p>

<p>Updates can come thick and fast now because I don't have to worry about publishing custom builds or waiting for the libmemcached developers to merge my patches.</p>

<p>In retrospect it seems obvious—it's always a win to remove coordination from a system.</p>

<h2>linker woes</h2>

<p>Unfortunately, it was easier to make that decision than it was to implement it. Linux and OS X link libraries differently, and I had a lot of trouble making sure that no system-installed version of libmemcached would get linked, instead of the custom one built during <code>gem install</code>.</p>

<p>When you link a shared object, OS X seems to maintain a reference to the original <code>.dylib</code>. Linux does not, and depends on ldconfig and <code>LD_LIBRARY_PRELOAD</code> to find the object at runtime. Since you can't modify the shell environment from within a running process, there's no way to override <code>LD_LIBRARY_PRELOAD</code>, so I needed to statically link libmemcached into the gem's own <code>.so</code> or <code>.bundle</code>.</p>

<p>The only way I could do this on both systems was to configure libmemcached with <code>CFLAGS=-fPIC --disable-shared</code>, rename the <code>libemcached.*</code> static object files to <code>libemcached_gem.*</code>, and pass <code>-lmemcached_gem</code> to the linker rather than <code>-lmemcached</code>. Otherwise the linker would prefer the system-installed dynamic objects, even with the correct paths and <code>-static</code> option set.</p>

<p>Note that you can check what objects a binary has linked to via <code>otool -F</code> on OS X, and <code>ldd</code> on Linux.</p>

<p>Feel free to look at the <a href="http://github.com/fauna/memcached/blob/6f2c517df97a5a6c871802d93ef56fdb4358c22c/ext/extconf.rb">extconf.rb source</a> and let me know if there's a better way to do this.</p>


    <xhtml:img xmlns:xhtml="http://www.w3.org/1999/xhtml" src="http://feeds.feedburner.com/~r/snax/~4/WOuAla7TWi8" height="1" width="1" /></div></content>
<feedburner:origLink>http://blog.evanweaver.com/articles/2009/08/04/memcached-gem-release</feedburner:origLink></entry>

<entry>
  <title>up and running with cassandra
</title>
  <link href="http://feedproxy.google.com/~r/snax/~3/Ze91Rolb7x4/up-and-running-with-cassandra" />
  <id>http://blog.evanweaver.com/articles/2009/07/06/up-and-running-with-cassandra</id>
  
  <updated>2010-08-12T18:45:49Z</updated>
  <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">
      <p><a href="http://wiki.apache.org/cassandra/">Cassandra</a> is a hybrid non-relational database in the same class as Google's BigTable. It is more featureful 
than a key/value store like <a href="http://www.basho.com/Riak.html">Riak</a>, but supports fewer query types than a document store like <a href="http://www.mongodb.org">MongoDB</a>.</p>

<p>Cassandra was started by Facebook and later transferred to the open-source community. It is an ideal runtime database for web-scale domains like social networks.</p>

<p>This post is both a tutorial and a "getting started" overview. You will learn about Cassandra's features, data model, API, and operational requirements—everything you need to know to deploy a Cassandra-backed service.</p>

<p><b>May 11, 2010</b>: post updated for Cassandra gem 0.8 and Cassandra version 0.6.</p>

<h2>features</h2>

<p>There are a number of reasons to choose Cassandra for your website. Compared to other databases, three big features stand out:</p>

<ul>
<li><b>Flexible schema</b>: with Cassandra, like a document store, you don't have to decide what fields you need in your records ahead of time. You can add and remove arbitrary fields on the fly. This is an incredible productivity boost, especially in large deployments.</li>
<li><b>True scalability</b>: Cassandra scales horizontally in the purest sense. To add more capacity to a cluster, turn on another machine. You don't have restart any processes, change your application queries, or manually relocate any data.</li>
<li><b>Multi-datacenter awareness</b>: you can adjust your node layout to ensure that if one datacenter burns in a fire, an alternative datacenter will have at least one full copy of every record.</li>
  </ul>

<p>Some other features that help put Cassandra above the competition
:</p>

<ul>
<li><b>Range queries</b>: unlike most key/value stores, you can query for ordered ranges of keys.</li>
<li><b>List datastructures</b>: super columns add a 5th dimension to the hybrid model, turning columns into lists. This is very handy for things like per-user indexes.</li>
<li><b>Distributed writes</b>: you can read and write any data to anywhere in the cluster at any time. There is never any single point of failure.</li>
</ul>

<h2>installation</h2>

<p>You need a Unix system. If you are using Mac OS 10.5, all you need is Git. Otherwise, you need to install Java 1.6, Git 1.6, Ruby, and Rubygems in some reasonable way.</p>

<p>Start a terminal and run:</p>
<pre>
sudo gem install cassandra
</pre>

<p>If you are using Mac OS, you need to export the following environment variables:</p>
<pre>
export JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home"
export PATH="/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin:$PATH"
</pre>

<p>Now you can build and start a test server with <code>cassandra_helper</code>:</p>
<pre>
cassandra_helper cassandra
</pre>

<p>It runs!</p>

<h2>live demo</h2>

<p>The above script boots the server with a schema that we can interact with. Open another terminal window and start <code>irb</code>, the Ruby shell:</p>
<pre>
irb
</pre>

<p>In the <code>irb</code> prompt, require the library:</p>
<pre>
require 'rubygems'
require 'cassandra'
include SimpleUUID
</pre>

<p>Now instantiate a client object:</p>
<pre>
twitter = Cassandra.new('Twitter')
</pre>

<p>Let's insert a few things:</p>
<pre>
user = {'screen_name' =&gt; 'buttonscat'}
twitter.insert(:Users, '5', user)  

tweet1 = {'text' =&gt; 'Nom nom nom nom nom.', 'user_id' =&gt; '5'}
twitter.insert(:Statuses, '1', tweet1)

tweet2 = {'text' =&gt; '@evan Zzzz....', 'user_id' =&gt; '5', 'reply_to_id' =&gt; '8'}
twitter.insert(:Statuses, '2', tweet2)
</pre>

<p>Notice that the two status records do not have all the same columns. Let's go ahead and connect them to our user record:</p>
<pre>
twitter.insert(:UserRelationships, '5', {'user_timeline' =&gt; {UUID.new =&gt; '1'}})
twitter.insert(:UserRelationships, '5', {'user_timeline' =&gt; {UUID.new =&gt; '2'}})
</pre>

<p>The <code>UUID.new</code> call creates a collation key based on the current time; our tweet ids are stored in the values.</p>

<p>Now we can query our user's tweets:</p>
<pre>
timeline = twitter.get(:UserRelationships, '5', 'user_timeline', :reversed =&gt; true)
timeline.map { |time, id| twitter.get(:Statuses, id, 'text') }
# =&gt; ["@evan Zzzz....", "Nom nom nom nom nom."]
</pre>

<p>Two tweet bodies, returned in recency order—not bad at all. In a similar fashion, each time a user tweets, we could loop through their followers and insert the status key into their follower's <code>home_timeline</code> relationship, for handling general status delivery.</p>

<h2>the data model</h2>

<p>Cassandra is best thought of as a 4 or 5 dimensional hash. The usual way to refer to a piece of data is as follows: a <b>keyspace</b>, a <b>column family</b>, a <b>key</b>, an <i>optional</i> <b>super column</b>, and a <b>column</b>. At the end of that chain lies a single, lonely value.</p>

<p>Let's break down what these layers mean.</p>

<ul>
<li><p><b>Keyspace</b> (also confusingly called "table"): the outer-most level of organization. This is usually the name of the application. For example, <code>'Twitter'</code> and <code>'Wordpress'</code> are both good keyspaces. Keyspaces must be defined at startup in the <code>storage-conf.xml</code> file.</p></li>

<li><p><b>Column family</b>: a slice of data corresponding to a particular key. Each column family is stored in a separate file on disk, so it can be useful to put frequently accessed data in one column family, and rarely accessed data in another. Some good column family names might be <code>:Posts</code>, <code>:Users</code> and <code>:UserAudits</code>. Column families must be defined at startup.</p></li>

<li><p><b>Key</b>: the permanent name of the record. You can query over ranges of keys in a column family, like <code>:start =&gt; '10050', :finish =&gt; '10070'</code>—this is the only index Cassandra provides for free. Keys are defined on the fly.</p></li>
</ul>

<p>After the column family level, the organization can diverge—this is a feature unique to Cassandra. You can choose either:</p>

<ul>
<li><p>A <b>column</b>: this is a tuple with a name and a value. Good columns might be <code>'screen_name' =&gt; 'lisa4718'</code> or <code>'Google' =&gt; 'http://google.com'</code>.</p>

<p>It is common to not specify a particular column name when requesting a key; the response will then be an ordered hash of all columns. For example, querying for <code>(:Users, '174927')</code> might return:</p>
<pre>
{'name' =&gt; 'Lisa Jones', 
 'gender' =&gt; 'f', 
 'screen_name' =&gt; 'lisa4718'}
</pre>

<p>In this case, <code>name</code>, <code>gender</code>, and <code>screen_name</code> are all column names. Columns are defined on the fly, and different records can have different sets of column names, even in the same keyspace and column family. This lets you use the column name itself as either <b>structure</b> or <b>data</b>. Columns can be stored in recency order, or alphabetical by name, and all columns keep a timestamp.</p></li>

<li><p>A <b>super column</b>: this is a named list. It contains standard columns, stored in recency order.</p>

<p>Say Lisa Jones has bookmarks in several categories. Querying <code>(:UserBookmarks, '174927')</code> might return:</p>
<pre>
{'work' =&gt; {
    'Google' =&gt; 'http://google.com', 
    'IBM' =&gt; 'http://ibm.com'}, 
 'todo': {...}, 
 'cooking': {...}}
</pre>

<p>Here, <code>work</code>, <code>todo</code>, and <code>cooking</code> are all super column names. They are defined on the fly, and there can be any number of them per row. <code>:UserBookmarks</code> is the name of the <b>super column family</b>. Super columns are stored in alphabetical order, with their sub columns physically adjacent on the disk.</p></li>
</ul>

<p>Super columns and standard columns cannot be mixed at the same (4th) level of dimensionality. You must define at startup which column families contain standard columns, and which contain super columns with standard columns inside them.</p>

<p>Super columns are a great way to store one-to-many indexes to other records: make the sub column names TimeUUIDs (or whatever you'd like to use to sort the index), and have the values be the foreign key. We saw an example of this strategy in the demo, above.</p>

<p>If this is confusing, don't worry. We'll now look at two example schemas in depth.</p>

<h2>twitter schema</h2>

<p>Here is the schema definition we used for the demo, above. It is based on Eric Florenzano's <a href="http://github.com/ericflo/twissandra/tree/master">Twissandra</a>:</p>
<pre>
&lt;Keyspace Name="Twitter"&gt;
  &lt;ColumnFamily CompareWith="UTF8Type" Name="Statuses" /&gt;
  &lt;ColumnFamily CompareWith="UTF8Type" Name="StatusAudits" /&gt;
  &lt;ColumnFamily CompareWith="UTF8Type" Name="StatusRelationships"
    CompareSubcolumnsWith="TimeUUIDType" ColumnType="Super" /&gt;  
  &lt;ColumnFamily CompareWith="UTF8Type" Name="Users" /&gt;
  &lt;ColumnFamily CompareWith="UTF8Type" Name="UserRelationships"
    CompareSubcolumnsWith="TimeUUIDType" ColumnType="Super" /&gt;
&lt;/Keyspace&gt;
</pre>

<p>What could be in <code>StatusRelationships</code>? Maybe a list of users who favorited the tweet? Having a super column family for both record types lets us index each direction of whatever many-to-many relationships we come up with.</p>

<p>Here's how the data is organized:</p>

<div style="text-align: center; margin-bottom: 10px;"><a href="http://blog.evanweaver.com/files/cassandra/twitter.jpg"><img src="http://blog.evanweaver.com/files/cassandra/twitter_small.jpg" alt="Click to enlarge" /></a></div>

<p>Cassandra lets you distribute the keys across the cluster either randomly, or in order, via the <code>Partitioner</code> option in the <code>storage-conf.xml</code> file.</p>

<p>For the Twitter application, if we were using the order-preserving partitioner, all recent statuses would be stored on the same node. This would cause hotspots. Instead, we should use the random partitioner.</p><p>Alternatively, we could preface the status keys with the user key, which has less temporal locality. If we used <code>user_id:status_id</code> as the status key, we could do range queries on the user fragment to get tweets-by-user, avoiding the need for a <code>user_timeline</code> super column.</p>

<h2>multi-blog schema</h2>

<p>Here's a another schema, suggested to me by <a href="http://spyced.blogspot.com/">Jonathan Ellis</a>, the primary Cassandra maintainer. It's for a multi-tenancy blog platform:</p>
<pre>
&lt;Keyspace Name="Multiblog"&gt;      
  &lt;ColumnFamily CompareWith="TimeUUIDType" Name="Blogs" /&gt;
  &lt;ColumnFamily CompareWith="TimeUUIDType" Name="Comments"/&gt;
&lt;/Keyspace&gt;
</pre>

<p>Imagine we have a blog named 'The Cutest Kittens'. We will insert a row when the first post is made as follows:</p>
<pre>
require 'rubygems'
require 'cassandra'
include SimpleUUID

multiblog = Cassandra.new('Multiblog')

multiblog.insert(:Blogs, 'The Cutest Kittens',
  { UUID.new =&gt; 
    '{"title":"Say Hello to Buttons Cat","body":"Buttons is a cute cat."}' })
</pre>

<p><code>UUID.new</code> generates a unique, sortable column name, and the JSON hash contains the post details. Let's insert another:</p>
<pre>
multiblog.insert(:Blogs, 'The Cutest Kittens',
  { UUID.new =&gt; 
    '{"title":"Introducing Commie Cat","body":"Commie is also a cute cat"}' })
</pre>

<p>Now we can find the latest post with the following query:</p>
<pre>
post = multiblog.get(:Blogs, 'The Cutest Kittens', :reversed =&gt; true).to_a.first
</pre>

<p>On our website, we can build links based on the readable representation of the UUID:</p>
<pre>
guid = post.first.to_guid
# =&gt; "b06e80b0-8c61-11de-8287-c1fa647fd821"
</pre>

<p>If the user clicks this string in a permalink, our app can find the post directly via:</p>
<pre>
multiblog.get(:Blogs, 'The Cutest Kittens', :start =&gt; UUID.new(guid), :count =&gt; 1)
</pre>

<p>For comments, we'll use the post UUID as the outermost key:</p>
<pre>
multiblog.insert(:Comments, guid,
  {UUID.new =&gt; 'I like this cat. - Evan'})
multiblog.insert(:Comments, guid, 
  {UUID.new =&gt; 'I am cuter. - Buttons'})
</pre>

<p>Now we can get all comments (oldest first) for a post by calling:</p>
<pre>
multiblog.get(:Comments, guid)
</pre>

<p>We could paginate them by passing <code>:start</code> with a UUID. See <a href="http://www.slideshare.net/Eweaver/efficient-pagination-using-mysql">this presentation</a> to learn more about token-based pagination.</p>

<p>We have sidestepped two problems with this data model: we don't have to maintain separate indexes for any lookups, and the posts and comments are stored in separate files, where they don't cause as much write contention. Note that we didn't need to use any super columns, either.</p>

<h2>storage layout and api comparison</h2>

<p>The storage strategy for Cassandra's standard model is the same as BigTable's. Here's a comparison chart:</p>

<table class="tt">
  <tr><th /><th colspan="2">multi-file</th><th>per-file</th><th colspan="4" class="tt_right">intra-file</th></tr>
  <tr><th>Relational</th><td>server</td><td>database</td><td>table*</td><td>primary key</td><td>column value</td><td /><td class="tt_right" /></tr>
  <tr><th>BigTable</th><td>cluster</td><td>table</td><td>column family</td><td>key</td><td>column name</td><td>column value</td><td class="tt_right" /></tr>
  <tr><th>Cassandra, standard model</th><td>cluster</td><td>keyspace</td><td>column family</td><td>key</td><td>column name</td><td>column value</td><td class="tt_right" /></tr>
  <tr><th class="tt_footer">Cassandra, super column model</th><td class="tt_footer">cluster</td><td class="tt_footer">keyspace</td><td class="tt_footer">column family</td><td class="tt_footer">key</td><td class="tt_footer">super column name</td><td class="tt_footer">column name</td><td class="tt_footer tt_right">column value</td></tr>
</table>

<p style="font-size: 12px; text-align: right; margin-top: 0px;">* With fixed column names.</p>

<p>Column families are stored in <b>column-major</b> order, which is why people call BigTable a column-oriented database. This is not the same as a 
column-oriented OLAP database like Sybase IQ—it depends on whether your data model considers keys to span column families or not.</p>

<div style="text-align: center;"><a href="http://blog.evanweaver.com/files/cassandra/row_oriented.jpg"><img src="http://blog.evanweaver.com/files/cassandra/row_oriented_small.jpg" alt="Click to enlarge" /></a></div>

<p>In row-orientation, the column names are the <b>structure</b>, and you think of the column families as <b>containing keys</b>. This is the convention in relational databases.</p>

<div style="text-align: center;"><a href="http://blog.evanweaver.com/files/cassandra/column_oriented.jpg"><img src="http://blog.evanweaver.com/files/cassandra/column_oriented_small.jpg" alt="Click to enlarge" /></a></div>

<p>In column-orientation, the column names are the <b>data</b>, and the column families are the structure. You think of the key as <b>containing the column family</b>, which is the convention in BigTable. (In Cassandra, super columns are also stored in column-major order—all the sub columns are together.)</p>

<p>In Cassandra's Ruby API, parameters are expressed in storage order, for clarity:</p>

<table class="tt">
  <tr><th>Relational</th><td class="tt_right"><code>SELECT `column` FROM `database`.`table` WHERE `id` = key;</code></td></tr>
  <tr><th>BigTable</th><td class="tt_right"><code>table.get(key, "column_family:column")</code></td></tr>
  <tr><th>Cassandra: standard model</th><td class="tt_right"><code>keyspace.get("column_family", key, "column")</code></td></tr>
  <tr><th class="tt_footer">Cassandra: super column model</th><td class="tt_footer tt_right"><code>keyspace.get("column_family", key, "super_column", "column")</code></td></tr>
</table>

<p>Note that Cassandra's internal Thrift interface mimics BigTable in some ways, but this is being changed.</p>

<h2>going to production</h2>

<p>Cassandra is an alpha product and could, theoretically, lose your data. In particular, if you change the schema specified in the <code>storage-conf.xml</code> file, you must follow <a href="https://issues.apache.org/jira/browse/CASSANDRA-44">these instructions</a> carefully, or corruption will occur (this is going to be fixed). Also, the on-disk storage format is subject to change, making upgrading a bit difficult.</p>

<p>The biggest deployment is at Facebook, where hundreds of terabytes of token indexes are kept in about a hundred Cassandra nodes. However, their use case 
allows the data to be rebuilt if something goes wrong. Proceed carefully, keep a backup in an <a href="http://mashable.com/2009/01/30/magnolia-data-loss/">unrelated storage engine</a>...and submit patches if things go wrong. (Some other production 
deployments are listed <a href="http://www.dbms2.com/2010/07/06/riptano-and-cassandra-adoption/">here</a>.)</p>

<p>That aside, here is a guide for deploying a production cluster:</p> 

<ul>
<li><p><b>Hardware</b>: get a handful of commodity Linux servers. 16GB memory is good; Cassandra likes a big filesystem buffer. You don't need RAID. If you put the commitlog file and the data files on separate physical disks, things will go faster. Don't use EC2 or friends without being aware that the virtualized I/O can be slow, especially on the small instances.</p></li>

<li><p><b>Configuration</b>: in the <code>storage-conf.xml</code> schema file, set the replication factor to 3. List the IP address of one of the nodes as the seed. Set the listen address to the empty string, so the hosts will resolve their own IPs. Now, adjust the contents of <code>cassandra.in.sh</code> for your various paths and JVM options—for a 16GB node, set the JVM heap to 4GB.</p></li>

<li><p><b>Deployment</b>: build a package of Cassandra itself and your configuration files, and deliver it to all your servers (I use <a href="http://en.wikipedia.org/wiki/Capistrano">Capistrano</a> for this). Start the servers by setting <code>CASSANDRA_INCLUDE</code> in the environment to point to your <code>cassandra.in.sh</code> file, and run <code>bin/cassandra</code>. At this point, you should see join notices in the Cassandra logs:</p>
<pre>
Cassandra starting up...
Node 10.224.17.13:7001 has now joined.
Node 10.224.17.14:7001 has now joined.
</pre>
<p>Congratulations! You have a cluster. Don't forget to turn off debug logging in the <code>log4j.properties</code> file.</p></li>

<li><p><b>Visibility</b>: you can get a little more information about your cluster via the tool <code>bin/nodeprobe</code>, included:</p>
<pre>
$ bin/nodeprobe --host 10.224.17.13 ring
Token(124007023942663924846758258675932114665)  3 10.224.17.13  |&lt;--|
Token(106858063638814585506848525974047690568)  3 10.224.17.19  |   ^
Token(141130545721235451315477340120224986045)  3 10.224.17.14  |--&gt;|
</pre>

<p>Cassandra also exposes various statistics over <a href="http://en.wikipedia.org/wiki/Java_Management_Extensions">JMX</a>.</p></li>
</ul>

<p>Note that your client machines (not servers!) must have accurate clocks for Cassandra to resolve write conflicts properly. Use <a href="http://en.wikipedia.org/wiki/Network_Time_Protocol">NTP</a>.</p>

<h2>conclusion</h2>

<p>There is a misperception that if someone advocates a non-relational database, they either don't understand SQL optimization, or they are generally a hater. This is not the case.</p>

<p>It is reasonable to seek a new tool for a new problem, and database problems have changed with the rise of web-scale distributed systems. This does not mean that SQL as a general-purpose runtime and reporting tool is going away. However, at web-scale, it is more flexible to separate the concerns. Runtime object lookups can be handled by a low-latency, strict, self-managed system like Cassandra. Asynchronous analytics and reporting can be handled by a high-latency, flexible, un-managed system like <a href="http://hadoop.apache.org/core/">Hadoop</a>. And in neither case does SQL lend itself to sharding.</p>

<p>I think that Cassandra is the most promising current implementation of a runtime distributed database, but much work remains to be done. We're beginning to use Cassandra at Twitter, and here's what I would like to happen real-soon-now:</p>
<ul>
<li><b>Interface cleanup</b>: <span style="text-decoration: line-through;">the Thrift API for Cassandra is incomplete and inconsistent, which makes writing 
clients very irritating.</span><br />Done!</li>
<li><b>Online migrations</b>: restarting the cluster 3 times to add a column family is silly.</li>
<li><b>ActiveModel or DataMapper adapter</b>: <span style="text-decoration: line-through;">for interaction with business objects in Ruby.</span><br />Done! 
Michael 
Koziarski on the Rails core team wrote an <a href="http://github.com/NZKoz/cassandra_object">ActiveModel adapter</a>.</li>
<li><b>Scala client</b>: for interoperability with JVM middleware.</li>
</ul>

<p>Go ahead and jump on any of those projects—it's a chance to get in on the ground floor.</p>

<p>Cassandra has excellent performance. There some benchmark results for version 0.5 at the end of the <a href="http://www.brianfrankcooper.net/pubs/ycsb-v4.pdf"> Yahoo performance study</a>.</p>

<h2>further resources</h2>

<ul>
<li><a href="http://wiki.apache.org/cassandra/">Cassandra wiki</a></li>
<li>Presentation by Avinash Lakshman about Cassandra: <a href="http://www.slideshare.net/Eweaver/cassandra-presentation-at-nosql">slides</a>, <a href="http://vimeo.com/5185526">video</a></li>
<li>The <a href="http://mail-archives.apache.org/mod_mbox/incubator-cassandra-user/">cassandra-user</a> and <a href="http://mail-archives.apache.org/mod_mbox/incubator-cassandra-user/">cassandra-dev</a> mailing lists</li>
<li>The #cassandra IRC channel on <a href="irc://irc.freenode.net/cassandra">irc.freenode.net</a></li>
<li>Cassandra's <a href="http://issues.apache.org/jira/browse/CASSANDRA">bug tracker</a></li>
<li>Twitter's Ruby client: <a href="http://blog.evanweaver.com/files/doc/fauna/cassandra_client">docs</a>, <a href="http://github.com/fauna/cassandra_client/">source</a></li>
<!--<li>Matt Revelle's <a href="http://github.com/mattrepl/clojure-cassandra/tree/master">Clojure client</a></li>-->
</ul>

    <xhtml:img xmlns:xhtml="http://www.w3.org/1999/xhtml" src="http://feeds.feedburner.com/~r/snax/~4/Ze91Rolb7x4" height="1" width="1" /></div></content>
<feedburner:origLink>http://blog.evanweaver.com/articles/2009/07/06/up-and-running-with-cassandra</feedburner:origLink></entry>

 
</feed>
