Using Postgres schemas to separate data of your SaaS application in Django

Track:
Web Development, Web APIs, Front-End Integration
Type:
Talk
Level:
beginner
Duration:
30 minutes

Abstract

Every SaaS will come against the same issue at one point - how to make sure to only show a customer's data to only that specific customer? And it's not just a security problem, but a performance problem as well. At scale, even with indexes, selecting just the appropriate data can become slow on massive tables.

The "naive" approach is to have a table of customers, and link every other table using foreign keys, and always filter based on the current customer. This approach works fine, and with the library django-scope is pretty safe, but the filter still always needs to be provided and all the data is still in the same physical database table.

Database segregation to the rescue! PostgreSQL has a feature called schemas, which almost acts like a database within a database - each has its own tables and indexes, and you can have many different schemas within one database. In this talk I will introduce you to the django-tenants library, which utilizes these schemas to implement tenanting.

Django-tenants introduces two types of apps, shared apps containing data accessible for all tenants, and tenanted apps specific to one tenant. The data in the tenanted app is only available while the tenant is active, usually based on a subdomain. The django models then work exactly like before, but only the correct data will be returned without any filtering.

In the talk, after walking through a simplified setup of the problem, we'll look at how much simpler django-tenants can make our life while implementing a SaaS application, but also look at certain new and more exciting problems it can bring.