29 May 2013

Multi-tenanting Ruby on Rails Applications on Heroku - Part I


Multi-tenanting is a term used to describe the ability to virtually partition data within in the application database so that the data of different tenants (typically client accounts) cannot be accessed by users of other tenants of the application.
Heroku is an awesome Platform as a Service (PaaS) provider which originally started out specializing in hosting Ruby on Rails Applications using Postgres. I use Heroku extensively for the Ruby on Rails applications which I develop and support.
Let's take a look at the fundamental philosophy of a multi-tenanted application. Suppose, for example, that you have a SaaS application, running on Heroku, which offers a strategic planning service for organizations. Each organization would then be a tenant and there would be multiple users of that organization accessing that organization's strategic plan data. Obviously, each tenant would want to know that rigid safeguards were in place to prevent their organizational plans from being visible outside their organization, even accidentally.
Perhaps you might also want to foster an eco-system with consultants for your application. Then it might happen that a consultant would need access to multiple tenants.
In Rails-ese, we've described two models, Tenant and User, with the following associations:

class Tenant < ActiveRecord::Base
  has_and_belongs_to many :users 

class User < ActiveRecord::Base
  has_and_belongs_to many :tenants 

This series of articles will discuss different multi-tenanting methods (specifically in the context of Postgres on Heroku for RoR apps) and end with a tutorial for how to use milia, a gem to ensure multi-tenanting for RoR apps on Heroku.
There are four parts to this discussion:
  1. Introduction
  2. Multi-tenanting methods
  3. Schema-based vs Row-based Multi-tenanting
  4. Milia tutorial