SlideShare a Scribd company logo
Multitenant applications: how
and why
@xima
Multitenant applications: How and Why
Who am I?
● Filipe Ximenes
● Recife / Brazil
● Aussie for 1 year
(2008 - 2009)
Multitenant applications: How and Why
vinta.com.br/playbook
FLOSS
Django React boilerplate
https://github.com/vintasoftware/django-react-boilerplate
Django Role Permissions
https://github.com/vintasoftware/django-role-permissions
Tapioca
https://github.com/vintasoftware/tapioca-wrapper
Context
Corporate
Fidget Spinner
Tracking
Multitenant applications: How and Why
Multitenant applications: How and Why
Multitenant applications: How and Why
"How do you protect our data?"
What is Multitenancy
"... refers to a software
architecture in which a single
instance of software runs on a
server and serves multiple
tenants."
- Wikipedia
What we want to achieve?
● Reduce infrastructure costs by sharing hardware resources
● Simplify software maintenance by keeping a single code base
● Simplify infrastructure maintenance by having fewer nodes
Single Shared Schema
[or how the big guys do it]
Multitenant applications: How and Why
"Talk is cheap..."
Routing - ibm.spinnertracking.com
def tenant_middleware(get_response):
def middleware(request):
host = request.get_host().split(':')[0]
subdomain = host.split('.')[0]
try:
customer = Customer.objects.get(name=subdomain)
except Customer.DoesNotExist:
customer = None
request.customer = customer
response = get_response(request)
return response
return middleware
Querying
avg_duration = (
Spin.objects
.filter(user_spinner__user__customer=request.customer)
.aggregate(avg=Avg('duration')))['avg']
Multitenant applications: How and Why
Simpler querying
avg_duration = (
Spin.objects
.filter(customer=request.customer)
.aggregate(avg=Avg('duration')))['avg']
Case study: Salesforce
● 1:5000 ratio
● Double checking
● Transparent to developers
Drawbacks
● Guaranteeing isolation is hard
● Might lead to complexity to the codebase
● 3rd party library integration
Multiple databases
Multitenant applications: How and Why
Routing
DATABASES = {
'default': {
'ENGINE': ...,
'NAME': ...,
},
'ibm': {
'ENGINE': ...,
'NAME': ...,
}
}
The `.using()` approach
spinners = (
Spinner.objects
.using(request.customer.name)
.annotate(
avg_duration=Avg('owned_spinners__spins__duration'))
.order_by('-avg_duration'))
The threadlocal middleware approach
def multidb_middleware(get_response):
def middleware(request):
subdomain = get_subdomain(request)
customer = get_customer(subdomain)
request.customer = customer
@thread_local(using_db=customer.name)
def execute_request(request):
return get_response(request)
response = execute_request(request)
return response
return middleware
The router
class TenantRouter(object):
def db_for_read(self, model, **hints):
return get_thread_local('using_db', 'default')
def db_for_write(self, model, **hints):
return get_thread_local('using_db', 'default')
# …
# settings.py
DATABASE_ROUTERS = ['multitenancy.routers.TenantRouter']
Querying
spinners = (
Spinner.objects
.using(request.customer.name)
.annotate(
avg_duration=Avg('owned_spinners__spins__duration'))
.order_by('-avg_duration'))
Database Multitenancy
vs.
Application Multitenancy
Single Database
Multiple Schemas
Multitenant applications: How and Why
What are schemas in the first place?
SELECT id, name FROM user
WHERE user.name LIKE 'F%';
What are schemas in the first place?
CREATE SCHEMA ibm;
SELECT id, name FROM ibm.user
WHERE ibm.user.name LIKE 'F%';
The `search_path`
SET search_path TO ibm;
SELECT id, name FROM user
WHERE user.name LIKE 'F%';
Django-tenant-schemas
Routing - middleware
# ...
connection.set_schema_to_public()
hostname = self.hostname_from_request(request)
TenantModel = get_tenant_model()
try:
tenant = self.get_tenant(TenantModel, hostname, request)
assert isinstance(tenant, TenantModel)
except TenantModel.DoesNotExist:
# ...
request.tenant = tenant
connection.set_tenant(request.tenant)
# ...
Routing - settings
MIDDLEWARE_CLASSES = [
'tenant_schemas.middleware.TenantMiddleware',
# …
]
DATABASES = {
'default': {
'ENGINE': 'tenant_schemas.postgresql_backend',
'NAME': 'mydb',
}
}
Routing - db backend
# ...
try:
cursor_for_search_path.execute(
'SET search_path = {0}'.format(','.join(search_paths)))
except (django.db.utils.DatabaseError, psycopg2.InternalError):
self.search_path_set = False
else:
self.search_path_set = True
if name:
cursor_for_search_path.close()
# ...
The Command Line
./manage.py tenant_command shell
./manage.py createsuperuser
./manage.py migrate_schemas
Querying
spinners = (
Spinner.objects
.annotate(
avg_duration=Avg('owned_spinners__spins__duration'))
.order_by('-avg_duration'))
SELECT id, duration FROM ibm.spinner_spin
WHERE duration > 120
UNION
SELECT id, duration FROM vinta.spinner_spin
WHERE duration > 120;
Querying across schemas
SELECT uuid, duration FROM ibm.spinner_spin
WHERE duration > 120
UNION
SELECT uuid, duration FROM vinta.spinner_spin
WHERE duration > 120;
Querying across schemas
Upsides
● Querying looks same as standard application
● New schemas created automatically
● Knows how to handle migrations
● Simpler infrastructure
Drawbacks
● Be carefull with too many schemas (maybe not more than 100's clients?)
● Tests need some setup and might get slower
● Harder to query across schemas
multitenancy is not
discrete, it is a
continuous spectrum
bit.ly/django-multitenancy
github.com/filipeximenes/multitenancy
Obrigado!
http://bit.ly/vinta2017
Newsletter:
vinta.com.br/blog/
twitter.com/@xima
github.com/filipeximenes
ximenes@vinta.com.br

More Related Content

PPT
Xen Summit 2008 Tokyo - Operating Xen domains through LL(Perl/Python) with li...
ODP
Tutorial Puppet
KEY
CoffeeScript By Example
PDF
Bento lunch talk
PDF
Node.js Introduction
PDF
Scaling in Mind (Case study of Drupal Core)
PDF
Building a multitenant application with Django
PPT
Multi Tenancy With Python and Django
Xen Summit 2008 Tokyo - Operating Xen domains through LL(Perl/Python) with li...
Tutorial Puppet
CoffeeScript By Example
Bento lunch talk
Node.js Introduction
Scaling in Mind (Case study of Drupal Core)
Building a multitenant application with Django
Multi Tenancy With Python and Django

Similar to Multitenant applications: How and Why (20)

PPTX
Software as a service
PPTX
Multi Tenancy In The Cloud
PPTX
What is Multi-Tenant Architecture ?
PDF
Scaling Multi-Tenant Applications Using the Django ORM & Postgres | PyCaribbe...
PDF
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
PPTX
Tenants: A Look Behind the Scenes
PDF
Scaling Multi-tenant Applications Using the Django ORM & Postgres | PyCon Can...
PPTX
“Salesforce Multi-tenant architecture”,
PDF
Scaling Multi-Tenant Applications Using Django and Postgres | PyBay 2018 | Sa...
PDF
A systematic review of in-memory database over multi-tenancy
PDF
Defining multitenancy
PDF
Sharing data in a multitenant architecture
PPTX
SaaS transformation with OCE - uEngineCloud
PDF
Henry been database-per-tenant with 50k databases
PPTX
Building a multi-tenant application using 45.000 databases - Henry Been - Cod...
PPTX
Cloud brew cloudcamp
PDF
Multitenancy in cloud computing architecture
PDF
How to build customizable multitenant web applications - IPC11 Spring Edition
PDF
Database Multitenancy in Ruby
PDF
Multitenancy con múltiples Bases de Datos
Software as a service
Multi Tenancy In The Cloud
What is Multi-Tenant Architecture ?
Scaling Multi-Tenant Applications Using the Django ORM & Postgres | PyCaribbe...
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
Tenants: A Look Behind the Scenes
Scaling Multi-tenant Applications Using the Django ORM & Postgres | PyCon Can...
“Salesforce Multi-tenant architecture”,
Scaling Multi-Tenant Applications Using Django and Postgres | PyBay 2018 | Sa...
A systematic review of in-memory database over multi-tenancy
Defining multitenancy
Sharing data in a multitenant architecture
SaaS transformation with OCE - uEngineCloud
Henry been database-per-tenant with 50k databases
Building a multi-tenant application using 45.000 databases - Henry Been - Cod...
Cloud brew cloudcamp
Multitenancy in cloud computing architecture
How to build customizable multitenant web applications - IPC11 Spring Edition
Database Multitenancy in Ruby
Multitenancy con múltiples Bases de Datos
Ad

More from Filipe Ximenes (8)

PDF
Tasks: you gotta know how to run them
PDF
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
PDF
O que é esse tal de rest? [PyBR2016]
PDF
APIs: o que são? onde vivem? do que se alimentam? [PyNE2016]
PDF
Usando tapioca para acessar APIs web [PyBR11]
PDF
Expressões idiomáticas do python
PDF
Boas práticas de django
PDF
Migrando do App Engine para o Heroku
Tasks: you gotta know how to run them
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
O que é esse tal de rest? [PyBR2016]
APIs: o que são? onde vivem? do que se alimentam? [PyNE2016]
Usando tapioca para acessar APIs web [PyBR11]
Expressões idiomáticas do python
Boas práticas de django
Migrando do App Engine para o Heroku
Ad

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Machine learning based COVID-19 study performance prediction
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation theory and applications.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Understanding_Digital_Forensics_Presentation.pptx
Review of recent advances in non-invasive hemoglobin estimation
20250228 LYD VKU AI Blended-Learning.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
“AI and Expert System Decision Support & Business Intelligence Systems”
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Spectral efficient network and resource selection model in 5G networks
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Machine learning based COVID-19 study performance prediction
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation theory and applications.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Per capita expenditure prediction using model stacking based on satellite ima...
CIFDAQ's Market Insight: SEC Turns Pro Crypto

Multitenant applications: How and Why