SlideShare a Scribd company logo
1 of 25
Multi-Tenancy With Django 
Scott Crespo 
Software Engineer 
Director, Orlando Data Science 
Scott@OrlandoDS.com
1. Multi-Tenant Architectures 
2. Django Tenant Schemas Explained 
3. Basic Use + Tips and Tricks
Definition 
Multi-Tenancy: 
A software architecture where a single application 
instance enables multiple organizations 
(tenants) to view their data. 
*This is a key component of XaaS (i.e. Something 
as a Service)
Architectures 
Multi-tenant architectures can be placed on a continuum 
Shared Separate
Common Approaches to Multi-Tenancy
Shared Architecutre 
One Database + One Schema 
One database instance, and one public schema 
serve all tenants. 
Pros 
- Easy to build if data layer is simple 
- Every user on same domain (might be desirable) 
- Only use if a Tenant has exactly one user. 
Cons 
- Expensive (Makes lots of calls to db for tenant 
object)
Isolated Architecture 
Multiple Databases 
Each tenant has their own database instance 
Pros 
- Most Secure 
- Easier disaster recovery 
- Not expensive for compute resources 
Cons 
- Difficult to scale 
- Expensive storage resources 
- Difficult to share data across tenants
Hybrid Architecture 
One Database – Multiple Schemas 
One database instance for all tenants. Each 
tenant gets a dedicated schema. 
Shared 'public' schema 
Dedicated 'tenant' schema
What's a Schema? 
Acts as a namespace in Postgres 
Adds an additional layer of organization/isolation 
to the database 
(Database → Schema → Table) 
ex) SELECT * FROM schema_name.table 
When a schema is not specified in the connection 
or query – only the 'public' schema is accessed 
Schemas to be queried can be specified in the 
app's database connection via 
'SEARCH_PATH' parameter
One Database – Multiple Schemas 
Pros 
- Scalable 
- Cheap 
- Simple 
- Semi-secure 
- Sharable 
Cons 
- Difficult disaster 
recovery 
- Less-secure than 
dedicated db's
Django Tenant Schemas 
Implements Multi-Schema Approach 
Requires PostgreSQL 
Installation: 
$ pip install django-tenant-schemas 
Docs: 
Django-tenant-schemas.readthedocs.org
Features 
1.Tenant-based Subdomains 
2.Postgres Support
The Tenant Object 
Stored on the 'public' schema 
Contains 2 Critical Fields 
- domain_url – the tenant's domain (foo.bar.com) 
- schema_name – the schema where the Tenant's 
isolated data is stored (tenant_jw8j23jp)
Request Routing 
1.User makes a request 
2.Middleware looks up tenant object on the public 
schema and returns schema_name 
Tenant.objects.get(domain=request.domain).schema_name 
1.Tenant_Schema's database wrapper adds 
schema_name to the connection's 
SEARCH_PATH 
cursor.execute('SET search_path = public, schema_name') 
1.Subsequent Requests include schema_name 
in the search path
Basic Use 
Settings.py 
Specify TENANT and SHARED apps 
 Caution! Don't include new tenant registration on tenants' apps 
Use the tenant_schemas postgres backend 
Use the tenant schemas middleware
Basic use 
models.py 
 Create a tenant app that contains your tenant model 
(i.e. organization, company, etc). 
 Use tenant_schema's mixin 
- domain_url 
- schema_name 
from tenant_schemas.models import TenantMixin 
class Company(TenantMixin) 
company_name =models.CharField(max_length=255L) 
about = models.TextField(blank=True) 
auto_create_schema = True
The app containing your tenant model should 
remain in the project's root directory. Otherwise 
tenant_schemas can't find it. 
|-- apps 
| |-- __init__.py 
| |-- app1 
| |-- app2 
| |-- app3 
|-- Project 
| |-- __init__.py 
| |-- settings.py 
| |-- settings.pyc 
| |-- urls.py 
| `-- wsgi.py 
|-- manage.py 
`-- tenant 
|-- admin.py 
|-- __init__.py 
|-- models.py 
|-- tests.py 
`-- views.py 
* you could try simlinks as a work-around, but not recommended
Basic Use 
Command Line & DNS 
Use tenant_schemas command wrapper for 
db commands 
 Use sync_schemas and 
migrate_schemas 
 DO NOT use syncdb or migrate 
Server & DNS 
- Make sure to use subdomain wildcards
Basic Use 
Custom Commands 
Create a 'make_tenants' custom command 
- Must create a public tenant and a 
private tenant to complete creation of 
the database
Custom Command: 
make_tenants.py 
from lawfirm.models import LawFirm 
from django.core.management.base import NoArgsCommand 
import os 
if os.environ['DJANGO_SETTINGS_MODULE'] == 'settings.base': 
from settings.base import BASE_URL 
else: 
from settings.dev import BASE_URL 
class Command(NoArgsCommand): 
def handle_noargs(self,**options): 
# create your public tenant 
LawFirm(domain_url=BASE_URL, 
schema_name='public', 
firm_name='LawCRM', 
).save() 
#test tenant to verify sub-domain routing 
LawFirm(domain_url='test.'+BASE_URL, 
schema_name='test', 
firm_name='Test Firm', 
).save()
Schema Naming Schemes 
Auto-generate tenant schema names and 
enforce uniqueness. 
Prefix with 'tenant_' 
Append a hash to the end 
*Schema name must begin with a letter, $, or 
underscore 
Example Database: 
- public 
- test 
dev
Modify Search Path on the Fly 
(this took time to figure out) 
from django.db import connection 
connection.set_tenant(tenant) 
# set_tenant() accepts tenant object, NOT 
# tenant_name!
Important Decision 
Tenant Model on 
Public Schema 
User Model on Public 
Schema 
- Easy 
- Less Secure 
- User More Portable 
Tenant Model on 
Public Schema 
User Model on Private 
Schema 
- Not so easy 
- More secure 
- User Less Portable 
VS
Thanks! 
Scott Crespo 
scott@orlandods.com

More Related Content

What's hot

데브시스터즈 데이터 레이크 구축 이야기 : Data Lake architecture case study (박주홍 데이터 분석 및 인프라 팀...
데브시스터즈 데이터 레이크 구축 이야기 : Data Lake architecture case study (박주홍 데이터 분석 및 인프라 팀...데브시스터즈 데이터 레이크 구축 이야기 : Data Lake architecture case study (박주홍 데이터 분석 및 인프라 팀...
데브시스터즈 데이터 레이크 구축 이야기 : Data Lake architecture case study (박주홍 데이터 분석 및 인프라 팀...Amazon Web Services Korea
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...Anusha Chickermane
 
글로벌 기업들의 효과적인 데이터 분석을 위한 Data Lake 구축 및 분석 사례 - 김준형 (AWS 솔루션즈 아키텍트)
글로벌 기업들의 효과적인 데이터 분석을 위한 Data Lake 구축 및 분석 사례 - 김준형 (AWS 솔루션즈 아키텍트)글로벌 기업들의 효과적인 데이터 분석을 위한 Data Lake 구축 및 분석 사례 - 김준형 (AWS 솔루션즈 아키텍트)
글로벌 기업들의 효과적인 데이터 분석을 위한 Data Lake 구축 및 분석 사례 - 김준형 (AWS 솔루션즈 아키텍트)Amazon Web Services Korea
 
Amazon Redshift로 데이터웨어하우스(DW) 구축하기
Amazon Redshift로 데이터웨어하우스(DW) 구축하기Amazon Redshift로 데이터웨어하우스(DW) 구축하기
Amazon Redshift로 데이터웨어하우스(DW) 구축하기Amazon Web Services Korea
 
Amazon SageMaker 모델 배포 방법 소개::김대근, AI/ML 스페셜리스트 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나
Amazon SageMaker 모델 배포 방법 소개::김대근, AI/ML 스페셜리스트 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나Amazon SageMaker 모델 배포 방법 소개::김대근, AI/ML 스페셜리스트 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나
Amazon SageMaker 모델 배포 방법 소개::김대근, AI/ML 스페셜리스트 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나Amazon Web Services Korea
 
Amazon S3 이미지 온디맨드 리사이징을 통한 70% 서버 비용 줄이기 - AWS Summit Seoul 2017
Amazon S3 이미지 온디맨드 리사이징을 통한 70% 서버 비용 줄이기 - AWS Summit Seoul 2017Amazon S3 이미지 온디맨드 리사이징을 통한 70% 서버 비용 줄이기 - AWS Summit Seoul 2017
Amazon S3 이미지 온디맨드 리사이징을 통한 70% 서버 비용 줄이기 - AWS Summit Seoul 2017Amazon Web Services Korea
 
AWS 고객이 주로 겪는 운영 이슈에 대한 해법-AWS Summit Seoul 2017
AWS 고객이 주로 겪는 운영 이슈에 대한 해법-AWS Summit Seoul 2017AWS 고객이 주로 겪는 운영 이슈에 대한 해법-AWS Summit Seoul 2017
AWS 고객이 주로 겪는 운영 이슈에 대한 해법-AWS Summit Seoul 2017Amazon Web Services Korea
 
비용 관점에서 AWS 클라우드 아키텍처 디자인하기::류한진::AWS Summit Seoul 2018
비용 관점에서 AWS 클라우드 아키텍처 디자인하기::류한진::AWS Summit Seoul 2018비용 관점에서 AWS 클라우드 아키텍처 디자인하기::류한진::AWS Summit Seoul 2018
비용 관점에서 AWS 클라우드 아키텍처 디자인하기::류한진::AWS Summit Seoul 2018Amazon Web Services Korea
 
Curso de Java Persistence API (JPA) (Java EE 7)
Curso de Java Persistence API (JPA) (Java EE 7)Curso de Java Persistence API (JPA) (Java EE 7)
Curso de Java Persistence API (JPA) (Java EE 7)Helder da Rocha
 
효율적인 빅데이터 분석 및 처리를 위한 Glue, EMR 활용 - 김태현 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019
효율적인 빅데이터 분석 및 처리를 위한 Glue, EMR 활용 - 김태현 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019효율적인 빅데이터 분석 및 처리를 위한 Glue, EMR 활용 - 김태현 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019
효율적인 빅데이터 분석 및 처리를 위한 Glue, EMR 활용 - 김태현 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019Amazon Web Services Korea
 
CQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationCQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationBrian Ritchie
 
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or LessAmazon Web Services
 
[Spring Camp 2018] 11번가 Spring Cloud 기반 MSA로의 전환 : 지난 1년간의 이야기
[Spring Camp 2018] 11번가 Spring Cloud 기반 MSA로의 전환 : 지난 1년간의 이야기[Spring Camp 2018] 11번가 Spring Cloud 기반 MSA로의 전환 : 지난 1년간의 이야기
[Spring Camp 2018] 11번가 Spring Cloud 기반 MSA로의 전환 : 지난 1년간의 이야기YongSung Yoon
 
Amazon S3 Best Practice and Tuning for Hadoop/Spark in the Cloud
Amazon S3 Best Practice and Tuning for Hadoop/Spark in the CloudAmazon S3 Best Practice and Tuning for Hadoop/Spark in the Cloud
Amazon S3 Best Practice and Tuning for Hadoop/Spark in the CloudNoritaka Sekiyama
 
Airflow를 이용한 데이터 Workflow 관리
Airflow를 이용한  데이터 Workflow 관리Airflow를 이용한  데이터 Workflow 관리
Airflow를 이용한 데이터 Workflow 관리YoungHeon (Roy) Kim
 
클라우드 기반 AWS 데이터베이스 선택 옵션 - AWS Summit Seoul 2017
클라우드 기반 AWS 데이터베이스 선택 옵션 - AWS Summit Seoul 2017 클라우드 기반 AWS 데이터베이스 선택 옵션 - AWS Summit Seoul 2017
클라우드 기반 AWS 데이터베이스 선택 옵션 - AWS Summit Seoul 2017 Amazon Web Services Korea
 
Amazon RDS Proxy 집중 탐구 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon RDS Proxy 집중 탐구 - 윤석찬 :: AWS Unboxing 온라인 세미나Amazon RDS Proxy 집중 탐구 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon RDS Proxy 집중 탐구 - 윤석찬 :: AWS Unboxing 온라인 세미나Amazon Web Services Korea
 

What's hot (20)

데브시스터즈 데이터 레이크 구축 이야기 : Data Lake architecture case study (박주홍 데이터 분석 및 인프라 팀...
데브시스터즈 데이터 레이크 구축 이야기 : Data Lake architecture case study (박주홍 데이터 분석 및 인프라 팀...데브시스터즈 데이터 레이크 구축 이야기 : Data Lake architecture case study (박주홍 데이터 분석 및 인프라 팀...
데브시스터즈 데이터 레이크 구축 이야기 : Data Lake architecture case study (박주홍 데이터 분석 및 인프라 팀...
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
 
글로벌 기업들의 효과적인 데이터 분석을 위한 Data Lake 구축 및 분석 사례 - 김준형 (AWS 솔루션즈 아키텍트)
글로벌 기업들의 효과적인 데이터 분석을 위한 Data Lake 구축 및 분석 사례 - 김준형 (AWS 솔루션즈 아키텍트)글로벌 기업들의 효과적인 데이터 분석을 위한 Data Lake 구축 및 분석 사례 - 김준형 (AWS 솔루션즈 아키텍트)
글로벌 기업들의 효과적인 데이터 분석을 위한 Data Lake 구축 및 분석 사례 - 김준형 (AWS 솔루션즈 아키텍트)
 
Amazon Redshift로 데이터웨어하우스(DW) 구축하기
Amazon Redshift로 데이터웨어하우스(DW) 구축하기Amazon Redshift로 데이터웨어하우스(DW) 구축하기
Amazon Redshift로 데이터웨어하우스(DW) 구축하기
 
Amazon SageMaker 모델 배포 방법 소개::김대근, AI/ML 스페셜리스트 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나
Amazon SageMaker 모델 배포 방법 소개::김대근, AI/ML 스페셜리스트 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나Amazon SageMaker 모델 배포 방법 소개::김대근, AI/ML 스페셜리스트 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나
Amazon SageMaker 모델 배포 방법 소개::김대근, AI/ML 스페셜리스트 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나
 
Amazon S3 이미지 온디맨드 리사이징을 통한 70% 서버 비용 줄이기 - AWS Summit Seoul 2017
Amazon S3 이미지 온디맨드 리사이징을 통한 70% 서버 비용 줄이기 - AWS Summit Seoul 2017Amazon S3 이미지 온디맨드 리사이징을 통한 70% 서버 비용 줄이기 - AWS Summit Seoul 2017
Amazon S3 이미지 온디맨드 리사이징을 통한 70% 서버 비용 줄이기 - AWS Summit Seoul 2017
 
AWS 고객이 주로 겪는 운영 이슈에 대한 해법-AWS Summit Seoul 2017
AWS 고객이 주로 겪는 운영 이슈에 대한 해법-AWS Summit Seoul 2017AWS 고객이 주로 겪는 운영 이슈에 대한 해법-AWS Summit Seoul 2017
AWS 고객이 주로 겪는 운영 이슈에 대한 해법-AWS Summit Seoul 2017
 
비용 관점에서 AWS 클라우드 아키텍처 디자인하기::류한진::AWS Summit Seoul 2018
비용 관점에서 AWS 클라우드 아키텍처 디자인하기::류한진::AWS Summit Seoul 2018비용 관점에서 AWS 클라우드 아키텍처 디자인하기::류한진::AWS Summit Seoul 2018
비용 관점에서 AWS 클라우드 아키텍처 디자인하기::류한진::AWS Summit Seoul 2018
 
Curso de Java Persistence API (JPA) (Java EE 7)
Curso de Java Persistence API (JPA) (Java EE 7)Curso de Java Persistence API (JPA) (Java EE 7)
Curso de Java Persistence API (JPA) (Java EE 7)
 
효율적인 빅데이터 분석 및 처리를 위한 Glue, EMR 활용 - 김태현 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019
효율적인 빅데이터 분석 및 처리를 위한 Glue, EMR 활용 - 김태현 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019효율적인 빅데이터 분석 및 처리를 위한 Glue, EMR 활용 - 김태현 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019
효율적인 빅데이터 분석 및 처리를 위한 Glue, EMR 활용 - 김태현 솔루션즈 아키텍트, AWS :: AWS Summit Seoul 2019
 
CQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationCQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility Segregation
 
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less
 
[Spring Camp 2018] 11번가 Spring Cloud 기반 MSA로의 전환 : 지난 1년간의 이야기
[Spring Camp 2018] 11번가 Spring Cloud 기반 MSA로의 전환 : 지난 1년간의 이야기[Spring Camp 2018] 11번가 Spring Cloud 기반 MSA로의 전환 : 지난 1년간의 이야기
[Spring Camp 2018] 11번가 Spring Cloud 기반 MSA로의 전환 : 지난 1년간의 이야기
 
Amazon S3 Best Practice and Tuning for Hadoop/Spark in the Cloud
Amazon S3 Best Practice and Tuning for Hadoop/Spark in the CloudAmazon S3 Best Practice and Tuning for Hadoop/Spark in the Cloud
Amazon S3 Best Practice and Tuning for Hadoop/Spark in the Cloud
 
Amazon EMR Masterclass
Amazon EMR MasterclassAmazon EMR Masterclass
Amazon EMR Masterclass
 
Airflow를 이용한 데이터 Workflow 관리
Airflow를 이용한  데이터 Workflow 관리Airflow를 이용한  데이터 Workflow 관리
Airflow를 이용한 데이터 Workflow 관리
 
Introduction to Amazon Athena
Introduction to Amazon AthenaIntroduction to Amazon Athena
Introduction to Amazon Athena
 
클라우드 기반 AWS 데이터베이스 선택 옵션 - AWS Summit Seoul 2017
클라우드 기반 AWS 데이터베이스 선택 옵션 - AWS Summit Seoul 2017 클라우드 기반 AWS 데이터베이스 선택 옵션 - AWS Summit Seoul 2017
클라우드 기반 AWS 데이터베이스 선택 옵션 - AWS Summit Seoul 2017
 
Amazon RDS Proxy 집중 탐구 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon RDS Proxy 집중 탐구 - 윤석찬 :: AWS Unboxing 온라인 세미나Amazon RDS Proxy 집중 탐구 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon RDS Proxy 집중 탐구 - 윤석찬 :: AWS Unboxing 온라인 세미나
 

Viewers also liked

Developing Software As A Service App with Python & Django
Developing Software As A Service App with Python & DjangoDeveloping Software As A Service App with Python & Django
Developing Software As A Service App with Python & DjangoAllan Mangune
 
Moving from Django Apps to Services
Moving from Django Apps to ServicesMoving from Django Apps to Services
Moving from Django Apps to ServicesCraig Kerstiens
 
Django multi-tier
Django multi-tierDjango multi-tier
Django multi-tiersmirolo
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of DjangoJacob Kaplan-Moss
 
Django Multi-DB in Anger
Django Multi-DB in AngerDjango Multi-DB in Anger
Django Multi-DB in AngerLoren Davie
 
12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best PracticesDavid Arcos
 
Postgres performance for humans
Postgres performance for humansPostgres performance for humans
Postgres performance for humansCraig Kerstiens
 
2012 07 making disqus realtime@euro python
2012 07 making disqus realtime@euro python2012 07 making disqus realtime@euro python
2012 07 making disqus realtime@euro pythonAdam Hitchcock
 
Visdjango presentation django_boston_oct_2014
Visdjango presentation django_boston_oct_2014Visdjango presentation django_boston_oct_2014
Visdjango presentation django_boston_oct_2014jlbaldwin
 
Django shop
Django shopDjango shop
Django shopTribaal
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blogPierre Sudron
 
Django Interview Questions and Answers
Django Interview Questions and AnswersDjango Interview Questions and Answers
Django Interview Questions and AnswersPython Devloper
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to djangoIlian Iliev
 
Big o notation
Big o notationBig o notation
Big o notationkeb97
 
ZCA: A component architecture for Python
ZCA: A component architecture for PythonZCA: A component architecture for Python
ZCA: A component architecture for PythonTimo Stollenwerk
 
Dev/Test Scenarios in the DevOps World
Dev/Test Scenarios in the DevOps WorldDev/Test Scenarios in the DevOps World
Dev/Test Scenarios in the DevOps WorldPranav Ainavolu
 
LCNUG 2015 - what's new for agile teams in TFS 2015
LCNUG 2015 -  what's new for agile teams in TFS 2015LCNUG 2015 -  what's new for agile teams in TFS 2015
LCNUG 2015 - what's new for agile teams in TFS 2015Angela Dugan
 

Viewers also liked (20)

Developing Software As A Service App with Python & Django
Developing Software As A Service App with Python & DjangoDeveloping Software As A Service App with Python & Django
Developing Software As A Service App with Python & Django
 
Moving from Django Apps to Services
Moving from Django Apps to ServicesMoving from Django Apps to Services
Moving from Django Apps to Services
 
Django multi-tier
Django multi-tierDjango multi-tier
Django multi-tier
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
Django Multi-DB in Anger
Django Multi-DB in AngerDjango Multi-DB in Anger
Django Multi-DB in Anger
 
12 tips on Django Best Practices
12 tips on Django Best Practices12 tips on Django Best Practices
12 tips on Django Best Practices
 
Postgres performance for humans
Postgres performance for humansPostgres performance for humans
Postgres performance for humans
 
2012 07 making disqus realtime@euro python
2012 07 making disqus realtime@euro python2012 07 making disqus realtime@euro python
2012 07 making disqus realtime@euro python
 
Visdjango presentation django_boston_oct_2014
Visdjango presentation django_boston_oct_2014Visdjango presentation django_boston_oct_2014
Visdjango presentation django_boston_oct_2014
 
dJango
dJangodJango
dJango
 
Django shop
Django shopDjango shop
Django shop
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
 
Django in Windows
Django in WindowsDjango in Windows
Django in Windows
 
Django Interview Questions and Answers
Django Interview Questions and AnswersDjango Interview Questions and Answers
Django Interview Questions and Answers
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Big o notation
Big o notationBig o notation
Big o notation
 
ZCA: A component architecture for Python
ZCA: A component architecture for PythonZCA: A component architecture for Python
ZCA: A component architecture for Python
 
Dev/Test Scenarios in the DevOps World
Dev/Test Scenarios in the DevOps WorldDev/Test Scenarios in the DevOps World
Dev/Test Scenarios in the DevOps World
 
LCNUG 2015 - what's new for agile teams in TFS 2015
LCNUG 2015 -  what's new for agile teams in TFS 2015LCNUG 2015 -  what's new for agile teams in TFS 2015
LCNUG 2015 - what's new for agile teams in TFS 2015
 
Intro django
Intro djangoIntro django
Intro django
 

Similar to Multi Tenancy With Python and Django

Getting data into Rudder
Getting data into RudderGetting data into Rudder
Getting data into RudderRUDDER
 
Cloud Meetup - Automation in the Cloud
Cloud Meetup - Automation in the CloudCloud Meetup - Automation in the Cloud
Cloud Meetup - Automation in the Cloudpetriojala123
 
Infrastructure as Code with Terraform
Infrastructure as Code with TerraformInfrastructure as Code with Terraform
Infrastructure as Code with TerraformPedro J. Molina
 
Building a multitenant application with Django
Building a multitenant application with DjangoBuilding a multitenant application with Django
Building a multitenant application with DjangoADEDAMOLA ADEDAPO
 
Centralized Application Configuration with Spring and Apache Zookeeper
Centralized Application Configuration with Spring and Apache ZookeeperCentralized Application Configuration with Spring and Apache Zookeeper
Centralized Application Configuration with Spring and Apache ZookeeperRyan Gardner
 
Decoupled Libraries for PHP
Decoupled Libraries for PHPDecoupled Libraries for PHP
Decoupled Libraries for PHPPaul Jones
 
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdfSchema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdfseo18
 
Case Study _Cloud Native Transformation Deploying Integration workloads to AK...
Case Study _Cloud Native Transformation Deploying Integration workloads to AK...Case Study _Cloud Native Transformation Deploying Integration workloads to AK...
Case Study _Cloud Native Transformation Deploying Integration workloads to AK...Srikanth Prathipati
 
Configuration Management and Transforming Legacy Applications in the Enterpri...
Configuration Management and Transforming Legacy Applications in the Enterpri...Configuration Management and Transforming Legacy Applications in the Enterpri...
Configuration Management and Transforming Legacy Applications in the Enterpri...Docker, Inc.
 
Practical advice on deployment and management of enterprise workloads
Practical advice on deployment and management of enterprise workloadsPractical advice on deployment and management of enterprise workloads
Practical advice on deployment and management of enterprise workloadsJarek Miszczyk
 
AAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
AAI-3218 Production Deployment Best Practices for WebSphere Liberty ProfileAAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
AAI-3218 Production Deployment Best Practices for WebSphere Liberty ProfileWASdev Community
 
Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02arghya007
 
Using puppet
Using puppetUsing puppet
Using puppetAlex Su
 
Domain Access Module
Domain Access ModuleDomain Access Module
Domain Access ModuleRyan Cross
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
Achieve big data analytic platform with lambda architecture on cloud
Achieve big data analytic platform with lambda architecture on cloudAchieve big data analytic platform with lambda architecture on cloud
Achieve big data analytic platform with lambda architecture on cloudScott Miao
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsMarcelo Pinheiro
 
Solid fire cloudstack storage overview - CloudStack European User Group
Solid fire cloudstack storage overview - CloudStack European User GroupSolid fire cloudstack storage overview - CloudStack European User Group
Solid fire cloudstack storage overview - CloudStack European User GroupShapeBlue
 

Similar to Multi Tenancy With Python and Django (20)

Getting data into Rudder
Getting data into RudderGetting data into Rudder
Getting data into Rudder
 
Cloud Meetup - Automation in the Cloud
Cloud Meetup - Automation in the CloudCloud Meetup - Automation in the Cloud
Cloud Meetup - Automation in the Cloud
 
Infrastructure as Code with Terraform
Infrastructure as Code with TerraformInfrastructure as Code with Terraform
Infrastructure as Code with Terraform
 
Pyramid patterns
Pyramid patternsPyramid patterns
Pyramid patterns
 
Building a multitenant application with Django
Building a multitenant application with DjangoBuilding a multitenant application with Django
Building a multitenant application with Django
 
Centralized Application Configuration with Spring and Apache Zookeeper
Centralized Application Configuration with Spring and Apache ZookeeperCentralized Application Configuration with Spring and Apache Zookeeper
Centralized Application Configuration with Spring and Apache Zookeeper
 
Decoupled Libraries for PHP
Decoupled Libraries for PHPDecoupled Libraries for PHP
Decoupled Libraries for PHP
 
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdfSchema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
Schema-based multi-tenant architecture using Quarkus & Hibernate-ORM.pdf
 
Case Study _Cloud Native Transformation Deploying Integration workloads to AK...
Case Study _Cloud Native Transformation Deploying Integration workloads to AK...Case Study _Cloud Native Transformation Deploying Integration workloads to AK...
Case Study _Cloud Native Transformation Deploying Integration workloads to AK...
 
Configuration Management and Transforming Legacy Applications in the Enterpri...
Configuration Management and Transforming Legacy Applications in the Enterpri...Configuration Management and Transforming Legacy Applications in the Enterpri...
Configuration Management and Transforming Legacy Applications in the Enterpri...
 
Practical advice on deployment and management of enterprise workloads
Practical advice on deployment and management of enterprise workloadsPractical advice on deployment and management of enterprise workloads
Practical advice on deployment and management of enterprise workloads
 
AAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
AAI-3218 Production Deployment Best Practices for WebSphere Liberty ProfileAAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
AAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
 
Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02Red5workshop 090619073420-phpapp02
Red5workshop 090619073420-phpapp02
 
Using puppet
Using puppetUsing puppet
Using puppet
 
Django
DjangoDjango
Django
 
Domain Access Module
Domain Access ModuleDomain Access Module
Domain Access Module
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Achieve big data analytic platform with lambda architecture on cloud
Achieve big data analytic platform with lambda architecture on cloudAchieve big data analytic platform with lambda architecture on cloud
Achieve big data analytic platform with lambda architecture on cloud
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
 
Solid fire cloudstack storage overview - CloudStack European User Group
Solid fire cloudstack storage overview - CloudStack European User GroupSolid fire cloudstack storage overview - CloudStack European User Group
Solid fire cloudstack storage overview - CloudStack European User Group
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Multi Tenancy With Python and Django

  • 1. Multi-Tenancy With Django Scott Crespo Software Engineer Director, Orlando Data Science Scott@OrlandoDS.com
  • 2. 1. Multi-Tenant Architectures 2. Django Tenant Schemas Explained 3. Basic Use + Tips and Tricks
  • 3. Definition Multi-Tenancy: A software architecture where a single application instance enables multiple organizations (tenants) to view their data. *This is a key component of XaaS (i.e. Something as a Service)
  • 4. Architectures Multi-tenant architectures can be placed on a continuum Shared Separate
  • 5. Common Approaches to Multi-Tenancy
  • 6. Shared Architecutre One Database + One Schema One database instance, and one public schema serve all tenants. Pros - Easy to build if data layer is simple - Every user on same domain (might be desirable) - Only use if a Tenant has exactly one user. Cons - Expensive (Makes lots of calls to db for tenant object)
  • 7. Isolated Architecture Multiple Databases Each tenant has their own database instance Pros - Most Secure - Easier disaster recovery - Not expensive for compute resources Cons - Difficult to scale - Expensive storage resources - Difficult to share data across tenants
  • 8. Hybrid Architecture One Database – Multiple Schemas One database instance for all tenants. Each tenant gets a dedicated schema. Shared 'public' schema Dedicated 'tenant' schema
  • 9. What's a Schema? Acts as a namespace in Postgres Adds an additional layer of organization/isolation to the database (Database → Schema → Table) ex) SELECT * FROM schema_name.table When a schema is not specified in the connection or query – only the 'public' schema is accessed Schemas to be queried can be specified in the app's database connection via 'SEARCH_PATH' parameter
  • 10. One Database – Multiple Schemas Pros - Scalable - Cheap - Simple - Semi-secure - Sharable Cons - Difficult disaster recovery - Less-secure than dedicated db's
  • 11. Django Tenant Schemas Implements Multi-Schema Approach Requires PostgreSQL Installation: $ pip install django-tenant-schemas Docs: Django-tenant-schemas.readthedocs.org
  • 13. The Tenant Object Stored on the 'public' schema Contains 2 Critical Fields - domain_url – the tenant's domain (foo.bar.com) - schema_name – the schema where the Tenant's isolated data is stored (tenant_jw8j23jp)
  • 14. Request Routing 1.User makes a request 2.Middleware looks up tenant object on the public schema and returns schema_name Tenant.objects.get(domain=request.domain).schema_name 1.Tenant_Schema's database wrapper adds schema_name to the connection's SEARCH_PATH cursor.execute('SET search_path = public, schema_name') 1.Subsequent Requests include schema_name in the search path
  • 15.
  • 16. Basic Use Settings.py Specify TENANT and SHARED apps  Caution! Don't include new tenant registration on tenants' apps Use the tenant_schemas postgres backend Use the tenant schemas middleware
  • 17. Basic use models.py  Create a tenant app that contains your tenant model (i.e. organization, company, etc).  Use tenant_schema's mixin - domain_url - schema_name from tenant_schemas.models import TenantMixin class Company(TenantMixin) company_name =models.CharField(max_length=255L) about = models.TextField(blank=True) auto_create_schema = True
  • 18. The app containing your tenant model should remain in the project's root directory. Otherwise tenant_schemas can't find it. |-- apps | |-- __init__.py | |-- app1 | |-- app2 | |-- app3 |-- Project | |-- __init__.py | |-- settings.py | |-- settings.pyc | |-- urls.py | `-- wsgi.py |-- manage.py `-- tenant |-- admin.py |-- __init__.py |-- models.py |-- tests.py `-- views.py * you could try simlinks as a work-around, but not recommended
  • 19. Basic Use Command Line & DNS Use tenant_schemas command wrapper for db commands  Use sync_schemas and migrate_schemas  DO NOT use syncdb or migrate Server & DNS - Make sure to use subdomain wildcards
  • 20. Basic Use Custom Commands Create a 'make_tenants' custom command - Must create a public tenant and a private tenant to complete creation of the database
  • 21. Custom Command: make_tenants.py from lawfirm.models import LawFirm from django.core.management.base import NoArgsCommand import os if os.environ['DJANGO_SETTINGS_MODULE'] == 'settings.base': from settings.base import BASE_URL else: from settings.dev import BASE_URL class Command(NoArgsCommand): def handle_noargs(self,**options): # create your public tenant LawFirm(domain_url=BASE_URL, schema_name='public', firm_name='LawCRM', ).save() #test tenant to verify sub-domain routing LawFirm(domain_url='test.'+BASE_URL, schema_name='test', firm_name='Test Firm', ).save()
  • 22. Schema Naming Schemes Auto-generate tenant schema names and enforce uniqueness. Prefix with 'tenant_' Append a hash to the end *Schema name must begin with a letter, $, or underscore Example Database: - public - test dev
  • 23. Modify Search Path on the Fly (this took time to figure out) from django.db import connection connection.set_tenant(tenant) # set_tenant() accepts tenant object, NOT # tenant_name!
  • 24. Important Decision Tenant Model on Public Schema User Model on Public Schema - Easy - Less Secure - User More Portable Tenant Model on Public Schema User Model on Private Schema - Not so easy - More secure - User Less Portable VS
  • 25. Thanks! Scott Crespo scott@orlandods.com