SlideShare a Scribd company logo
1 of 27
Download to read offline
Business domain isolation
in DB (PostgreSQL)
Andrey Koleshko
@ka8725
When does the problem arise?
● Monolithic application break down to micro-services
● Logical isolation parts of a monolithic application, i.e. split
to modules (e.g. Rails engines)
Note, we will talk about solution for PostgreSQL
Initial state of the system
● Monolithic application
● Production setup
● One DB (PostgreSQL)
● Additional application (e.g. analytics) that only reads data
from the DB
○ This application relies on the current tables structure
○ It relies on some static data, such as enum values
Initial state of the system
● The consumer app relies
on the current tables
structure
● It relies on some static
data, such as enum
values
● Isolate a specific business domain in the DB
● Zero-downtime migration
● As less changes as possible to reduce costs and risks
The goal
● Set of tables that are “hidden” from the main app
Example:
○ Initially DB has tables: users and locations
○ Assume locations is a table from a business domain
○ After:
■ users remains in the main DB
■ locations is “hidden” from users
What is isolated business domain in DB?
The business
domain is a set of
tables that should be
isolated, i.e. “hidden”
from the main DB
The target
Natural solution
Setup a separate DB
and create the
domain tables there,
point all apps to use
this new DB
additionally to the
main DB
Pros
● Full isolation
○ while the business domain
DB fails, the main DB
remains functioning
● Separate configuration
● Separate data
Natural solution: pros and cons
Cons
● Implementation cost
● Maintenance cost
● Complex solution
Natural solution: cons - complex solution
Idea
Isolate the business
domain tables
logically inside DB
● Use schemas
○ https://www.postgresql.org/docs/12/ddl-schemas.html
○ many users use one DB without interfering each other
○ DB objects are organized into logical groups to make
them more manageable
○ third-party applications can be put into separate
schemas not to collide
How to implement this in PostgreSQL?
“Schemas are analogous to directories at the operating
system level, except that schemas cannot be nested.”
Metaphor
Result
● All tables remain in the same DB
● Domains are isolated:
○ public.users
○ business.locations
● Remove foreign keys between the tables
● Create the business schema with necessary tables,
indexes, constraints, foreign keys, etc. inside this schema
● Start writing data into these new tables
● But don’t stop writing into the old tables yet
● Switch all apps to read from the new tables
● Drop the old tables along with all related DB objects
Zero-downtime approach
● Remove foreign keys between the tables
● Create the business schema with necessary tables,
indexes, constraints, foreign keys, etc. inside this schema
● Start writing data into these new tables
● But don’t stop writing into the old tables yet
● Switch all apps to read from the new tables
● Drop the old tables along with all related DB objects
Zero-downtime approach
● Use triggers
○ https://www.postgresql.org/docs/12/trigger-definition.html
○ It’s like callbacks in ActiveRecord, but on DB level
Start writing data into the new tables
Switch to read from the new tables: step 1
Define an
interface
(contract/API)
takes data from
the old tables
and is used by
readers
Write to the
new and old
tables in
parallel
Switch to read from the new tables: step 2
Change the
API to read
from the the
new tables
and drop the
old tables
Switch all apps to read from the new tables: step 3
Note, the new
tables are
namespaced
in a view
● Use views
○ http://www.postgresqltutorial.com/postgresql-views/
○ Consider view as a virtual table reads data from one or
many other tables
○ If the tables used by views change, views fail
automatically - API tests out of box!
○ Enum values should be specified explicitly to avoid
broken API readers
○ Namespace the views in a specific schema
How to implement the API?
create schema api;
create view api.locations as
select
id, lat, lng, status
from public.locations
where public.locations.status =
any(array['completed', 'pending']);
View example
View example caveats
● Expose only data with enums that are known by the Consumer app
(array['completed', 'pending'])
○ If new enum value appears, the Consumer app will have to prepare code
for this and then the row with the new enum value can be exposed
○ This way it guarantees the Consumer app is not broken due to the new
enum value
● Rails was not prepared for that plan
● We’ve patched it:
https://gist.github.com/ka8725/a45214a0e9d93fb7b7072206d7f2d0b4
● Usage example:
dumper = SchemaDumper.new(ActiveRecord::Base.connection)
dumper.dump('api', Rails.root.join('db/api/schema.rb'))
● Created a rake task dumps these custom schemas and put it as a prerequisite
for the standard db:schema:dump
Generate separate schemas for Rails
● Easy to implement and maintain solution
● Rails is not friendly for non-trivial approaches and needs patches
● The final solution works for:
○ monolithic modular applications
○ micro-services
● The API idea is applicable for any app exposes data to internal services
● Follow your thoughts and learn using tools
Summary
Andrey Koleshko
@ka8725
ka8725@gmail.com
https://railsguides.net/
Questions

More Related Content

Similar to Business domain isolation in PostgreSQL with schemas and views

CDC patterns in Apache Kafka®
CDC patterns in Apache Kafka®CDC patterns in Apache Kafka®
CDC patterns in Apache Kafka®confluent
 
PHP Detroit -- MySQL 8 A New Beginning (updated presentation)
PHP Detroit -- MySQL 8 A New Beginning (updated presentation)PHP Detroit -- MySQL 8 A New Beginning (updated presentation)
PHP Detroit -- MySQL 8 A New Beginning (updated presentation)Dave Stokes
 
MOOC_PRESENTATION_FINAL_PART_1[1].pptx
MOOC_PRESENTATION_FINAL_PART_1[1].pptxMOOC_PRESENTATION_FINAL_PART_1[1].pptx
MOOC_PRESENTATION_FINAL_PART_1[1].pptxmh3473
 
Ledingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @LendingkartLedingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @LendingkartMukesh Singh
 
Cloud Architecture best practices
Cloud Architecture best practicesCloud Architecture best practices
Cloud Architecture best practicesOmid Vahdaty
 
Oracle to Postgres Schema Migration Hustle
Oracle to Postgres Schema Migration HustleOracle to Postgres Schema Migration Hustle
Oracle to Postgres Schema Migration HustleEDB
 
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...VMware Tanzu
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptxKulbir4
 
MongoDB .local Houston 2019: Wide Ranging Analytical Solutions on MongoDB
MongoDB .local Houston 2019: Wide Ranging Analytical Solutions on MongoDBMongoDB .local Houston 2019: Wide Ranging Analytical Solutions on MongoDB
MongoDB .local Houston 2019: Wide Ranging Analytical Solutions on MongoDBMongoDB
 
Object relational database management system
Object relational database management systemObject relational database management system
Object relational database management systemSaibee Alam
 
NoSQL Solutions - a comparative study
NoSQL Solutions - a comparative studyNoSQL Solutions - a comparative study
NoSQL Solutions - a comparative studyGuillaume Lefranc
 
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...Dave Stokes
 
Introduction To MongoDB
Introduction To MongoDBIntroduction To MongoDB
Introduction To MongoDBElieHannouch
 
Java Developers, make the database work for you (NLJUG JFall 2010)
Java Developers, make the database work for you (NLJUG JFall 2010)Java Developers, make the database work for you (NLJUG JFall 2010)
Java Developers, make the database work for you (NLJUG JFall 2010)Lucas Jellema
 
Oracle applications r12.2, ebr, online patching means lot of work for devel...
Oracle applications r12.2, ebr, online patching   means lot of work for devel...Oracle applications r12.2, ebr, online patching   means lot of work for devel...
Oracle applications r12.2, ebr, online patching means lot of work for devel...Ajith Narayanan
 
High Performance SSRS
High Performance SSRSHigh Performance SSRS
High Performance SSRSBert Wagner
 
01 surya bpc_script_ppt
01 surya bpc_script_ppt01 surya bpc_script_ppt
01 surya bpc_script_pptSurya Padhi
 
OSMC 2018 | Learnings, patterns and Uber’s metrics platform M3, open sourced ...
OSMC 2018 | Learnings, patterns and Uber’s metrics platform M3, open sourced ...OSMC 2018 | Learnings, patterns and Uber’s metrics platform M3, open sourced ...
OSMC 2018 | Learnings, patterns and Uber’s metrics platform M3, open sourced ...NETWAYS
 
Java-8-Structured-MongoDB.pptx
Java-8-Structured-MongoDB.pptxJava-8-Structured-MongoDB.pptx
Java-8-Structured-MongoDB.pptxSuKimAnhCTU
 

Similar to Business domain isolation in PostgreSQL with schemas and views (20)

CDC patterns in Apache Kafka®
CDC patterns in Apache Kafka®CDC patterns in Apache Kafka®
CDC patterns in Apache Kafka®
 
PHP Detroit -- MySQL 8 A New Beginning (updated presentation)
PHP Detroit -- MySQL 8 A New Beginning (updated presentation)PHP Detroit -- MySQL 8 A New Beginning (updated presentation)
PHP Detroit -- MySQL 8 A New Beginning (updated presentation)
 
MOOC_PRESENTATION_FINAL_PART_1[1].pptx
MOOC_PRESENTATION_FINAL_PART_1[1].pptxMOOC_PRESENTATION_FINAL_PART_1[1].pptx
MOOC_PRESENTATION_FINAL_PART_1[1].pptx
 
Ledingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @LendingkartLedingkart Meetup #2: Scaling Search @Lendingkart
Ledingkart Meetup #2: Scaling Search @Lendingkart
 
Cloud Architecture best practices
Cloud Architecture best practicesCloud Architecture best practices
Cloud Architecture best practices
 
Oracle to Postgres Schema Migration Hustle
Oracle to Postgres Schema Migration HustleOracle to Postgres Schema Migration Hustle
Oracle to Postgres Schema Migration Hustle
 
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
 
MongoDB .local Houston 2019: Wide Ranging Analytical Solutions on MongoDB
MongoDB .local Houston 2019: Wide Ranging Analytical Solutions on MongoDBMongoDB .local Houston 2019: Wide Ranging Analytical Solutions on MongoDB
MongoDB .local Houston 2019: Wide Ranging Analytical Solutions on MongoDB
 
Cloudant
CloudantCloudant
Cloudant
 
Object relational database management system
Object relational database management systemObject relational database management system
Object relational database management system
 
NoSQL Solutions - a comparative study
NoSQL Solutions - a comparative studyNoSQL Solutions - a comparative study
NoSQL Solutions - a comparative study
 
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
 
Introduction To MongoDB
Introduction To MongoDBIntroduction To MongoDB
Introduction To MongoDB
 
Java Developers, make the database work for you (NLJUG JFall 2010)
Java Developers, make the database work for you (NLJUG JFall 2010)Java Developers, make the database work for you (NLJUG JFall 2010)
Java Developers, make the database work for you (NLJUG JFall 2010)
 
Oracle applications r12.2, ebr, online patching means lot of work for devel...
Oracle applications r12.2, ebr, online patching   means lot of work for devel...Oracle applications r12.2, ebr, online patching   means lot of work for devel...
Oracle applications r12.2, ebr, online patching means lot of work for devel...
 
High Performance SSRS
High Performance SSRSHigh Performance SSRS
High Performance SSRS
 
01 surya bpc_script_ppt
01 surya bpc_script_ppt01 surya bpc_script_ppt
01 surya bpc_script_ppt
 
OSMC 2018 | Learnings, patterns and Uber’s metrics platform M3, open sourced ...
OSMC 2018 | Learnings, patterns and Uber’s metrics platform M3, open sourced ...OSMC 2018 | Learnings, patterns and Uber’s metrics platform M3, open sourced ...
OSMC 2018 | Learnings, patterns and Uber’s metrics platform M3, open sourced ...
 
Java-8-Structured-MongoDB.pptx
Java-8-Structured-MongoDB.pptxJava-8-Structured-MongoDB.pptx
Java-8-Structured-MongoDB.pptx
 

More from Andrei Kaleshka

How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFAAndrei Kaleshka
 
Корпоративное приложение на Rails
Корпоративное приложение на RailsКорпоративное приложение на Rails
Корпоративное приложение на RailsAndrei Kaleshka
 

More from Andrei Kaleshka (7)

How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFA
 
Rails data migrations
Rails data migrationsRails data migrations
Rails data migrations
 
Корпоративное приложение на Rails
Корпоративное приложение на RailsКорпоративное приложение на Rails
Корпоративное приложение на Rails
 
Ruby exceptions
Ruby exceptionsRuby exceptions
Ruby exceptions
 
Rails3 way
Rails3 wayRails3 way
Rails3 way
 
Complete ruby code
Complete ruby codeComplete ruby code
Complete ruby code
 
Rails 3 assets pipeline
Rails 3 assets pipelineRails 3 assets pipeline
Rails 3 assets pipeline
 

Recently uploaded

pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 

Recently uploaded (20)

pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 

Business domain isolation in PostgreSQL with schemas and views

  • 1. Business domain isolation in DB (PostgreSQL) Andrey Koleshko @ka8725
  • 2. When does the problem arise? ● Monolithic application break down to micro-services ● Logical isolation parts of a monolithic application, i.e. split to modules (e.g. Rails engines) Note, we will talk about solution for PostgreSQL
  • 3. Initial state of the system ● Monolithic application ● Production setup ● One DB (PostgreSQL) ● Additional application (e.g. analytics) that only reads data from the DB ○ This application relies on the current tables structure ○ It relies on some static data, such as enum values
  • 4. Initial state of the system ● The consumer app relies on the current tables structure ● It relies on some static data, such as enum values
  • 5. ● Isolate a specific business domain in the DB ● Zero-downtime migration ● As less changes as possible to reduce costs and risks The goal
  • 6. ● Set of tables that are “hidden” from the main app Example: ○ Initially DB has tables: users and locations ○ Assume locations is a table from a business domain ○ After: ■ users remains in the main DB ■ locations is “hidden” from users What is isolated business domain in DB?
  • 7. The business domain is a set of tables that should be isolated, i.e. “hidden” from the main DB The target
  • 8. Natural solution Setup a separate DB and create the domain tables there, point all apps to use this new DB additionally to the main DB
  • 9. Pros ● Full isolation ○ while the business domain DB fails, the main DB remains functioning ● Separate configuration ● Separate data Natural solution: pros and cons Cons ● Implementation cost ● Maintenance cost ● Complex solution
  • 10. Natural solution: cons - complex solution
  • 11.
  • 12. Idea Isolate the business domain tables logically inside DB
  • 13. ● Use schemas ○ https://www.postgresql.org/docs/12/ddl-schemas.html ○ many users use one DB without interfering each other ○ DB objects are organized into logical groups to make them more manageable ○ third-party applications can be put into separate schemas not to collide How to implement this in PostgreSQL?
  • 14. “Schemas are analogous to directories at the operating system level, except that schemas cannot be nested.” Metaphor
  • 15. Result ● All tables remain in the same DB ● Domains are isolated: ○ public.users ○ business.locations
  • 16. ● Remove foreign keys between the tables ● Create the business schema with necessary tables, indexes, constraints, foreign keys, etc. inside this schema ● Start writing data into these new tables ● But don’t stop writing into the old tables yet ● Switch all apps to read from the new tables ● Drop the old tables along with all related DB objects Zero-downtime approach
  • 17. ● Remove foreign keys between the tables ● Create the business schema with necessary tables, indexes, constraints, foreign keys, etc. inside this schema ● Start writing data into these new tables ● But don’t stop writing into the old tables yet ● Switch all apps to read from the new tables ● Drop the old tables along with all related DB objects Zero-downtime approach
  • 18. ● Use triggers ○ https://www.postgresql.org/docs/12/trigger-definition.html ○ It’s like callbacks in ActiveRecord, but on DB level Start writing data into the new tables
  • 19. Switch to read from the new tables: step 1 Define an interface (contract/API) takes data from the old tables and is used by readers
  • 20. Write to the new and old tables in parallel Switch to read from the new tables: step 2
  • 21. Change the API to read from the the new tables and drop the old tables Switch all apps to read from the new tables: step 3 Note, the new tables are namespaced in a view
  • 22. ● Use views ○ http://www.postgresqltutorial.com/postgresql-views/ ○ Consider view as a virtual table reads data from one or many other tables ○ If the tables used by views change, views fail automatically - API tests out of box! ○ Enum values should be specified explicitly to avoid broken API readers ○ Namespace the views in a specific schema How to implement the API?
  • 23. create schema api; create view api.locations as select id, lat, lng, status from public.locations where public.locations.status = any(array['completed', 'pending']); View example
  • 24. View example caveats ● Expose only data with enums that are known by the Consumer app (array['completed', 'pending']) ○ If new enum value appears, the Consumer app will have to prepare code for this and then the row with the new enum value can be exposed ○ This way it guarantees the Consumer app is not broken due to the new enum value
  • 25. ● Rails was not prepared for that plan ● We’ve patched it: https://gist.github.com/ka8725/a45214a0e9d93fb7b7072206d7f2d0b4 ● Usage example: dumper = SchemaDumper.new(ActiveRecord::Base.connection) dumper.dump('api', Rails.root.join('db/api/schema.rb')) ● Created a rake task dumps these custom schemas and put it as a prerequisite for the standard db:schema:dump Generate separate schemas for Rails
  • 26. ● Easy to implement and maintain solution ● Rails is not friendly for non-trivial approaches and needs patches ● The final solution works for: ○ monolithic modular applications ○ micro-services ● The API idea is applicable for any app exposes data to internal services ● Follow your thoughts and learn using tools Summary