SlideShare a Scribd company logo
1 of 35
Download to read offline
With great data(bases) comes
great responsibility
Large table
partitioning with
PostgreSQL and
Django
Paolo Romolini, Caterina Magini
8 December 2020 - Postgres Build 2020
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.3
• Physicist and major science and technology enthusiast
• In 2ndQuadrant from 2018 to 2020 as DBA and Support Engineer
• Now in EDB
About us
• Web developer
• Python and Django enthusiast
• Customer Portal developer
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.4
Summary
• Our use case
• The problem
• Declarative partitioning as possible solution
• The adopted solution
Our use case
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.6
• Facilitate support engineers and
customers job
• Independent management of
companies and users
• Software and repositories
management
• Knowledge base
• Support Ticketing System
The Customer Portal
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.7
• Open source
• Dry principle
• MVT logic
• Excellent documentation
• Django REST Framework
Django
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.8
• Django.contrib.postgres
• JsonB and Array Fields
• Full Text Search
• PostgreSQL specific model indexes
• The Django Project uses it
• https://github.com/django/djangoproject.com
PostgreSQL and Django
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.9
Triggered by ticket events
• Pushover notifications
• Mattermost chats
• Emails
The notifications system
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.10
class EmailMessage(models.Model):
subject = models.CharField(max_length=1024)
to_recipients = ArrayField(models.CharField(max_length=256))
message = models.TextField()
from_email = models.CharField(max_length=256)
metadata = models.JSONField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
[...]
The Email Messages app model
The problem
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.12
• The table was growing too much
• It needed maintenance
Working in DevOps helps!
The Database Table is too large!
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.13
• When an application gets deployed to production early on the performance is great
• After a while, the database starts to get bigger and queries slow down...
• ...and at a certain point, you realize the data is the bottleneck
Table partitioning is a good solution
The DBA’s opinion
A typical scenario
Declarative
partitioning as
possible
solution
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.15
Declarative partitioning in PostgreSQL
Horizontal partitioning: technique for the vertical scalability of a database
Before PostgreSQL 10 From PostgreSQL 10
• Early “partitioning” introduced in
PostgreSQL 8.1
• Heavily based on relation inheritance
• Constraints to define the partitions,
rules and trigger to route data
• Required a lot of maintenance
• Declarative partitioning
• Simplified syntax
• Partitioned tables = new type of
relationship
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.16
The partitioning evolution in PostgreSQL
<=PG 9.6 PG 10 PG 11 PG 12 PG 13
Table inheritance Declarative table
partitioning syntax
Hash partition Partition pruning
enhancements
Partition wise join
enhancements
CHECK constraints Support indexes on
partitions tables
Foreign Keys to
reference
partitioned tables
Partition pruning
improvements
Triggers FOR EACH ROW
Trigger for
partitioned tables
Faster COPY for
partitioned tables
Before ROW-LEVEL
trigger
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.17
● Divide et impera
○ Smaller tables, smaller indexes
● Easier maintenance
● Healthier delete operations and bulk loads
○ Remove a table is faster than removing a lot of records
● Overall performance gains
○ Impact of seqscans
Why partitioning?
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.18
• RANGE
• LIST
• HASH
Partitioning can also be multi-level
Partitioning strategies
Supported partitioning methods:
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.19
Multi-level partitioning
Courtesy of Muhammad Haroon (https://www.2ndquadrant.com/en/blog/scaling-iot-time-series-data-postgres-bdr/)
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.20
CREATE TABLE email_messages (
id serial NOT NULL,
subject varchar(1024) NOT NULL,
message text NOT NULL,
from_email varchar(256) NOT NULL,
html_message text NULL,
created_at timestamp with time zone NOT NULL,
updated_at timestamp with time zone NULL,
...
send_to_multiple_recipients boolean NULL,
PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);
How does it work?
Partitioned table
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.21
CREATE TABLE email_messages_2020_11 PARTITION OF email_messages
FOR VALUES FROM (‘2020-11-01 01:00:00+01’) TO (‘2020-12-01 01:00:00+01’)
CREATE TABLE email_messages_2020_11 PARTITION OF email_messages
FOR VALUES FROM (‘2020-11-01 01:00:00+01’) TO (‘2020-12-01 01:00:00+01’)
How does it work?
Partitions
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.22
The list of columns or expressions that define the partitions bound:
• Range
Can have more > 1 column
• Hash
• List Can have only 1 column/expression
The partitioning key
PARTITION BY {RANGE | LIST | HASH}
({ column_name | (expression )} [ COLLATE collation ] [ opclass ] [,...])
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.23
Indexes, Primary Keys and Foreign Keys support
● CREATE INDEX on partitioned tables locally-partitioned indexes
● Support for UNIQUE and PRIMARY KEY constraints
○ Partition key has to be part of the PRIMARY KEY
● FOREIGN KEYs
○ Partitioned tables can REFERENCE other tables
○ Partitioned tables can be REFERENCED by other tables
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.24
Testing the procedure in QA
Once we understood that partitioning could be the solution, we just had to test it.
• QA environment with PostgreSQL 10
• Large table referenced by another table
• Can’t turn a not partitioned in table into a partitioned one → New table
• Most of the data in the old table are historical, no need to migrate them immediately
• LOCK the old table during the deploy
• Simulate traffic… and check that everything is OK
Needs to upgrade to PG 12
The adopted
solution
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.26
No support for table partitioning in Django
• Third-party django applications?
• Executing SQL query without Django?
Which way to take?
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.27
• PostgreSQL declarative partitioning is transparent to Django
• Doing it using Django tools
Django migrations!
The way we have chosen
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.28
• A way to track django models changes
• They are applied against the database
• You can revert them
Django migrations
$ python manage.py showmigrations email_messages
email_messages
[X] 0001_initial
[X] 0002_auto_20200716_0837
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.29
Specify a different table name
class EmailMessage(models.Model):
[...]
created_at = models.DateTimeField(auto_now_add=True, null=True)
class Meta:
db_table = “email_messages”
Django default database table names:
"%s_%s" % (self.app_label, self.model_name)
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.30
Django migrations with custom SQL
class Migration(migrations.Migration):
[...]
operations = [
migrations.RunSQL(
sql=[(PARTITIONED_TABLES_SQL],
reverse_sql=[DROP_PARTITONED_TABLES_SQL],
)
]
Run the sqlmigrate command
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.31
The partition key of the Django migration
PARTITIONED_TABLES_SQL = """
CREATE TABLE "email_messages" (
"id" serial NOT NULL PRIMARY KEY,
[...]
) PARTITION BY RANGE
(created_at);
"""
PARTITIONED_TABLES_SQL = """
CREATE TABLE "email_messages" (
"id" serial NOT NULL,
[...]
PRIMARY KEY (id, created_at)
) PARTITION BY RANGE
(created_at);
"""
→
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.32
Create the partitions with Django
• Create a new django management command
• Schedule the command as a cron job
• Add another django migration
We are ready to test it in QA!
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.33
Deployment in production
• The deployment ran smoothly
• The old table was attached to the new partition
Success!
© Copyright EnterpriseDB Corporation, 2020. All rights reserved.34
Conclusion
• The declarative PostgreSQL partitions is good
• Django is a great framework
• DevOps
• That’s one way to do it, not the way!
Follow us:
https://www.linkedin.com/in/paoloromolini/
https://www.linkedin.com/in/caterina-magini/
Tweet:
#PostgresBuild2020
#PostgreSQL
#Django

More Related Content

What's hot

High Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando PatroniHigh Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando PatroniZalando Technology
 
CentOS 8で標準搭載! 「389-ds」で構築する 認証サーバーについて
CentOS 8で標準搭載! 「389-ds」で構築する 認証サーバーについてCentOS 8で標準搭載! 「389-ds」で構築する 認証サーバーについて
CentOS 8で標準搭載! 「389-ds」で構築する 認証サーバーについてNobuyuki Sasaki
 
VM Job Queues in CloudStack
VM Job Queues in CloudStackVM Job Queues in CloudStack
VM Job Queues in CloudStackShapeBlue
 
MongoDB Journaling and the Storage Enginer
MongoDB Journaling and the Storage EnginerMongoDB Journaling and the Storage Enginer
MongoDB Journaling and the Storage EnginerMongoDB
 
MySQL innoDB split and merge pages
MySQL innoDB split and merge pagesMySQL innoDB split and merge pages
MySQL innoDB split and merge pagesMarco Tusa
 
【18-E-3】クラウド・ネイティブ時代の2016年だから始める Docker 基礎講座
【18-E-3】クラウド・ネイティブ時代の2016年だから始める Docker 基礎講座【18-E-3】クラウド・ネイティブ時代の2016年だから始める Docker 基礎講座
【18-E-3】クラウド・ネイティブ時代の2016年だから始める Docker 基礎講座Masahito Zembutsu
 
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docxKeepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docxNeoClova
 
Zabbix最新情報 ~Zabbix 6.0に向けて~ @OSC2021 Online/Fall
Zabbix最新情報 ~Zabbix 6.0に向けて~ @OSC2021 Online/FallZabbix最新情報 ~Zabbix 6.0に向けて~ @OSC2021 Online/Fall
Zabbix最新情報 ~Zabbix 6.0に向けて~ @OSC2021 Online/FallAtsushi Tanaka
 
EC2でkeepalived+LVS(DSR)
EC2でkeepalived+LVS(DSR)EC2でkeepalived+LVS(DSR)
EC2でkeepalived+LVS(DSR)Sugawara Genki
 
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정PgDay.Seoul
 
PostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetPostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetAlexey Lesovsky
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBMydbops
 
わたしを支える技術
わたしを支える技術わたしを支える技術
わたしを支える技術yoku0825
 
MySQL Replication Overview -- PHPTek 2016
MySQL Replication Overview -- PHPTek 2016MySQL Replication Overview -- PHPTek 2016
MySQL Replication Overview -- PHPTek 2016Dave Stokes
 
Replication Troubleshooting in Classic VS GTID
Replication Troubleshooting in Classic VS GTIDReplication Troubleshooting in Classic VS GTID
Replication Troubleshooting in Classic VS GTIDMydbops
 
PostgreSQL Deep Internal
PostgreSQL Deep InternalPostgreSQL Deep Internal
PostgreSQL Deep InternalEXEM
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansibleGeorge Shuklin
 
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...Altinity Ltd
 
Introduction VAUUM, Freezing, XID wraparound
Introduction VAUUM, Freezing, XID wraparoundIntroduction VAUUM, Freezing, XID wraparound
Introduction VAUUM, Freezing, XID wraparoundMasahiko Sawada
 

What's hot (20)

High Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando PatroniHigh Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando Patroni
 
CentOS 8で標準搭載! 「389-ds」で構築する 認証サーバーについて
CentOS 8で標準搭載! 「389-ds」で構築する 認証サーバーについてCentOS 8で標準搭載! 「389-ds」で構築する 認証サーバーについて
CentOS 8で標準搭載! 「389-ds」で構築する 認証サーバーについて
 
VM Job Queues in CloudStack
VM Job Queues in CloudStackVM Job Queues in CloudStack
VM Job Queues in CloudStack
 
MongoDB Journaling and the Storage Enginer
MongoDB Journaling and the Storage EnginerMongoDB Journaling and the Storage Enginer
MongoDB Journaling and the Storage Enginer
 
MySQL innoDB split and merge pages
MySQL innoDB split and merge pagesMySQL innoDB split and merge pages
MySQL innoDB split and merge pages
 
【18-E-3】クラウド・ネイティブ時代の2016年だから始める Docker 基礎講座
【18-E-3】クラウド・ネイティブ時代の2016年だから始める Docker 基礎講座【18-E-3】クラウド・ネイティブ時代の2016年だから始める Docker 基礎講座
【18-E-3】クラウド・ネイティブ時代の2016年だから始める Docker 基礎講座
 
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docxKeepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
 
Zabbix最新情報 ~Zabbix 6.0に向けて~ @OSC2021 Online/Fall
Zabbix最新情報 ~Zabbix 6.0に向けて~ @OSC2021 Online/FallZabbix最新情報 ~Zabbix 6.0に向けて~ @OSC2021 Online/Fall
Zabbix最新情報 ~Zabbix 6.0に向けて~ @OSC2021 Online/Fall
 
EC2でkeepalived+LVS(DSR)
EC2でkeepalived+LVS(DSR)EC2でkeepalived+LVS(DSR)
EC2でkeepalived+LVS(DSR)
 
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
[pgday.Seoul 2022] 서비스개편시 PostgreSQL 도입기 - 진소린 & 김태정
 
PostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetPostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication Cheatsheet
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDB
 
わたしを支える技術
わたしを支える技術わたしを支える技術
わたしを支える技術
 
MySQL Replication Overview -- PHPTek 2016
MySQL Replication Overview -- PHPTek 2016MySQL Replication Overview -- PHPTek 2016
MySQL Replication Overview -- PHPTek 2016
 
Replication Troubleshooting in Classic VS GTID
Replication Troubleshooting in Classic VS GTIDReplication Troubleshooting in Classic VS GTID
Replication Troubleshooting in Classic VS GTID
 
PostgreSQL Deep Internal
PostgreSQL Deep InternalPostgreSQL Deep Internal
PostgreSQL Deep Internal
 
ClickHouse Keeper
ClickHouse KeeperClickHouse Keeper
ClickHouse Keeper
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansible
 
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...
Introduction to the Mysteries of ClickHouse Replication, By Robert Hodges and...
 
Introduction VAUUM, Freezing, XID wraparound
Introduction VAUUM, Freezing, XID wraparoundIntroduction VAUUM, Freezing, XID wraparound
Introduction VAUUM, Freezing, XID wraparound
 

Similar to Large Table Partitioning with PostgreSQL and Django

New and Improved Features in PostgreSQL 13
New and Improved Features in PostgreSQL 13New and Improved Features in PostgreSQL 13
New and Improved Features in PostgreSQL 13EDB
 
PostgreSQL 13 is Coming - Find Out What's New!
PostgreSQL 13 is Coming - Find Out What's New!PostgreSQL 13 is Coming - Find Out What's New!
PostgreSQL 13 is Coming - Find Out What's New!EDB
 
Practical Partitioning in Production with Postgres
Practical Partitioning in Production with PostgresPractical Partitioning in Production with Postgres
Practical Partitioning in Production with PostgresJimmy Angelakos
 
EDB & ELOS Technologies - Break Free from Oracle
EDB & ELOS Technologies - Break Free from OracleEDB & ELOS Technologies - Break Free from Oracle
EDB & ELOS Technologies - Break Free from OracleEDB
 
PostgreSQL as a Strategic Tool
PostgreSQL as a Strategic ToolPostgreSQL as a Strategic Tool
PostgreSQL as a Strategic ToolEDB
 
EDB: Power to Postgres
EDB: Power to PostgresEDB: Power to Postgres
EDB: Power to PostgresAshnikbiz
 
Enterprise-class security with PostgreSQL - 2
Enterprise-class security with PostgreSQL - 2Enterprise-class security with PostgreSQL - 2
Enterprise-class security with PostgreSQL - 2Ashnikbiz
 
Szabaduljon ki az Oracle szorításából
Szabaduljon ki az Oracle szorításábólSzabaduljon ki az Oracle szorításából
Szabaduljon ki az Oracle szorításábólEDB
 
Managing Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsManaging Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsBuhake Sindi
 
Oracle to Postgres Schema Migration Hustle
Oracle to Postgres Schema Migration HustleOracle to Postgres Schema Migration Hustle
Oracle to Postgres Schema Migration HustleEDB
 
Break Free from Oracle
Break Free from OracleBreak Free from Oracle
Break Free from OracleEDB
 
Expert Guide to Migrating Legacy Databases to Postgres
Expert Guide to Migrating Legacy Databases to PostgresExpert Guide to Migrating Legacy Databases to Postgres
Expert Guide to Migrating Legacy Databases to PostgresEDB
 
Un guide complet pour la migration de bases de données héritées vers PostgreSQL
Un guide complet pour la migration de bases de données héritées vers PostgreSQLUn guide complet pour la migration de bases de données héritées vers PostgreSQL
Un guide complet pour la migration de bases de données héritées vers PostgreSQLEDB
 
Replacing Oracle with EDB Postgres
Replacing Oracle with EDB PostgresReplacing Oracle with EDB Postgres
Replacing Oracle with EDB PostgresEDB
 
An Expert Guide to Migrating Legacy Databases to PostgreSQL
An Expert Guide to Migrating Legacy Databases to PostgreSQLAn Expert Guide to Migrating Legacy Databases to PostgreSQL
An Expert Guide to Migrating Legacy Databases to PostgreSQLEDB
 
EDB 13 - New Enhancements for Security and Usability - APJ
EDB 13 - New Enhancements for Security and Usability - APJEDB 13 - New Enhancements for Security and Usability - APJ
EDB 13 - New Enhancements for Security and Usability - APJEDB
 
New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13EDB
 
PostgreSQL as a Strategic Tool
PostgreSQL as a Strategic ToolPostgreSQL as a Strategic Tool
PostgreSQL as a Strategic ToolEDB
 
DBT ELT approach for Advanced Analytics.pptx
DBT ELT approach for Advanced Analytics.pptxDBT ELT approach for Advanced Analytics.pptx
DBT ELT approach for Advanced Analytics.pptxHong Ong
 

Similar to Large Table Partitioning with PostgreSQL and Django (20)

New and Improved Features in PostgreSQL 13
New and Improved Features in PostgreSQL 13New and Improved Features in PostgreSQL 13
New and Improved Features in PostgreSQL 13
 
PostgreSQL 13 is Coming - Find Out What's New!
PostgreSQL 13 is Coming - Find Out What's New!PostgreSQL 13 is Coming - Find Out What's New!
PostgreSQL 13 is Coming - Find Out What's New!
 
Practical Partitioning in Production with Postgres
Practical Partitioning in Production with PostgresPractical Partitioning in Production with Postgres
Practical Partitioning in Production with Postgres
 
EDB & ELOS Technologies - Break Free from Oracle
EDB & ELOS Technologies - Break Free from OracleEDB & ELOS Technologies - Break Free from Oracle
EDB & ELOS Technologies - Break Free from Oracle
 
PostgreSQL as a Strategic Tool
PostgreSQL as a Strategic ToolPostgreSQL as a Strategic Tool
PostgreSQL as a Strategic Tool
 
EDB: Power to Postgres
EDB: Power to PostgresEDB: Power to Postgres
EDB: Power to Postgres
 
Enterprise-class security with PostgreSQL - 2
Enterprise-class security with PostgreSQL - 2Enterprise-class security with PostgreSQL - 2
Enterprise-class security with PostgreSQL - 2
 
Szabaduljon ki az Oracle szorításából
Szabaduljon ki az Oracle szorításábólSzabaduljon ki az Oracle szorításából
Szabaduljon ki az Oracle szorításából
 
Managing Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsManaging Data in Jakarta EE Applications
Managing Data in Jakarta EE Applications
 
Oracle to Postgres Schema Migration Hustle
Oracle to Postgres Schema Migration HustleOracle to Postgres Schema Migration Hustle
Oracle to Postgres Schema Migration Hustle
 
Break Free from Oracle
Break Free from OracleBreak Free from Oracle
Break Free from Oracle
 
Expert Guide to Migrating Legacy Databases to Postgres
Expert Guide to Migrating Legacy Databases to PostgresExpert Guide to Migrating Legacy Databases to Postgres
Expert Guide to Migrating Legacy Databases to Postgres
 
Google BigQuery
Google BigQueryGoogle BigQuery
Google BigQuery
 
Un guide complet pour la migration de bases de données héritées vers PostgreSQL
Un guide complet pour la migration de bases de données héritées vers PostgreSQLUn guide complet pour la migration de bases de données héritées vers PostgreSQL
Un guide complet pour la migration de bases de données héritées vers PostgreSQL
 
Replacing Oracle with EDB Postgres
Replacing Oracle with EDB PostgresReplacing Oracle with EDB Postgres
Replacing Oracle with EDB Postgres
 
An Expert Guide to Migrating Legacy Databases to PostgreSQL
An Expert Guide to Migrating Legacy Databases to PostgreSQLAn Expert Guide to Migrating Legacy Databases to PostgreSQL
An Expert Guide to Migrating Legacy Databases to PostgreSQL
 
EDB 13 - New Enhancements for Security and Usability - APJ
EDB 13 - New Enhancements for Security and Usability - APJEDB 13 - New Enhancements for Security and Usability - APJ
EDB 13 - New Enhancements for Security and Usability - APJ
 
New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13
 
PostgreSQL as a Strategic Tool
PostgreSQL as a Strategic ToolPostgreSQL as a Strategic Tool
PostgreSQL as a Strategic Tool
 
DBT ELT approach for Advanced Analytics.pptx
DBT ELT approach for Advanced Analytics.pptxDBT ELT approach for Advanced Analytics.pptx
DBT ELT approach for Advanced Analytics.pptx
 

More from EDB

Cloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaSCloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaSEDB
 
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr Unternehmen
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr UnternehmenDie 10 besten PostgreSQL-Replikationsstrategien für Ihr Unternehmen
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr UnternehmenEDB
 
Migre sus bases de datos Oracle a la nube
Migre sus bases de datos Oracle a la nube Migre sus bases de datos Oracle a la nube
Migre sus bases de datos Oracle a la nube EDB
 
EFM Office Hours - APJ - July 29, 2021
EFM Office Hours - APJ - July 29, 2021EFM Office Hours - APJ - July 29, 2021
EFM Office Hours - APJ - July 29, 2021EDB
 
Benchmarking Cloud Native PostgreSQL
Benchmarking Cloud Native PostgreSQLBenchmarking Cloud Native PostgreSQL
Benchmarking Cloud Native PostgreSQLEDB
 
Las Variaciones de la Replicación de PostgreSQL
Las Variaciones de la Replicación de PostgreSQLLas Variaciones de la Replicación de PostgreSQL
Las Variaciones de la Replicación de PostgreSQLEDB
 
NoSQL and Spatial Database Capabilities using PostgreSQL
NoSQL and Spatial Database Capabilities using PostgreSQLNoSQL and Spatial Database Capabilities using PostgreSQL
NoSQL and Spatial Database Capabilities using PostgreSQLEDB
 
Is There Anything PgBouncer Can’t Do?
Is There Anything PgBouncer Can’t Do?Is There Anything PgBouncer Can’t Do?
Is There Anything PgBouncer Can’t Do?EDB
 
Data Analysis with TensorFlow in PostgreSQL
Data Analysis with TensorFlow in PostgreSQLData Analysis with TensorFlow in PostgreSQL
Data Analysis with TensorFlow in PostgreSQLEDB
 
A Deeper Dive into EXPLAIN
A Deeper Dive into EXPLAINA Deeper Dive into EXPLAIN
A Deeper Dive into EXPLAINEDB
 
IOT with PostgreSQL
IOT with PostgreSQLIOT with PostgreSQL
IOT with PostgreSQLEDB
 
A Journey from Oracle to PostgreSQL
A Journey from Oracle to PostgreSQLA Journey from Oracle to PostgreSQL
A Journey from Oracle to PostgreSQLEDB
 
Psql is awesome!
Psql is awesome!Psql is awesome!
Psql is awesome!EDB
 
Comment sauvegarder correctement vos données
Comment sauvegarder correctement vos donnéesComment sauvegarder correctement vos données
Comment sauvegarder correctement vos donnéesEDB
 
Cloud Native PostgreSQL - Italiano
Cloud Native PostgreSQL - ItalianoCloud Native PostgreSQL - Italiano
Cloud Native PostgreSQL - ItalianoEDB
 
New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13EDB
 
Best Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLBest Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLEDB
 
Cloud Native PostgreSQL - APJ
Cloud Native PostgreSQL - APJCloud Native PostgreSQL - APJ
Cloud Native PostgreSQL - APJEDB
 
Best Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLBest Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLEDB
 
EDB Postgres & Tools in a Smart City Project
EDB Postgres & Tools in a Smart City ProjectEDB Postgres & Tools in a Smart City Project
EDB Postgres & Tools in a Smart City ProjectEDB
 

More from EDB (20)

Cloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaSCloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaS
 
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr Unternehmen
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr UnternehmenDie 10 besten PostgreSQL-Replikationsstrategien für Ihr Unternehmen
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr Unternehmen
 
Migre sus bases de datos Oracle a la nube
Migre sus bases de datos Oracle a la nube Migre sus bases de datos Oracle a la nube
Migre sus bases de datos Oracle a la nube
 
EFM Office Hours - APJ - July 29, 2021
EFM Office Hours - APJ - July 29, 2021EFM Office Hours - APJ - July 29, 2021
EFM Office Hours - APJ - July 29, 2021
 
Benchmarking Cloud Native PostgreSQL
Benchmarking Cloud Native PostgreSQLBenchmarking Cloud Native PostgreSQL
Benchmarking Cloud Native PostgreSQL
 
Las Variaciones de la Replicación de PostgreSQL
Las Variaciones de la Replicación de PostgreSQLLas Variaciones de la Replicación de PostgreSQL
Las Variaciones de la Replicación de PostgreSQL
 
NoSQL and Spatial Database Capabilities using PostgreSQL
NoSQL and Spatial Database Capabilities using PostgreSQLNoSQL and Spatial Database Capabilities using PostgreSQL
NoSQL and Spatial Database Capabilities using PostgreSQL
 
Is There Anything PgBouncer Can’t Do?
Is There Anything PgBouncer Can’t Do?Is There Anything PgBouncer Can’t Do?
Is There Anything PgBouncer Can’t Do?
 
Data Analysis with TensorFlow in PostgreSQL
Data Analysis with TensorFlow in PostgreSQLData Analysis with TensorFlow in PostgreSQL
Data Analysis with TensorFlow in PostgreSQL
 
A Deeper Dive into EXPLAIN
A Deeper Dive into EXPLAINA Deeper Dive into EXPLAIN
A Deeper Dive into EXPLAIN
 
IOT with PostgreSQL
IOT with PostgreSQLIOT with PostgreSQL
IOT with PostgreSQL
 
A Journey from Oracle to PostgreSQL
A Journey from Oracle to PostgreSQLA Journey from Oracle to PostgreSQL
A Journey from Oracle to PostgreSQL
 
Psql is awesome!
Psql is awesome!Psql is awesome!
Psql is awesome!
 
Comment sauvegarder correctement vos données
Comment sauvegarder correctement vos donnéesComment sauvegarder correctement vos données
Comment sauvegarder correctement vos données
 
Cloud Native PostgreSQL - Italiano
Cloud Native PostgreSQL - ItalianoCloud Native PostgreSQL - Italiano
Cloud Native PostgreSQL - Italiano
 
New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13
 
Best Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLBest Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQL
 
Cloud Native PostgreSQL - APJ
Cloud Native PostgreSQL - APJCloud Native PostgreSQL - APJ
Cloud Native PostgreSQL - APJ
 
Best Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLBest Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQL
 
EDB Postgres & Tools in a Smart City Project
EDB Postgres & Tools in a Smart City ProjectEDB Postgres & Tools in a Smart City Project
EDB Postgres & Tools in a Smart City Project
 

Recently uploaded

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Recently uploaded (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

Large Table Partitioning with PostgreSQL and Django

  • 1. With great data(bases) comes great responsibility
  • 2. Large table partitioning with PostgreSQL and Django Paolo Romolini, Caterina Magini 8 December 2020 - Postgres Build 2020
  • 3. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.3 • Physicist and major science and technology enthusiast • In 2ndQuadrant from 2018 to 2020 as DBA and Support Engineer • Now in EDB About us • Web developer • Python and Django enthusiast • Customer Portal developer
  • 4. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.4 Summary • Our use case • The problem • Declarative partitioning as possible solution • The adopted solution
  • 6. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.6 • Facilitate support engineers and customers job • Independent management of companies and users • Software and repositories management • Knowledge base • Support Ticketing System The Customer Portal
  • 7. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.7 • Open source • Dry principle • MVT logic • Excellent documentation • Django REST Framework Django
  • 8. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.8 • Django.contrib.postgres • JsonB and Array Fields • Full Text Search • PostgreSQL specific model indexes • The Django Project uses it • https://github.com/django/djangoproject.com PostgreSQL and Django
  • 9. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.9 Triggered by ticket events • Pushover notifications • Mattermost chats • Emails The notifications system
  • 10. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.10 class EmailMessage(models.Model): subject = models.CharField(max_length=1024) to_recipients = ArrayField(models.CharField(max_length=256)) message = models.TextField() from_email = models.CharField(max_length=256) metadata = models.JSONField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True) [...] The Email Messages app model
  • 12. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.12 • The table was growing too much • It needed maintenance Working in DevOps helps! The Database Table is too large!
  • 13. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.13 • When an application gets deployed to production early on the performance is great • After a while, the database starts to get bigger and queries slow down... • ...and at a certain point, you realize the data is the bottleneck Table partitioning is a good solution The DBA’s opinion A typical scenario
  • 15. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.15 Declarative partitioning in PostgreSQL Horizontal partitioning: technique for the vertical scalability of a database Before PostgreSQL 10 From PostgreSQL 10 • Early “partitioning” introduced in PostgreSQL 8.1 • Heavily based on relation inheritance • Constraints to define the partitions, rules and trigger to route data • Required a lot of maintenance • Declarative partitioning • Simplified syntax • Partitioned tables = new type of relationship
  • 16. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.16 The partitioning evolution in PostgreSQL <=PG 9.6 PG 10 PG 11 PG 12 PG 13 Table inheritance Declarative table partitioning syntax Hash partition Partition pruning enhancements Partition wise join enhancements CHECK constraints Support indexes on partitions tables Foreign Keys to reference partitioned tables Partition pruning improvements Triggers FOR EACH ROW Trigger for partitioned tables Faster COPY for partitioned tables Before ROW-LEVEL trigger
  • 17. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.17 ● Divide et impera ○ Smaller tables, smaller indexes ● Easier maintenance ● Healthier delete operations and bulk loads ○ Remove a table is faster than removing a lot of records ● Overall performance gains ○ Impact of seqscans Why partitioning?
  • 18. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.18 • RANGE • LIST • HASH Partitioning can also be multi-level Partitioning strategies Supported partitioning methods:
  • 19. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.19 Multi-level partitioning Courtesy of Muhammad Haroon (https://www.2ndquadrant.com/en/blog/scaling-iot-time-series-data-postgres-bdr/)
  • 20. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.20 CREATE TABLE email_messages ( id serial NOT NULL, subject varchar(1024) NOT NULL, message text NOT NULL, from_email varchar(256) NOT NULL, html_message text NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NULL, ... send_to_multiple_recipients boolean NULL, PRIMARY KEY (id, created_at) ) PARTITION BY RANGE (created_at); How does it work? Partitioned table
  • 21. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.21 CREATE TABLE email_messages_2020_11 PARTITION OF email_messages FOR VALUES FROM (‘2020-11-01 01:00:00+01’) TO (‘2020-12-01 01:00:00+01’) CREATE TABLE email_messages_2020_11 PARTITION OF email_messages FOR VALUES FROM (‘2020-11-01 01:00:00+01’) TO (‘2020-12-01 01:00:00+01’) How does it work? Partitions
  • 22. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.22 The list of columns or expressions that define the partitions bound: • Range Can have more > 1 column • Hash • List Can have only 1 column/expression The partitioning key PARTITION BY {RANGE | LIST | HASH} ({ column_name | (expression )} [ COLLATE collation ] [ opclass ] [,...])
  • 23. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.23 Indexes, Primary Keys and Foreign Keys support ● CREATE INDEX on partitioned tables locally-partitioned indexes ● Support for UNIQUE and PRIMARY KEY constraints ○ Partition key has to be part of the PRIMARY KEY ● FOREIGN KEYs ○ Partitioned tables can REFERENCE other tables ○ Partitioned tables can be REFERENCED by other tables
  • 24. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.24 Testing the procedure in QA Once we understood that partitioning could be the solution, we just had to test it. • QA environment with PostgreSQL 10 • Large table referenced by another table • Can’t turn a not partitioned in table into a partitioned one → New table • Most of the data in the old table are historical, no need to migrate them immediately • LOCK the old table during the deploy • Simulate traffic… and check that everything is OK Needs to upgrade to PG 12
  • 26. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.26 No support for table partitioning in Django • Third-party django applications? • Executing SQL query without Django? Which way to take?
  • 27. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.27 • PostgreSQL declarative partitioning is transparent to Django • Doing it using Django tools Django migrations! The way we have chosen
  • 28. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.28 • A way to track django models changes • They are applied against the database • You can revert them Django migrations $ python manage.py showmigrations email_messages email_messages [X] 0001_initial [X] 0002_auto_20200716_0837
  • 29. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.29 Specify a different table name class EmailMessage(models.Model): [...] created_at = models.DateTimeField(auto_now_add=True, null=True) class Meta: db_table = “email_messages” Django default database table names: "%s_%s" % (self.app_label, self.model_name)
  • 30. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.30 Django migrations with custom SQL class Migration(migrations.Migration): [...] operations = [ migrations.RunSQL( sql=[(PARTITIONED_TABLES_SQL], reverse_sql=[DROP_PARTITONED_TABLES_SQL], ) ] Run the sqlmigrate command
  • 31. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.31 The partition key of the Django migration PARTITIONED_TABLES_SQL = """ CREATE TABLE "email_messages" ( "id" serial NOT NULL PRIMARY KEY, [...] ) PARTITION BY RANGE (created_at); """ PARTITIONED_TABLES_SQL = """ CREATE TABLE "email_messages" ( "id" serial NOT NULL, [...] PRIMARY KEY (id, created_at) ) PARTITION BY RANGE (created_at); """ →
  • 32. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.32 Create the partitions with Django • Create a new django management command • Schedule the command as a cron job • Add another django migration We are ready to test it in QA!
  • 33. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.33 Deployment in production • The deployment ran smoothly • The old table was attached to the new partition Success!
  • 34. © Copyright EnterpriseDB Corporation, 2020. All rights reserved.34 Conclusion • The declarative PostgreSQL partitions is good • Django is a great framework • DevOps • That’s one way to do it, not the way!