This website uses cookies to better the user experience of its visitors. Where applicable, this website uses a cookie control system, allowing users to allow or disallow the use of cookies on their computer/device on their first visit to the website. This complies with recent legislative requirements for websites to obtain explicit consent from users before leaving behind or reading files such as cookies on a user’s computer/device. To learn more click Cookie Policy.

Privacy preference center

Cookies are small files saved to a user’s computer/device hard drive that track, save, and store information about the user’s interactions and website use. They allow a website, through its server, to provide users with a tailored experience within the site. Users are advised to take necessary steps within their web browser security settings to block all cookies from this website and its external serving vendors if they wish to deny the use and saving of cookies from this website to their computer’s/device’s hard drive. To learn more click Cookie Policy.

Manage consent preferences

These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
Cookies list
Name _rg_session
Provider rubygarage.org
Retention period 2 days
Type First party
Category Necessary
Description The website session cookie is set by the server to maintain the user's session state across different pages of the website. This cookie is essential for functionalities such as login persistence, ensuring a seamless and consistent user experience. The session cookie does not store personal data and is typically deleted when the browser is closed, enhancing privacy and security.
Name m
Provider m.stripe.com
Retention period 1 year 1 month
Type Third party
Category Necessary
Description The m cookie is set by Stripe and is used to help assess the risk associated with attempted transactions on the website. This cookie plays a critical role in fraud detection by identifying and analyzing patterns of behavior to distinguish between legitimate users and potentially fraudulent activity. It enhances the security of online transactions, ensuring that only authorized payments are processed while minimizing the risk of fraud.
Name __cf_bm
Provider .pipedrive.com
Retention period 1 hour
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to support Cloudflare Bot Management. This cookie helps to identify and filter requests from bots, enhancing the security and performance of the website. By distinguishing between legitimate users and automated traffic, it ensures that the site remains protected from malicious bots and potential attacks. This functionality is crucial for maintaining the integrity and reliability of the site's operations.
Name _GRECAPTCHA
Provider .recaptcha.net
Retention period 6 months
Type Third party
Category Necessary
Description The _GRECAPTCHA cookie is set by Google reCAPTCHA to ensure that interactions with the website are from legitimate human users and not automated bots. This cookie helps protect forms, login pages, and other interactive elements from spam and abuse by analyzing user behavior. It is essential for the proper functioning of reCAPTCHA, providing a critical layer of security to maintain the integrity and reliability of the site's interactive features.
Name __cf_bm
Provider .calendly.com
Retention period 30 minutes
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to distinguish between humans and bots. This cookie is beneficial for the website as it helps in making valid reports on the use of the website. By identifying and managing automated traffic, it ensures that analytics and performance metrics accurately reflect human user interactions, thereby enhancing site security and performance.
Name __cfruid
Provider .calendly.com
Retention period During session
Type Third party
Category Necessary
Description The __cfruid cookie is associated with websites using Cloudflare services. This cookie is used to identify trusted web traffic and enhance security. It helps Cloudflare manage and filter legitimate traffic from potentially harmful requests, thereby protecting the website from malicious activities such as DDoS attacks and ensuring reliable performance for genuine users.
Name OptanonConsent
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonConsent cookie determines whether the visitor has accepted the cookie consent box, ensuring that the consent box will not be presented again upon re-entry to the site. This cookie helps maintain the user's consent preferences and compliance with privacy regulations by storing information about the categories of cookies the user has consented to and preventing unnecessary repetition of consent requests.
Name OptanonAlertBoxClosed
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonAlertBoxClosed cookie is set after visitors have seen a cookie information notice and, in some cases, only when they actively close the notice. It ensures that the cookie consent message is not shown again to the user, enhancing the user experience by preventing repetitive notifications. This cookie helps manage user preferences and ensures compliance with privacy regulations by recording when the notice has been acknowledged.
Name referrer_user_id
Provider .calendly.com
Retention period 14 days
Type Third party
Category Necessary
Description The referrer_user_id cookie is set by Calendly to support the booking functionality on the website. This cookie helps track the source of referrals to the booking page, enabling Calendly to attribute bookings accurately and enhance the user experience by streamlining the scheduling process. It assists in managing user sessions and preferences during the booking workflow, ensuring efficient and reliable operation.
Name _calendly_session
Provider .calendly.com
Retention period 21 days
Type Third party
Category Necessary
Description The _calendly_session cookie is set by Calendly, a meeting scheduling tool, to enable the meeting scheduler to function within the website. This cookie facilitates the scheduling process by maintaining session information, allowing visitors to book meetings and add events to their calendars seamlessly. It ensures that the scheduling workflow operates smoothly, providing a consistent and reliable user experience.
Name _gat_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _gat_UA-* cookie is a pattern type cookie set by Google Analytics, where the pattern element in the name contains the unique identity number of the Google Analytics account or website it relates to. This cookie is a variation of the _gat cookie and is used to throttle the request rate, limiting the amount of data collected by Google Analytics on high traffic websites. It helps manage the volume of data recorded, ensuring efficient performance and accurate analytics reporting.
Name _ga
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga cookie is set by Google Analytics to calculate visitor, session, and campaign data for the site's analytics reports. It helps track how users interact with the website, providing insights into site usage and performance.
Name _ga_*
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga_* cookie is set by Google Analytics to store and count page views on the website. This cookie helps track the number of visits and interactions with the website, providing valuable data for performance and user behavior analysis. It belongs to the analytics category and plays a crucial role in generating detailed usage reports for site optimization.
Name _gid
Provider rubygarage.org
Retention period 1 day
Type First party
Category Analytics
Description The _gid cookie is set by Google Analytics to store information about how visitors use a website and to create an analytics report on the website's performance. This cookie collects data on visitor behavior, including pages visited, duration of the visit, and interactions with the website, helping site owners understand and improve user experience. It is part of the analytics category and typically expires after 24 hours.
Name _dc_gtm_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _dc_gtm_UA-* cookie is set by Google Analytics to help load the Google Analytics script tag via Google Tag Manager. This cookie facilitates the efficient loading of analytics tools, ensuring that data on user behavior and website performance is accurately collected and reported. It is categorized under analytics and assists in the seamless integration and functioning of Google Analytics on the website.

Three Database Architectures for a Multi-Tenant Rails-Based SaaS App

  • 127245 views
  • 9 min
  • Jan 04, 2020
Artem Z.

Artem Z.

Ruby/JS Developer

Sviatoslav A.

Sviatoslav A.

Copywriter

Share

Multi-tenant Software as a Service (SaaS) applications are extremely popular products. Why is that?

Let’s imagine you want to create a web app and provide it to several organizations as a white label product. How might you implement such a project? You could simply copy the entire codebase for each organization. But this means you’ll have to support multiple application instances separately. That’s not the best solution, as your development team will have to manage server infrastructure and update features independently for each app instance.

Let’s now imagine that you provide your app to a dozen tenants and deploy a new app version for each of them. To update all applications, your web team will have to do the same thing a dozen times! There is a much better solution – you can develop a multi-tenant Software as a Service application.

Multi-tenant Software as a Service application

Multi-tenancy means that multiple organizations – otherwise called tenants or groups of users – can employ the very same application. With a multi-tenant SaaS app, your web development team will need to deploy and support only one codebase – not multiple applications. You’ll be able to update your SaaS app simultaneously for all tenants, and it’ll be easier to support the server infrastructure. Overall, multi-tenancy greatly simplifies development of a Software as a Service app.

But before you build a multi-tenant SaaS application, you’ll need to address one major problem – how to securely isolate each client’s data. Thus, the database layer will require special attention. We’ll introduce three approaches to designing the database layer.

We’ll be talking about how to build a multi-tenant SaaS app with Rails, and to design the database layer for a multi-tenant Rails-based SaaS application, you’ll need the Apartment Ruby library. The other Ruby libraries we should mention are Detectify and Houser. Your development team can use those libraries to build database requests. You’ll also need a relational database, such as PostgreSQL or MySQL, to save tenant data in the Rails app. These Ruby libraries and databases that we’ve just mentioned will help you complete specific tasks, and we’ll review them in detail.

Multi-Tenant SaaS Application and Database Design

As we’ve suggested, the major architectural concern with multi-tenant SaaS apps is the database layer, which is also called the persistence layer. There are three aspects of database design that we’ll address:

  • The level of tenant data isolation;
  • Difficulties with restoring data;
  • Difficulties with data encryption.

A multi-tenant application architecture can adopt one of three database architectures. The first option is to use a separate database for each tenant. The second option is to use the same database for all tenants, but to give each tenant their own schema with individual tables. With either of these two approaches, we recommend using Apartment, the Ruby gem we mentioned previously.

But there’s also the third option: tenants share a schema within the same database. Note that Apartment won’t work in this case. Your development team will need to implement this design manually.

We’ll provide more details about the workings of the Ruby libraries we’ve mentioned, but first let’s dive into how to organize the database layer.

Single Database for Single Tenant

The main advantage of “one database–one tenant” design is that it ensures the highest level of data safety. Each database instance is located on a separate server, so instances are physically separated. This means that one tenant simply can’t access another tenant’s data.

Separate database architecture in a multi-tenant SaaS application

Another advantage of this approach is that it’s flexible. Imagine a situation when one tenant wants to encrypt data but others don’t. Do you have to encrypt the data of all tenants? Actually, you don’t! Since tenants have fully isolated databases, we are free to encrypt the data of any tenant (or not).

The complete isolation of databases also helps us to easily restore data. Whenever a tenant’s data gets corrupted, we can retrieve it from a backup database without implementing complex logic.

Given these advantages, using individual databases for tenants seems like a slick solution. But there’s always a catch. As we mentioned before, multi-tenant Software as a Service applications are designed to reduce the cost of server infrastructure. However, when you provide a dedicated database for each tenant, you have to use a separate server instance to store each database. Hence, you’ll have to pay for additional servers, driving up the cost of using the application. Besides, the ‘separate database’ approach complicates the server infrastructure, making it more difficult to support.

Tenants may not want to save their data alongside that of other tenants. If tenants need the highest data safety and flexibility, and are ready to pay for it, then the “single database” design is a perfect choice. You can implement this design for a full white-label web application (it's understood that a full white-label app has a unique domain name; a partial white-label app would have only a unique subdomain name).

But there is a database design that is cheaper and still provides partial isolation: the “separate schemas” design.

Separate Schema for Each Tenant

To lower the operating costs of the database layer, you can opt for a ‘separate schema’ design.

With this design, the app connects to a single database instance. Each tenant has their own schema (a set of tables) within the database, but not an entire database. Using separate schemas lets you reduce the complexity of server infrastructure, and thereby the cost. The separate schema design provides another benefit as well: it’s very flexible. Although initially each new schema has standard tables, tenants are able to customize their schema however they want.

Shared database architecture in a multi-tenant SaaS application

There are some disadvantages of the separate schema design, however; for one, we have to pay attention to how we back up and restore data. Let’s say that one tenant’s data gets corrupted, while the data of all other tenants is intact. To avoid overwriting the entire database, developers will have to implement special techniques.

One approach would be to copy tenant data from a backup server to a separate server. After that, we could retrieve the data from the necessary schema. Finally, we could use this data to replace the corrupted information in the main database. As you can imagine, this process is time consuming.

Separate schemas provide only partial data isolation, but are a cheaper alternative to fully isolated databases. The separate schema design is equally good for both partial and full white-label SaaS applications.

So far, we’ve reviewed two approaches to designing the database layer that provide a high enough level of data isolation. There’s one more option left – a shared schema for all tenants.

Shared Schema for Tenants

Using a shared schema for all tenants is an easy-to-implement approach, at least at the initial stages of development. Let’s sort through how a shared schema works. In the simplest sense, the data of all tenants will be stored in the same tables. To find and retrieve data from each row, which is assigned to a specific tenant, your SaaS application will use a tenant ID.

The shared schema design provides a few benefits. There’s no need to create and adjust schemas for tenants, unlike with the separate schema approach. There’s also no need to run additional servers for databases.

Shared schema architecture in a multi-tenant SaaS application

But what about the disadvantages of using a shared schema? Hopefully, your app will gradually add more and more tenants over time. Assuming it does, then eventually it will become increasingly difficult to query, index, and update data. Besides, it’s also difficult to retrieve data for a given tenant. The multi-tenant SaaS app first has to verify the tenant access level; then the app must also verify the user access level, and only after that can we build a request to the database. With this design, each request will be fairly complex.

Given the advantages and disadvantages of each approach, we recommend using separate schemas, as they provide the best balance between difficulty of development and cost of running the database layer. But you should take into consideration the level of data safety your tenants will require. All three approaches guarantee enough security level for certain applications, and your Service Level Agreements must stipulate the level of security you provide: either full or partial isolation.

So that’s how to implement the database layer in a Software as a Service application. Now we need to talk about what tools you can use to develop this layer for a Ruby on Rails-based SaaS app.

Implementing Database Design in a Rails-based SaaS App

Apartment is a top Ruby library that separates tenant data. Basically, you can create tenants using Apartment, and the library will automatically assign a new isolated schema to each tenant. This is the second approach that we discussed. But Apartment can create isolated database instances as well.

As we can see, Apartment allows us to build Rails-based SaaS apps with full or partial white-labeling right away. And to get the most from Apartment, you should use a PostgreSQL database.

How does Apartment work? Apartment fetches data from the schema that corresponds to the elevator – domain, subdomain, or full host name. The library simply analyzes each request to the database using elevators. By default, Apartment splits tenants by subdomains, but you can quickly set it up to use domains.

Keep in mind that for the third approach – a shared schema – Apartment won’t work.

To implement a shared schema approach, your development team only needs to assign IDs to tenants and send database requests with those IDs. And if you’re going to provide custom domains or subdomains for your clients, you’ll need either Detectify or Houser.

Houser is a multi-tenancy gem that can send database requests using subdomain names. But Houser is a relatively old Ruby library. For modern Rails-based SaaS apps, we wanted more flexibility. That's why we've developed Detectify to replace Houser.

Detectify can create database requests using both domains and subdomains. It also lets the app ignore routes when sending a URL-based request to the database. Overall, Detectify is a more advanced multi-tenancy gem than Houser. For more information, you can read our Detectify review.

Developing a multi-tenant Software as a Service application with Rails goes well beyond designing the database layer. But if you choose one of these three database architectures at the start, it will be easier to develop, support, and scale your web application in the long run.

CONTENTS

Authors:

Artem Z.

Artem Z.

Ruby/JS Developer

Sviatoslav A.

Sviatoslav A.

Copywriter

Rate this article!

Nay
So-so
Not bad
Good
Wow
36 rating, average 4.61 out of 5

Share article with

Comments (6)
Mujadded Al Rabbani Alif
Mujadded Al Rabbani Alif about 7 years ago
This article just cleared so many confusions of mine. Thank you!
Reply
Pramod Shinde
Pramod Shinde over 6 years ago
Hey, In Single Database for Single Tenant approach, Can we create multiple databases on a single database server/instance for each tenant?
Reply
Ercan Ilik
Ercan Ilik about 6 years ago
Thank you very much for a useful post.
Reply
Maryna Z.
Maryna Z. about 6 years ago Ercan Ilik
Hi Ercan! Thanks for your feedback ;)
Reply
Cuong Hoang
Cuong Hoang almost 6 years ago
Useful doc for me. Thank you !
Reply
Maryna Z.
Maryna Z. almost 6 years ago Cuong Hoang
Thank you, Cuong! We're happy to be helpful.
Reply

Subscribe via email and know it all first!