SlideShare a Scribd company logo
1 of 35
Multi-tenant Laravel
How to build a SaaS application with separated databases
Intro
Peter Mein
Lead Developer at Rapide Internet
Laravel
API’s
DevOps
K8’s
At the controls:
Lucas van der Have
Senior Developer bij DossierData
Saas? Tenants?
What is SaaS?
What is a tenant?
Saas? Tenants?
What is SaaS?
What is a tenant?
Saas? Tenants?
What is SaaS?
What is a tenant?
The principle of multi-tenancy is about a single piece of software
serving multiple tenants.
Why?
To maintain and service individual customer better
Examples
● CTIP 120+ tables, 50+ tenants, 20m+ geoobjects, total 50gb, single database
● DossierData, 150+ tables, 200+ tenants averaging 1Gb - 5Gb per db
● MKA, 100+ tables, 200+ tenants, 2m+ chatberichten
Multi-tenant !== Multi-website
Multi-tenant
1 application codebase serving multiple customers with a distinct dataset
i.e. GMail, Facebook or LinkedIn
Multi-website
1 application codebase serving multiple websites/fronts
i.e. Magento
Single database
Multi-tenant
Database Layout
Example of table structure
Master database RO
Shared database RW
Tenant database RW / RO
Separated database
#deepdive
Request lifecycle
- Request
- Middleware
- Setup tenant connection
- Controller
- Call models from the tenant db
- Call models from a shared or master database
- Inter database relations
- Fire a tenant event
- Return response
Setup tenant connection
Determine tenant
Encryption
Changing configs on the fly
Setup tenant connection
Determine tenant
Encryption
Changing configs on the fly
Setup tenant connection
public function getTenant()
{
$subdomain = $this->getSubdomain();
if ($this->tenant !== null) {
return $this->tenant;
}
return $this->tenant = $this->tenantRepository->findBySubdomain($subdomain);
}
Services/TenantService.php
Setup tenant connection
Determine tenant
Encryption
Changing configs on the fly
Setup tenant connection
private function getDatabaseCredentialsByTenant(Tenant $tenant): array
{
return [
'hostname' => $tenant->db_host,
'database' => $this->encrypter->decrypt($tenant->db_name),
'username' => $this->encrypter->decrypt($tenant->db_user),
'password' => $this->encrypter->decrypt($tenant->db_pass),
];
}
Services/TenantService.php
Setup tenant connection
Determine tenant
Encryption
Changing configs on the fly
Setup tenant connection
public function connect(Tenant $tenant = null): bool
{
if ($tenant === null) {
return false;
}
list($hostname, $database, $username, $password) = $this->getDatabaseCredentialsByTenant($tenant);
// Update tenant connection configs
$this->updateConnectionDetails('tenant_database', $hostname, $database, $username, $password);
// Set to shared hostname to same as tenant database, necessary for migration to Galera
$this->updateConnectionDetails('shared_database', $hostname);
$this->reconnectConnection('shared_database');
$this->connection = $this->reconnectConnection('mysql');
return true;
}
Services/ConnectionService.php
Setup tenant connection
protected function updateConnectionDetails($connection, $hostname, $database = null, $username = null, $password = null)
{
$settingKey = sprintf('database.connections.%s', $connection);
config(sprintf('%s.host', $settingKey), $hostname);
if ($database !== null) {
config(sprintf('%s.database', $settingKey), $database);
}
if ($username !== null) {
config(sprintf('%s.username', $settingKey), $username);
}
if ($password !== null) {
config(sprintf('%s.password', $settingKey), $password);
}
}
Services/ConnectionService.php
Call model from the tenant db
- Primary connection
- Call model as normally
i.e.
- Model::find(1);
Call model from shared or master db
- Switch connection of a model or set the default connection on the model
- Retrieve the model using eloquent
Call model from shared or master db
class Permission extends Model
{
public function getConnectionName()
{
return 'shared_database';
}
protected $fillable = [
'name',
'description',
'policy'
];
}
Models/Permission.php
Inter database relations
- A Role has many Permissions
- Permissions are stored in shared db
- Laravel limitations and how to fix them
- Direction of relations
SELECT * FROM tenant_database.users AS u
JOIN tenant_database.users_roles AS ur ON u.id = ur.user_id
JOIN shared_database.roles AS r ON ur.role_id = r.id
WHERE u.id = 1;
Call model from shared or master db
class Permission extends Model
{
...
private function getTableNameForConnection($table, $connection = null)
{
return vsprintf('%s.%s', [$this->getDatabaseNameForConnection($connection), $table]);
}
public function roles()
{
return $this->belongsToMany(
AppModelsRole::class,
$this->getTableNameForConnection('role_permissions', 'tenant_database'),
'permission_id',
'role_id'
);
}
...
}
Models/Permission.php
Fire an event
- Only a problem on Async listeners
- Needs a tenant to run
Fire an event
abstract class TenantEvent extends Event
{
public function __construct()
{
if (($tenant = $this->getTenantService()->getTenant()) instanceof Tenant) {
$this->setTenant($tenant);
} else {
throw new MissingTenantException();
}
}
public function __sleep()
{
// Unset tenant model for serialization
$this->tenant = null;
// Continue with sleep
return parent::__sleep();
}
public function __wakeup()
{
// Fetch the tenant by id
$this->tenant = $this->getTenantService()->find($this->tenantId);
$this->tenantId = $this->tenant->id;
// Initialize tenant database connection
$this->getTenantManager()->connect($this->tenant);
// Continue with wake up
parent::__wakeup();
}
}
Abstracts/TenantEvent.php
Warnings
Everything outside the request lifecycle requires manual tenant switching
Cache
Broadcast
Storage
Queues
Inter database relations and connections to be used
Cross connection transactions
Pro’s & Con’s
Backups per tenant
Easy recovery
GDPR
Scalability
Manageability (migrating to new db environment)
Overhead
Complexer logic for built in laravel functions:
- Commands
- Events
- Queues
- Broadcasting
Planning ahead
Server layout
Layer 4 load balancing
Packages
I don’t want to do this all by myself:
https://github.com/hyn/multi-tenant ★1143
https://github.com/orchestral/tenanti ★406
https://github.com/HipsterJazzbo/Landlord ★525
Andere onderwerpen
● Laravel API's and their limitations
● Strangling Laravel with react
● Deploying Laravel to production (With CI)
● Error handling in Laravel with channels and sentry
● Oauth2 implementation with passport (and what its missing)
● Laravel and Kubernetes
● Local development with Docker
● Broadcasting to the world
● Storage in the cloud, and efficient image retrieval (Thumbor and S3)
● Unit testing, Integration testing, Browser testing
● Package development and contributing to open source
● Modular laravel; simulate microservices
https://sli.do #F294
Questions?
Thank you

More Related Content

What's hot

Mandatory access control for information security
Mandatory access control for information securityMandatory access control for information security
Mandatory access control for information securityAjit Dadresa
 
Anti forensic
Anti forensicAnti forensic
Anti forensicMilap Oza
 
Security and Viruses
Security and VirusesSecurity and Viruses
Security and VirusesAmrit Kaur
 
Security in cloud computing
Security in cloud computingSecurity in cloud computing
Security in cloud computingveena venugopal
 
Search problems in Artificial Intelligence
Search problems in Artificial IntelligenceSearch problems in Artificial Intelligence
Search problems in Artificial Intelligenceananth
 
Introduction to Expert Systems {Artificial Intelligence}
Introduction to Expert Systems {Artificial Intelligence}Introduction to Expert Systems {Artificial Intelligence}
Introduction to Expert Systems {Artificial Intelligence}FellowBuddy.com
 
Goal stack planning.ppt
Goal stack planning.pptGoal stack planning.ppt
Goal stack planning.pptSadagopanS
 
Artificial Intelligence 1 Planning In The Real World
Artificial Intelligence 1 Planning In The Real WorldArtificial Intelligence 1 Planning In The Real World
Artificial Intelligence 1 Planning In The Real Worldahmad bassiouny
 
Password strength svm
Password strength svmPassword strength svm
Password strength svmSunil Rm
 
Artificial Intelligence -- Search Algorithms
Artificial Intelligence-- Search Algorithms Artificial Intelligence-- Search Algorithms
Artificial Intelligence -- Search Algorithms Syed Ahmed
 
Practical Malware Analysis: Ch 11: Malware Behavior
Practical Malware Analysis: Ch 11: Malware BehaviorPractical Malware Analysis: Ch 11: Malware Behavior
Practical Malware Analysis: Ch 11: Malware BehaviorSam Bowne
 
Bakery Algorithm
Bakery Algorithm Bakery Algorithm
Bakery Algorithm thededar
 
Expert System Full Details
Expert System Full DetailsExpert System Full Details
Expert System Full Detailsssbd6985
 
x.509-Directory Authentication Service
x.509-Directory Authentication Servicex.509-Directory Authentication Service
x.509-Directory Authentication ServiceSwathy T
 

What's hot (20)

Mandatory access control for information security
Mandatory access control for information securityMandatory access control for information security
Mandatory access control for information security
 
Anti forensic
Anti forensicAnti forensic
Anti forensic
 
Security and Viruses
Security and VirusesSecurity and Viruses
Security and Viruses
 
Security in cloud computing
Security in cloud computingSecurity in cloud computing
Security in cloud computing
 
Predicate logic
 Predicate logic Predicate logic
Predicate logic
 
Search problems in Artificial Intelligence
Search problems in Artificial IntelligenceSearch problems in Artificial Intelligence
Search problems in Artificial Intelligence
 
Chapter 5 - Identity Management
Chapter 5 - Identity ManagementChapter 5 - Identity Management
Chapter 5 - Identity Management
 
Digital forensics
Digital forensicsDigital forensics
Digital forensics
 
Uncertainty in AI
Uncertainty in AIUncertainty in AI
Uncertainty in AI
 
Introduction to Expert Systems {Artificial Intelligence}
Introduction to Expert Systems {Artificial Intelligence}Introduction to Expert Systems {Artificial Intelligence}
Introduction to Expert Systems {Artificial Intelligence}
 
Goal stack planning.ppt
Goal stack planning.pptGoal stack planning.ppt
Goal stack planning.ppt
 
Artificial Intelligence 1 Planning In The Real World
Artificial Intelligence 1 Planning In The Real WorldArtificial Intelligence 1 Planning In The Real World
Artificial Intelligence 1 Planning In The Real World
 
Password strength svm
Password strength svmPassword strength svm
Password strength svm
 
Artificial Intelligence -- Search Algorithms
Artificial Intelligence-- Search Algorithms Artificial Intelligence-- Search Algorithms
Artificial Intelligence -- Search Algorithms
 
Public key Infrastructure (PKI)
Public key Infrastructure (PKI)Public key Infrastructure (PKI)
Public key Infrastructure (PKI)
 
Practical Malware Analysis: Ch 11: Malware Behavior
Practical Malware Analysis: Ch 11: Malware BehaviorPractical Malware Analysis: Ch 11: Malware Behavior
Practical Malware Analysis: Ch 11: Malware Behavior
 
Reasoning in AI
Reasoning in AIReasoning in AI
Reasoning in AI
 
Bakery Algorithm
Bakery Algorithm Bakery Algorithm
Bakery Algorithm
 
Expert System Full Details
Expert System Full DetailsExpert System Full Details
Expert System Full Details
 
x.509-Directory Authentication Service
x.509-Directory Authentication Servicex.509-Directory Authentication Service
x.509-Directory Authentication Service
 

Similar to Multi tenant laravel

Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Shinya Ohyanagi
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统yiditushe
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebookguoqing75
 
REST more with json-api and fractal
REST more with json-api and fractalREST more with json-api and fractal
REST more with json-api and fractalBoyan Yordanov
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonKris Wallsmith
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 3camp
 
Zendcon 2007 Api Design
Zendcon 2007 Api DesignZendcon 2007 Api Design
Zendcon 2007 Api Designunodelostrece
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioningSource Ministry
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5Darren Craig
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...andrewnacin
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8Alexei Gorobets
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 

Similar to Multi tenant laravel (20)

Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
REST more with json-api and fractal
REST more with json-api and fractalREST more with json-api and fractal
REST more with json-api and fractal
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Fatc
FatcFatc
Fatc
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2
 
Zendcon 2007 Api Design
Zendcon 2007 Api DesignZendcon 2007 Api Design
Zendcon 2007 Api Design
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioning
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 

Recently uploaded

The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

Multi tenant laravel

  • 1. Multi-tenant Laravel How to build a SaaS application with separated databases
  • 2. Intro Peter Mein Lead Developer at Rapide Internet Laravel API’s DevOps K8’s At the controls: Lucas van der Have Senior Developer bij DossierData
  • 3. Saas? Tenants? What is SaaS? What is a tenant?
  • 4. Saas? Tenants? What is SaaS? What is a tenant?
  • 5. Saas? Tenants? What is SaaS? What is a tenant? The principle of multi-tenancy is about a single piece of software serving multiple tenants.
  • 6. Why? To maintain and service individual customer better Examples ● CTIP 120+ tables, 50+ tenants, 20m+ geoobjects, total 50gb, single database ● DossierData, 150+ tables, 200+ tenants averaging 1Gb - 5Gb per db ● MKA, 100+ tables, 200+ tenants, 2m+ chatberichten
  • 7. Multi-tenant !== Multi-website Multi-tenant 1 application codebase serving multiple customers with a distinct dataset i.e. GMail, Facebook or LinkedIn Multi-website 1 application codebase serving multiple websites/fronts i.e. Magento
  • 10. Database Layout Example of table structure Master database RO Shared database RW Tenant database RW / RO
  • 13. Request lifecycle - Request - Middleware - Setup tenant connection - Controller - Call models from the tenant db - Call models from a shared or master database - Inter database relations - Fire a tenant event - Return response
  • 14. Setup tenant connection Determine tenant Encryption Changing configs on the fly
  • 15. Setup tenant connection Determine tenant Encryption Changing configs on the fly
  • 16. Setup tenant connection public function getTenant() { $subdomain = $this->getSubdomain(); if ($this->tenant !== null) { return $this->tenant; } return $this->tenant = $this->tenantRepository->findBySubdomain($subdomain); } Services/TenantService.php
  • 17. Setup tenant connection Determine tenant Encryption Changing configs on the fly
  • 18. Setup tenant connection private function getDatabaseCredentialsByTenant(Tenant $tenant): array { return [ 'hostname' => $tenant->db_host, 'database' => $this->encrypter->decrypt($tenant->db_name), 'username' => $this->encrypter->decrypt($tenant->db_user), 'password' => $this->encrypter->decrypt($tenant->db_pass), ]; } Services/TenantService.php
  • 19. Setup tenant connection Determine tenant Encryption Changing configs on the fly
  • 20. Setup tenant connection public function connect(Tenant $tenant = null): bool { if ($tenant === null) { return false; } list($hostname, $database, $username, $password) = $this->getDatabaseCredentialsByTenant($tenant); // Update tenant connection configs $this->updateConnectionDetails('tenant_database', $hostname, $database, $username, $password); // Set to shared hostname to same as tenant database, necessary for migration to Galera $this->updateConnectionDetails('shared_database', $hostname); $this->reconnectConnection('shared_database'); $this->connection = $this->reconnectConnection('mysql'); return true; } Services/ConnectionService.php
  • 21. Setup tenant connection protected function updateConnectionDetails($connection, $hostname, $database = null, $username = null, $password = null) { $settingKey = sprintf('database.connections.%s', $connection); config(sprintf('%s.host', $settingKey), $hostname); if ($database !== null) { config(sprintf('%s.database', $settingKey), $database); } if ($username !== null) { config(sprintf('%s.username', $settingKey), $username); } if ($password !== null) { config(sprintf('%s.password', $settingKey), $password); } } Services/ConnectionService.php
  • 22. Call model from the tenant db - Primary connection - Call model as normally i.e. - Model::find(1);
  • 23. Call model from shared or master db - Switch connection of a model or set the default connection on the model - Retrieve the model using eloquent
  • 24. Call model from shared or master db class Permission extends Model { public function getConnectionName() { return 'shared_database'; } protected $fillable = [ 'name', 'description', 'policy' ]; } Models/Permission.php
  • 25. Inter database relations - A Role has many Permissions - Permissions are stored in shared db - Laravel limitations and how to fix them - Direction of relations SELECT * FROM tenant_database.users AS u JOIN tenant_database.users_roles AS ur ON u.id = ur.user_id JOIN shared_database.roles AS r ON ur.role_id = r.id WHERE u.id = 1;
  • 26. Call model from shared or master db class Permission extends Model { ... private function getTableNameForConnection($table, $connection = null) { return vsprintf('%s.%s', [$this->getDatabaseNameForConnection($connection), $table]); } public function roles() { return $this->belongsToMany( AppModelsRole::class, $this->getTableNameForConnection('role_permissions', 'tenant_database'), 'permission_id', 'role_id' ); } ... } Models/Permission.php
  • 27. Fire an event - Only a problem on Async listeners - Needs a tenant to run
  • 28. Fire an event abstract class TenantEvent extends Event { public function __construct() { if (($tenant = $this->getTenantService()->getTenant()) instanceof Tenant) { $this->setTenant($tenant); } else { throw new MissingTenantException(); } } public function __sleep() { // Unset tenant model for serialization $this->tenant = null; // Continue with sleep return parent::__sleep(); } public function __wakeup() { // Fetch the tenant by id $this->tenant = $this->getTenantService()->find($this->tenantId); $this->tenantId = $this->tenant->id; // Initialize tenant database connection $this->getTenantManager()->connect($this->tenant); // Continue with wake up parent::__wakeup(); } } Abstracts/TenantEvent.php
  • 29. Warnings Everything outside the request lifecycle requires manual tenant switching Cache Broadcast Storage Queues Inter database relations and connections to be used Cross connection transactions
  • 30. Pro’s & Con’s Backups per tenant Easy recovery GDPR Scalability Manageability (migrating to new db environment) Overhead Complexer logic for built in laravel functions: - Commands - Events - Queues - Broadcasting Planning ahead
  • 31. Server layout Layer 4 load balancing
  • 32. Packages I don’t want to do this all by myself: https://github.com/hyn/multi-tenant ★1143 https://github.com/orchestral/tenanti ★406 https://github.com/HipsterJazzbo/Landlord ★525
  • 33. Andere onderwerpen ● Laravel API's and their limitations ● Strangling Laravel with react ● Deploying Laravel to production (With CI) ● Error handling in Laravel with channels and sentry ● Oauth2 implementation with passport (and what its missing) ● Laravel and Kubernetes ● Local development with Docker ● Broadcasting to the world ● Storage in the cloud, and efficient image retrieval (Thumbor and S3) ● Unit testing, Integration testing, Browser testing ● Package development and contributing to open source ● Modular laravel; simulate microservices https://sli.do #F294

Editor's Notes

  1. Saas is an application that serves multiple people with teh
  2. Scopes for single database
  3. Scopes for single database
  4. Scopes for single database