CouchDB and the web

This is my presentation from JavaZone 2010

Note that during my presentation, I showed the view section and basic replication directly in Futon instead of showing the fallback in the slides. What I did show was mostly the same, but naturally I showed some variations on the mappers as well.


Feature prioritization for Pillow the CouchDB shard manager

I have now reached the end of my todo list for Pillow. That doesn’t mean it’s finished and ready to be stamped version 1.0. In it’s current incarnation it is fully usable and production ready, but in order to earn a 1.0 it needs to do a bit more.

The current resharding always doubles the number of servers required. Since you may overshard, that doesn’t necessarily mean you have to double the number of physical servers, but you need to organize more CouchDB instances than you might otherwise need. Smoother sharding algorithms that enable addition of single additional servers exist (consistent hashing) so Pillow should support this.

Pillow currently only supports rereducers written in Erlang. It would really be nice to support JavaScript for rereducers. A summing rereducer exists and mappers without reducers works just like in CouchDB. However when you have more complex reduction needs, copying the reducer code from your CouchDB into Pillow beats writing (and maintaining) them again in a new language.

Pillow should really support the bulk document API of CouchDB. I haven’t used this one myself, but adding support should be pretty straightforward.

CouchApp support is harder since it requires JavaScript support and then some. I probably need to play around with a CouchApp or two to find out more, but since I haven’t done so, it’s hard to determine how much work it would take.

While I do hope that there are no non-replicated CouchDB servers in production out there, reality is that there probably are lots. I like the three-way replication minimum myself and with CouchDB’s master-master scheme, it works really well. Pillow however is currently happily ignorant of any replication you have set up. I would really like to have Pillow manage such replication. In addition to managing replication, sets of Pillow servers should be controllable from a random server in the same master-master way ensuring full control of your cluster from any single Pillow node.

There is no clear prioritized list right now, all features listed above (and probably more) would be beneficial. However, as I am currently the only one developing Pillow and the time I can spend on Pillow is limited, I have to prioritize. The five features can be grouped:

  • CouchDB API compatibility: JavaScript views, bulk documents, CouchApp
  • Production flexibility and scaling: Consistent Hashing and Replication management

It is not hard to admit that API compatibility is important, but the core of the API is supported. Production flexibility and scaling is more important for me at the moment and I will probably focus on that. I also think that replication management is slightly more useful than consistent hashing. Choosing between the API features is harder since I don’t need them myself, but JavaScript views is a prerequisite of CouchApp and bulk document support is straightforward in comparison to CouchApp leading to this priority list:

  1. Replication management
  2. Consistent hashing
  3. JavaScript views
  4. Bulk documents
  5. CouchApp

This list is the result of my needs at the time of writing. Others may convince me to adjust the priorities. Better yet, others may jump in and add support for the features they need.


Pillow, the CouchDB shard manager

If there is one thing that has bothered me about my choice of CouchDB as the main storage system for Sincerial, it’s the lack of an automatic system for shard management. In the early days of a startup, a single server is probably capable of handling all the necessary data. However, a successful service that is built around the harvesting and analysis of data will sooner or later have to shard the dataset across multiple servers. And for a new service, the sooner you have to start sharding, the better. Several good distributed storage systems exist. Google’s original bigtable, HBase (Hadoop’s bigtable equivalent), Cassandra and more solve this particular problem, but there is more to choosing and running a storage system than just data volume scaling. CouchDB has other strengths that made it a good choice for our application, but that is not the topic of this post.

CouchDB-lounge originally written by Kevin Ferguson (macfergus), Vijay Ragunathan (lukatmyshu) and Shaun Lindsay (srlindsay) at Meebo.com will handle distribution of requests to the right servers in a cluster of servers, but you still have to handle resharding or repartitioning manually. CouchDB-lounge consists of two components, dumbproxy handling reading and writing of documents and smartproxy handling views. These require Nginx and Twisted (a Python framework) respectively. If you overshard appropriately, you can scale your data volume a long way before you have to start resharding.

While manually repartitioning a CouchDB database is doable, I’d rather have an automatic way of doing it since I don’t want to make mistakes. In addition, the Sincerial system uses Ruby running with Phusion Passenger in Apache and I didn’t want to add two more frameworks on top of that. This might sound like a not-invented here excuse, but it isn’t or at least I don’t think it is.

When I started developing Pillow, I chose to do so in erlang to match couchdb. The reason was two-fold. First of all I was curious about erlang and I like functional programming. Secondly, CouchDB was written in erlang and there had to be a reason for that. Now I’ve released version 0.3 of Pillow. This version supports automatic resharding, routing of requests to the right shard and views. Reducers need to be written in erlang, but a summing reducer is in place and mappers without reducers are supported out of the box. As such, this version of Pillow has all the functionality I set out to develop, but it does not support the full CouchDB API.

The bulk document API is not supported. And I haven’t tried running standalone CouchApps. The reason being that I am focusing on our needs. I intend to have full support of the CouchDB API eventually, but it might be that I integrate more tightly with CouchDB and use CouchDB as a library to make this happen. This will make supporting javascript reducers easier as well. It would of course be interesting to have Pillow become an integral part of CouchDB as well providing one can still access each CouchDB server directly for maintenance purposes. The latter being one of the reasons I’m in general a bit sceptical to distributed systems that hide the inner workings since often hard to fix problems that may occur.


CouchDB Replication Monitor

CouchDB does replication, but replication needs to be set up after each server restart. This means you need to ensure that replication is restarted whenever the daemon restarts CouchDB. I have never seen replication stop working without a restart, but I prefer being safe to being sorry about replication. To be perfectly honest, I do not trust that my replication initiation after a soft CouchDB restart works properly either so I prefer to monitor the replication and have a safety mechanism in place to restart replication if needed.

There are several ways to monitor replication. You could fetch the status page of all servers and restart replication on servers with an empty page, but that is a kind of brute force approach in my world. A better solution is to use the replication itself to monitor that it works.

Each server updates their timestamp in CouchDB and this is again replicated to the other servers. This gets us a bit of the way, but not all the way. The server you are checking might have received updates from all the other servers, but you don’t know if it’s pushed out anything to the other servers. To solve this, you can add information about the other servers to the local server as well. This will give you a matrix of server replication status.

For each server, you will see the timestamp replicated from the server and a list of timestamps replicated to that server. The latter often being a generation older than the former. Cron can be used to update this data. The cronjob reads all the server timestamps and updates this servers timestamp followed by a list of the other servers timestamp.

A mapper to get a server id to server status out of the db.

map: function(doc) {
  emit(doc._id, doc);
}

Our monitroing database is called server_status. The design containing the mapper is called collections and the view server_list.

A Ruby database checker that can run on cron.

require 'rubygems'
require 'couchrest'
require 'json'
require 'open-uri'

STATUS_DB = 'http://localhost:5984/server_status'
COLLECTIONS = 'collections'
SERVER_LIST = 'server_list'

hostname = ARGV[0]

status_db = CouchRest.database!(STATUS_DB)
status_view = "#{STATUS_DB}/_design/#{COLLECTIONS}/_view/#{SERVER_LIST}"

# Get the current information about this server if available
server_status = begin
  status_db.get(hostname)
rescue RestClient::ResourceNotFound
  {'_id' => hostname}
end

server_status['time'] = Time.new.to_i
# Get the current times of the other servers and update this server's
# view of them
JSON(open(status_view).read)['rows'].map do |row|
  {'server' => row['id'], 'status' => row['value']}
end.each do |status|
  unless status['server'] == hostname
    server_status['servers'][status['server']] = status['status']['time']
  end
end
status_db.save_doc(server_status)

Now you need to determine when to trigger replication restart. This can be handled in the watchdog cronjob. If the highest timestamp seen for this server at other servers is above a threshold, restart replication.

The final loop triggering when the age is above a threshold. The init_replication method just posts a continuous replication trigger to the db:

JSON(open(status_view).read)['rows'].map do |row|
  {'server' => row['id'], 'status' => row['value']}
end.each do |status|
  if server_status['time'] - status['status']['time'] > THRESHOLD
    init_replication(status['server'])
  end
  unless status['server'] == hostname
    server_status['servers'][status['server']] = status['status']['time']
  end
end

Rudimentary init_replication method.

def init_replication(server)
  target = "http://#{server}:5984"
  databases = ['server_status']
  databases.each do |db|
    config = {
            'source' => "#{db}",
            'target' => "#{target}/#{db}",
            'continuous' => true
    }
    payload = JSON.generate(config)
    result = Net::HTTP.new('127.0.0.1', '5984').post(
      '/_replicate', payload, {'content-type' => 'text/x-json'})
    unless result.code == 200
      p "replication to #{target}/#{db} failed with #{result.code}"
    end
  end
end

We have a monitoring view of replication ages in our system. It shows the matrix of timestamps as age in seconds rather than the actual timestamp since the age is the important metric.
Server Status

A bonus of this replication monitoring system is that we can access the status page from a mobil phone and get an accurate picture of the replication status. This doesn’t worry me now, but it did when we first set it up. Now it’s just a part of our general monitoring view.


Sincerial Launched

Since we launched Sincerial with one connected online store, fundies.no on Thursday, I feel it’s time to go through the system and the choices we made on our way to launch.

Hosting
The obvious and easy choice was Amazon Web Services (AWS) Elastic Compute Cloud (EC2). A hosting service such as EC2 allows a lot of flexibility in server solutions including quick ramp up if the luxury problem of needing more servers occurs. Freedom to choose operating system and providing a virtual server resembling what you get from a traditional hosting services were also important for us. There were alternatives, traditional hosting services where you book physical servers would incur a larger fixed cost than we wanted and at the same time, we would have lost the flexibility. We currently fire up servers and test things in no time just to shut those servers down after the test. With a traditional hosting provider, we would need spare servers for testing or used the live servers. Windows Azure could have been an alternative, but it’s just a .NET Windows hosting environment and not flexible enough. I feel I should mention Google App Engine as well, but we didn’t really consider it since it’s too restricted and even more locked in than Windows Azure.

Operating System
We decided to use CentOS for the servers. The reason for this was favorable experience with Fedora over the last year and Ubuntu getting more painful at the same time. Red Hat Enterprise Linux (RHEL) was a contender, but CentOS provides us with the part of RHEL that we need without all the parts that we would pay for, but not use. Debian would have been our choice a few years back, but the Fedora and Ubuntu experiences over the last year brought us down on the Fedora, RHEL, CentOS side and as mentioned, CentOS was the best fit among those three. Windows wasn’t considered. We had absolutely no need for anything Windows in there and remote management and configuration of Linux systems is so much easier while being extremely stable. The Amazon Machine Image (AMI) we use was created by RightScale.

Web Serving Environment
We chose Apache because that’s what we’ve used in the past and Apache is solid and dependable. The downside of Apache is that it’s a big beast that might be overkill for our need. An alternative that we looked a bit at is nginx, but we didn’t want to spend time on that before launch. We will however look more closely at nginx in the future.

Progamming Language
I am a rubyist and we chose Ruby. The first time I tried Ruby, I wrote a few scripts that I would normally have written in Perl. These weren’t big scripts, but far from one-liners. They downloaded some content and analyzed it. Writing the scripts in Ruby took me a bit longer than it would have taken writing them in Perl, but they worked right away. In Perl there is always something wrong unless you have a one-liner. The strongest alternative was Python and between Ruby and Python it comes down to taste. The first readability I got as a Googler was in Python and I did write a lot of Python, but it still doesn’t feel right. I was very happy when I got a chance to sneak myself to a Ruby readability. Java was sort of not considered, but would have been the choice if the lightweight short time-to-market alternatives hadn’t been available. We use Phusion Passenger to serve a combination of pure Ruby racks and Sinatra apps in Apache.

Storage
CouchDB won this one. Key value storage is what we need so relational databases are a complication that we can happily forget about. Selling points of CouchDB was that it was easy to get started, it has an HTTP RESTful API and views are written as Javascript map-reduce. Map reduces is well suited to our calculation needs so we get a lot more done inside the database than we would do with i.e. SQL. The strongest alternative was definitely MongoDB which is very similar to CouchDB, but uses a more classical query language. We also briefly looked at Voldemort, but our calculation need is not suited to Voldemort‘s simple key lookup scheme. SimpleDB ties us to Amazon and Hadoop is a bit too heavy for our needs. We didn’t consider MySQL, but that would have been our choice had we needed a relational database.

Conclusion
Our LARC stack (Linux Apache, Ruby, CouchDB) works very well for us and that combination has enabled us to develop our service very quickly with the result being an easy system to maintain. We haven’t really looked back at those choices except for a few moments after upgrading to CouchDB 0.10.0 and seeing that our map reduces that put a lot of work in the reducers had to be rewritten. One look at MongoDB‘s query language stopped those regrets. As mentioned when discussing web serving environments, we do consider switching from Apache to nginx, but it’s not a high priority thing and we are happy with Apache and the consideration comes more from curiosity than need. As for CentOS and EC2, they just work and gets out of the way which is exactly what they should do.


CouchDB on Amazon EC2 CentOS server with Sprinkle

Read the Getting Started part of Till Klampäckel’s CouchDB on Ubuntu on AWS blog post for some general information. I see no reason to repeat those things here.

Till stresses the need for a security group opening port 80, but you should also enable ssh at port 22, otherwise it will be impossible to isntall anything. The AMI I use is rightscale’s CentOS 5.2 i386 v4.2.4. If you need a 64-bit image, that should work just as well.

Make sure you have Sprinkle installed on you the system you are installing from. Put this in your spinkle file and name it something reasonable. I called it couchdb.rb. If not, gem install sprinkle. Sprinkle is written in Ruby so if you don’t have Ruby, you should start by installing that.


# Sprinkle provisioning and deployment for CouchDB on
# an Amazon EC2 CentOS server

package :spidermonkey do
  source 'http://ftp.mozilla.org/pub/mozilla.org/js/js-1.7.0.tar.gz' do
    custom_dir 'js/src'
    custom_install "make BUILD_OPT=1 -f Makefile.ref && cp *.{h,tbl} /usr/include/ && cd Linux_All_OPT.OBJ && cp *.h /usr/include/ && mkdir -p /usr/{bin,lib}/ && cp js /usr/bin/ && cp libjs.so /usr/lib/"
end

  verify do
    has_executable 'js'
    has_file '/usr/include/jsapi.h'
    has_file '/usr/lib/libjs.so'
  end
end

package :erlang_dependencies do
  yum %w( ncurses-devel openssl-devel)
end

package :erlang do
  description 'Erlang, the programming language'
  source 'http://erlang.org/download/otp_src_R13B01.tar.gz'

  verify do
    has_executable '/usr/local/bin/erl'
  end

  requires :erlang_dependencies
end

package :couchdb_dependencies do
  yum %w( curl curl-devel icu libicu-devel )
end

# - CouchDB 0.9.1
package :couchdb, :provides => :database do
  description 'CouchDB'
  version '0.9.1'
  source 'http://mirrorservice.nomedia.no/apache.org/couchdb/0.9.1/apache-couchdb-0.9.1.tar.gz' do
    post :install, 'adduser -r -d /usr/local/var/lib/couchdb -M -s /bin/bash -c "CouchDB Administrator" couchdb'
    post :install, 'touch /usr/local/var/log/couchdb/couch.log'
    post :install, 'chown couchdb /usr/local/var/log/couchdb/couch.log'
    post :install, 'mkdir -p /usr/local/var/lib/couchdb'
    post :install, 'chown couchdb /usr/local/var/lib/couchdb'
    post :install, '/usr/local/etc/rc.d/couchdb start'
    post :install, 'ln -s /usr/local/etc/rc.d/couchdb /etc/init.d/couchdb'
    post :install, 'chkconfig --add couchdb'
  end

  verify do
    has_executable '/usr/local/bin/couchdb'
  end

  requires :couchdb_dependencies
  requires :erlang
  requires :spidermonkey
end

package :rubygems do
  description 'Ruby Gems Package Management System'
  yum 'rubygems'
end

package :couchrest do
  description 'Rest API for CouchDB'
  version '0.33'
  gem 'couchrest'
end

policy :db, :roles => :db do
  requires :database
  requires :couchrest
end

# Deployment
deployment do
  delivery :capistrano do
    set :user, 'root'
    set :use_sudo, false
    set :run_method, :run

    role :db, 'ec2-x-y-z-w.eu-west-1.compute.amazonaws.com'
  end

  # source based package installer defaults
  source do
    prefix '/usr/local' # where all source packages will be configured to install
    archives '/usr/local/sources' # where all source packages will be downloaded to
    builds '/usr/local/build' # where all source packages will be built
  end
end

Replace ec2-x-y-z-w.eu-west-1.compute.amazonaws.com with the public DNS name listed on the Amazon Web Services instance view. You don’t need rubygems and couchrest unless you are going to use Ruby, but I decided to leave them since CouchRest is a nice libarary to use when talking to CouchDB from Ruby.

Run it in a shell with sprinkle -s couchdb.rb. Might be interesting to check the powder cloud like this first: sprinkle -cts couchdb.rb. The expected cloud looks liek this:

--> Cloud hierarchy for policy db

Policy db requires package database
Selecting couchdb for virtual package database
  Package couchdb requires couchdb_dependencies
  Package couchdb requires erlang
    Package erlang requires erlang_dependencies
  Package couchdb requires spidermonkey

Policy db requires package couchrest
  Package couchrest requires rubygems

Set up an SSH tunnel to get the remote futonI tend to use 5994 locally to avoid conflicts with the local CouchDB. ssh -L 5994:localhost:5984 root@ec2-x-y-z-w.eu-west-1.compute.amazonaws.com where once again, ec2-x-y-z-w.eu-west-1.compute.amazonaws.com should be replaced with the public DNS name listed on the Amazon Web Services instance view. Point your browser to http://localhost:5994/_utils/ for that familiar futon view.


The CouchDB indexer – lightweight search engine in hours

Have you ever been in a situation where you needed to create a reverse lookup index of some documents you had lying around?

A reverse lookup index is the kind of index used by the search engines (or Googles if you like) of this world. Creating a reverse lookup index isn’t hard, but you would normally expect to spend a couple of weeks writing code to create one when needed unless you decide to use an existing indexer like lucene. Using lucene is a bit heavy if the indexing is not core to your application. If you store your documents in CouchDB, you can create an indexer writing just 4 lines of JavaScript. You should have at least one more line for safeguarding your input values, but a search engine indexer in 5 lines of JavaScript is IMHO still pretty good.

The prerequisite for this indexer is that the documents you want to index all have a vector field containing a document vector in the form of a hash mapping term to term weight {<term0> => <tweight0>, <tterm1> => <tweight1>, …,<ttermn> => <tweightn>}. The weight could be just the number of times a term occurs in the document or a some metric indicating how important a word is to a document relative to all possible documents. The traditional weight used in search engines is tf-idf (term frequency multiplied by inverse document frequency). Head over to Wikipedia if you want to learn more about tf-idf. Of course, if you just want to find all documents matching a query, you can ignore the weights completely.

If you have document vectors, you have all the input data you need to create a reverse lookup index. This is the mapper if you just want to get all documents matching a query. Note that it completely ignores the term weights:


function(doc) {
    if (!('vector' in doc)) return;
    var vector = doc.vector;
    for (var term in vector) {
        emit(term, doc._id);
    }
}

The function operates on each document in the database. The first statement is a simple safeguard ensuring that we don’t try to access vector if the document doesn’t have that property. Since CouchDB is schema free, different types of documents with different fields may be stored in the same database. If the vector property is there, we store it in a variable called vector. For each element in vector, we emit the key which is the term and the id of the document we are operating on. If you run just this mapper, you will get a list of term to single document id mappings. This is a major step forward since we now have a reverse mapping of the database.

To get the reverse database map into something that is quick and easy to lookup, we need a reducer. It’s purpose is to convert the list of term, document id pairs into a single term to document id list.


function(keys, values) {
    var docs = [];
    for (var i = 0; i < values.length; ++i) {
        docs.push(values[i]);
    }
    return docs;
}

In this situation, we don’t care about the keys. CouchDB handles that for us. We need an array to store all the document ids. Then we iterate over all the values and push them into our array. Finally we return the array. CouchDB ensures that this is only called once for a single term ensuring we end up with a single document id list for each term.

This index can be used to find all documents matching a given set of terms. Note that there is not much sophistication in this method so the only rank score you can get is the number of matching terms. Adding term weights to the index will give you something to use for ranking. Change the emit line in the mapper to

emit(term, [doc._id, vector[term]]);

This will give you a list of document id, term weight pairs for each term instead of just the document ids.

That mapper is 7 lines of code, 4 lines if you don’t count the function declaration line and lines only containing curly braces. Ignoring the safe guard as well, the mapper body can be reduced to this single line by also skipping the temporary variable assignment:

for (var term in doc.vector) emit(term, [doc._id, doc.vector[term]]);

In the same manner, the reduce function may be reduced to a body of just 3 lines of code

var docs = [];
for (var i = 0; i < values.length; ++i) docs.push(values[i]);
return docs;

That’s the power and beauty of CouchDB map reduce. You can write a search engine indexer in 4 lines of JavaScript. Granted, you need to create vectors of your documents in advance, but that’s just a matter of parsing a text string and splitting on whitespace and/or punctuation into an array and reducing the term array into a hash of <term> => <weight> pairs. Sure, you can do this with a map reduce as well, but that might be overkill since you will only be operating on a single document at a time.

One last important point is that while Futon, the CouchDB browser client will show the expected results, you have to explicitly tell CouchDB to group the result if you want to use this in your application. My database is called pages, the design is called demos and the view index making the output of the map reduce available as json at
http://localhost:5984/pages/_design/demos/_view/index?group=true
Thanks to J. Chris Anderson for clarifying and pointing out the grouping query usage.


Follow

Get every new post delivered to your Inbox.