How to Replicate PostgreSQL Database

Brandon Kang
Brandon KangService Platform Architect
Service Platform Architect
Brandon Kang
sangjinn@gmail.com
https://tech.brandonkang.net
July 2020
How to Replicate
PostgreSQL Database
/ / 0 2 /
.
2 : / 2 . /
A
@ /: /
/ /
Replication Overall
Primary Server
• A server for both READ and WRITE
Standby Server = Slave server, Backup server, Replica, etc.
• A server where the data is kept in sync with the master continuously
• A warm standby server can’t be connected until it is promoted to primary
• A hot standby server accepts connections and serves read-only queries
• Data is written to the master server and propagated to the slave servers
• When primary server has an issue, a standby server will take over and
continue to take ‘WRITE” process
WAL Shipping Replication
WAL(Write-Ahead Logging)
• A log file where all the modifications to the database
• WAL is used for recovery after a database crash, ensuring data integrity
• WAL is used in database systems to achieve atomicity and durability
WAL based Replication ­ Streaming WAL Records
• Write-ahead log records are used to keep the data in sync
• WAL record chunks are streamed by database servers to synchronize
• Standby server connects to the master to receive the WAL chunks
• WAL records are streamed as they are generated
• The streaming of WAL records need not wait for the WAL file to be filled
Streaming Replication
PRIMARY
Server
Standby
Server
WAL
Sender
WAL
Receiver
WAL Record
READ ONLYREAD/WRITE
pg_wal
directory
WAL
File
pg_wal
directory
WAL
File
Synchronize
- WAL Record1
- WAL Record2
- WAL Record3
……
Replication Configuration
Primary Node ­ pg_hba.conf
/PG_HOME/DATA/pg_hba.conf
# Allow replication connections from localhost,
# by a user with the replication privilege.
# TYPE DATABASE USER ADDRESS METHOD
host replication repl_user IPaddress(CIDR) md5
Restart PostgreSQL service on the primary node
Internal IP ranges
Firewall Open for this.
Replication Configuration
Primary Node ­/PG_HOME/DATA/postgres.conf
# Possible values are replica|minimal|logical
wal_level = hot_standby
archive_mode = on #Syncronize with Primany node using wal archive
archive_command = ‘cp %p /PG_TBS/backup/archive/%f’ #psql_superuser archive backup
# required for pg_rewind capability when standby goes out of sync with master
wal_log_hints = on
# sets the maximum number of concurrent connections from the standby servers.
max_wal_senders = 2
# The below parameter is used to tell the master to keep the minimum number of
# segments of WAL logs so that they are not deleted before standby consumes them.
# each segment is 16MB
wal_keep_segments = 16
Replication Configuration
Secondary Node ­/PG_HOME/DATA/postgres.conf
hot_standby = on
Secondary Node ­/PG_HOME/DATA/recovery.conf
standby_mode = ‘on’
restore_command = ‘cp %p /PG_TBS/backup/archive/%f “%p”’
Primary_conninfo = ‘host=… ports=… user=postgres password= application_name=slave1’
# Explaining a few options used for pg_basebackup utility
# -X option is used to include the required transaction log files (WAL files) in the
# backup. When you specify stream, this will open a second connection to the server
# and start streaming the transaction log at the same time as running the backup.
# -c is the checkpoint option. Setting it to fast will force the checkpoint to be
# created soon.
# -W forces pg_basebackup to prompt for a password before connecting
# to a database.
pg_basebackup -D <data_directory> -h <master_host> -X stream -c fast -U
repl_user -W
Replication Configuration
Secondary Node ­ pg_basebackup utility
# Explaining a few options used for pg_basebackup utility
# -X option is used to include the required transaction log files (WAL files) in the
# backup. When you specify stream, this will open a second connection to the server
# and start streaming the transaction log at the same time as running the backup.
# -c is the checkpoint option. Setting it to fast will force the checkpoint to be
# created soon.
# -W forces pg_basebackup to prompt for a password before connecting
# to a database.
pg_basebackup -D <data_directory> -h <master_host> -X stream -c fast -U repl_user -W
Example)
$pg_basebackup ­h localhost ­p 5170 -u postgres ­D /PG_TBS/cluster -checkpoint=fast --progress
Replication Configuration
Secondary Node ­ Replication configuration file
# Specifies whether to start the server as a standby. In streaming replication,
# this parameter must be set to on.
standby_mode = ‘on’
# Specifies a connection string which is used for the standby server to connect
# with the primary/master.
primary_conninfo = ‘host=<master_host> port=<postgres_port> user=<replication_user>
password=<password> application_name=”host_name”’
# Specifies recovering to a particular timeline. The default is to recover along the
# same timeline that was current when the base backup was taken.
# Setting this to latest recovers to the latest timeline found
# in the archive, which is useful in a standby server.
recovery_target_timeline = ‘latest’
Start PostgreSQL service on the Standby node
Replication Testing
postgres=# select * from pg_stat_replication ;
-[ RECORD 1 ]----+---------------------------------
pid | 1114
usesysid | 16384
usename | repuser
application_name | walreceiver
client_addr | 127.0.0.1
client_hostname |
client_port | 52444
backend_start | 08-MAR-20 19:54:05.535695 -04:00
state | streaming
..
sync_priority | 0
sync_state | async
ps ­ef | grep postgres
[Master] wal sender process check
[Standby] wal receiver & startup process check
SELECT * FROM pg_stat_replication; Query execution on the Primary/Standby nodes
Replication Testing
pg_is_in_recovery(): A function to check if standby server is still in recovery mode or not
postgres=# select pg_is_in_recovery();
pg_is_in_recovery
-------------------
t
(1 row)
pg_last_xact_replay_timestamp(): A function shows time stamp of last replica transaction
postgres=# select pg_last_xact_replay_timestamp();
pg_last_xact_replay_timestamp
----------------------------------
08-MAR-20 20:54:27.635591 -04:00 (1 row)
SELECT CASE WHEN pg_last_xlog_receive_location() = pg_last_xlog_replay_location()
THEN 0
ELSE EXTRACT (EPOCH FROM now() - pg_last_xact_replay_timestamp())
END AS log_delay;
Calculating logs in seconds
Scaling PostgreSQL
PRIMARY
Server
Standby
Server
WAL
Sender
WAL
Receiver
WAL Record
WRITE
Synchronize
HAProxy /
NGINX / F5 READ
WRITE
READ
pgBouncer
primary_db
standby_db
Application
- Thank You. -
Service Platform Architect
Brandon Kang
sangjinn@gmail.com
https://tech.brandonkang.net
1 of 13

Recommended

Streaming replication in PostgreSQL by
Streaming replication in PostgreSQLStreaming replication in PostgreSQL
Streaming replication in PostgreSQLAshnikbiz
1.9K views12 slides
Streaming Replication Made Easy in v9.3 by
Streaming Replication Made Easy in v9.3Streaming Replication Made Easy in v9.3
Streaming Replication Made Easy in v9.3Sameer Kumar
1.2K views14 slides
Built in physical and logical replication in postgresql-Firat Gulec by
Built in physical and logical replication in postgresql-Firat GulecBuilt in physical and logical replication in postgresql-Firat Gulec
Built in physical and logical replication in postgresql-Firat GulecFIRAT GULEC
397 views49 slides
Webinar Slides: Migrating to Galera Cluster by
Webinar Slides: Migrating to Galera ClusterWebinar Slides: Migrating to Galera Cluster
Webinar Slides: Migrating to Galera ClusterSeveralnines
9.2K views23 slides
Out of the box replication in postgres 9.4 by
Out of the box replication in postgres 9.4Out of the box replication in postgres 9.4
Out of the box replication in postgres 9.4Denish Patel
11.7K views50 slides
PostgreSQL Streaming Replication Cheatsheet by
PostgreSQL Streaming Replication CheatsheetPostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetAlexey Lesovsky
6.1K views1 slide

More Related Content

What's hot

Pgbr 2013 postgres on aws by
Pgbr 2013   postgres on awsPgbr 2013   postgres on aws
Pgbr 2013 postgres on awsEmanuel Calvo
4.7K views39 slides
HBase Coprocessor Introduction by
HBase Coprocessor IntroductionHBase Coprocessor Introduction
HBase Coprocessor IntroductionSchubert Zhang
12K views20 slides
ProstgreSQLFailoverConfiguration by
ProstgreSQLFailoverConfigurationProstgreSQLFailoverConfiguration
ProstgreSQLFailoverConfigurationSuyog Shirgaonkar
482 views22 slides
Out of the box replication in postgres 9.4(pg confus) by
Out of the box replication in postgres 9.4(pg confus)Out of the box replication in postgres 9.4(pg confus)
Out of the box replication in postgres 9.4(pg confus)Denish Patel
1.1K views52 slides
Streaming replication in practice by
Streaming replication in practiceStreaming replication in practice
Streaming replication in practiceAlexey Lesovsky
8.7K views70 slides
PostgreSQL Replication Tutorial by
PostgreSQL Replication TutorialPostgreSQL Replication Tutorial
PostgreSQL Replication TutorialHans-Jürgen Schönig
3K views70 slides

What's hot(20)

Pgbr 2013 postgres on aws by Emanuel Calvo
Pgbr 2013   postgres on awsPgbr 2013   postgres on aws
Pgbr 2013 postgres on aws
Emanuel Calvo4.7K views
HBase Coprocessor Introduction by Schubert Zhang
HBase Coprocessor IntroductionHBase Coprocessor Introduction
HBase Coprocessor Introduction
Schubert Zhang12K views
Out of the box replication in postgres 9.4(pg confus) by Denish Patel
Out of the box replication in postgres 9.4(pg confus)Out of the box replication in postgres 9.4(pg confus)
Out of the box replication in postgres 9.4(pg confus)
Denish Patel1.1K views
Streaming replication in practice by Alexey Lesovsky
Streaming replication in practiceStreaming replication in practice
Streaming replication in practice
Alexey Lesovsky8.7K views
Failsafe Mechanism for Yahoo Homepage by Kit Chan
Failsafe Mechanism for Yahoo HomepageFailsafe Mechanism for Yahoo Homepage
Failsafe Mechanism for Yahoo Homepage
Kit Chan518 views
Scaling PostgreSQL with Skytools by Gavin Roy
Scaling PostgreSQL with SkytoolsScaling PostgreSQL with Skytools
Scaling PostgreSQL with Skytools
Gavin Roy5.1K views
plProxy, pgBouncer, pgBalancer by elliando dias
plProxy, pgBouncer, pgBalancerplProxy, pgBouncer, pgBalancer
plProxy, pgBouncer, pgBalancer
elliando dias7.1K views
Resources, Providers, and Helpers Oh My! by Brian Stajkowski
Resources, Providers, and Helpers Oh My!Resources, Providers, and Helpers Oh My!
Resources, Providers, and Helpers Oh My!
Brian Stajkowski1.4K views
HBaseCon 2013: A Developer’s Guide to Coprocessors by Cloudera, Inc.
HBaseCon 2013: A Developer’s Guide to CoprocessorsHBaseCon 2013: A Developer’s Guide to Coprocessors
HBaseCon 2013: A Developer’s Guide to Coprocessors
Cloudera, Inc.8K views
Replacing Squid with ATS by Kit Chan
Replacing Squid with ATSReplacing Squid with ATS
Replacing Squid with ATS
Kit Chan632 views
Postgresql database administration volume 1 by Federico Campoli
Postgresql database administration volume 1Postgresql database administration volume 1
Postgresql database administration volume 1
Federico Campoli33.3K views
Kafka Tutorial: Advanced Producers by Jean-Paul Azar
Kafka Tutorial: Advanced ProducersKafka Tutorial: Advanced Producers
Kafka Tutorial: Advanced Producers
Jean-Paul Azar203.2K views
GitLab PostgresMortem: Lessons Learned by Alexey Lesovsky
GitLab PostgresMortem: Lessons LearnedGitLab PostgresMortem: Lessons Learned
GitLab PostgresMortem: Lessons Learned
Alexey Lesovsky490 views
On The Building Of A PostgreSQL Cluster by Srihari Sriraman
On The Building Of A PostgreSQL ClusterOn The Building Of A PostgreSQL Cluster
On The Building Of A PostgreSQL Cluster
Srihari Sriraman1.1K views
PostgreSQL Performance Tuning by elliando dias
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuning
elliando dias4.1K views
Apache lb by Ksd Che
Apache lbApache lb
Apache lb
Ksd Che453 views
Kafka meetup JP #3 - Engineering Apache Kafka at LINE by kawamuray
Kafka meetup JP #3 - Engineering Apache Kafka at LINEKafka meetup JP #3 - Engineering Apache Kafka at LINE
Kafka meetup JP #3 - Engineering Apache Kafka at LINE
kawamuray2.4K views

Similar to How to Replicate PostgreSQL Database

Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica... by
Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...
Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...Command Prompt., Inc
2.7K views28 slides
PuppetConf 2016: An Introduction to Measuring and Tuning PE Performance – Cha... by
PuppetConf 2016: An Introduction to Measuring and Tuning PE Performance – Cha...PuppetConf 2016: An Introduction to Measuring and Tuning PE Performance – Cha...
PuppetConf 2016: An Introduction to Measuring and Tuning PE Performance – Cha...Puppet
1.2K views26 slides
Percona Xtrabackup - Highly Efficient Backups by
Percona Xtrabackup - Highly Efficient BackupsPercona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient BackupsMydbops
3.8K views45 slides
Out of the Box Replication in Postgres 9.4(PgConfUS) by
Out of the Box Replication in Postgres 9.4(PgConfUS)Out of the Box Replication in Postgres 9.4(PgConfUS)
Out of the Box Replication in Postgres 9.4(PgConfUS)Denish Patel
1K views52 slides
The Essential postgresql.conf by
The Essential postgresql.confThe Essential postgresql.conf
The Essential postgresql.confRobert Treat
7.7K views22 slides
Highly efficient backups with percona xtrabackup by
Highly efficient backups with percona xtrabackupHighly efficient backups with percona xtrabackup
Highly efficient backups with percona xtrabackupNilnandan Joshi
4.7K views34 slides

Similar to How to Replicate PostgreSQL Database(20)

Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica... by Command Prompt., Inc
Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...
Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...
PuppetConf 2016: An Introduction to Measuring and Tuning PE Performance – Cha... by Puppet
PuppetConf 2016: An Introduction to Measuring and Tuning PE Performance – Cha...PuppetConf 2016: An Introduction to Measuring and Tuning PE Performance – Cha...
PuppetConf 2016: An Introduction to Measuring and Tuning PE Performance – Cha...
Puppet1.2K views
Percona Xtrabackup - Highly Efficient Backups by Mydbops
Percona Xtrabackup - Highly Efficient BackupsPercona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient Backups
Mydbops3.8K views
Out of the Box Replication in Postgres 9.4(PgConfUS) by Denish Patel
Out of the Box Replication in Postgres 9.4(PgConfUS)Out of the Box Replication in Postgres 9.4(PgConfUS)
Out of the Box Replication in Postgres 9.4(PgConfUS)
Denish Patel1K views
The Essential postgresql.conf by Robert Treat
The Essential postgresql.confThe Essential postgresql.conf
The Essential postgresql.conf
Robert Treat7.7K views
Highly efficient backups with percona xtrabackup by Nilnandan Joshi
Highly efficient backups with percona xtrabackupHighly efficient backups with percona xtrabackup
Highly efficient backups with percona xtrabackup
Nilnandan Joshi4.7K views
The Magic of Hot Streaming Replication, Bruce Momjian by Fuenteovejuna
The Magic of Hot Streaming Replication, Bruce MomjianThe Magic of Hot Streaming Replication, Bruce Momjian
The Magic of Hot Streaming Replication, Bruce Momjian
Fuenteovejuna 1K views
Configuring Your First Hadoop Cluster On EC2 by benjaminwootton
Configuring Your First Hadoop Cluster On EC2Configuring Your First Hadoop Cluster On EC2
Configuring Your First Hadoop Cluster On EC2
benjaminwootton29.7K views
Percona Cluster with Master_Slave for Disaster Recovery by Ram Gautam
Percona Cluster with Master_Slave for Disaster RecoveryPercona Cluster with Master_Slave for Disaster Recovery
Percona Cluster with Master_Slave for Disaster Recovery
Ram Gautam339 views
Best Practices: Migrating a Postgres Production Database to the Cloud by EDB
Best Practices: Migrating a Postgres Production Database to the CloudBest Practices: Migrating a Postgres Production Database to the Cloud
Best Practices: Migrating a Postgres Production Database to the Cloud
EDB1.9K views
[MathWorks] Versioning Infrastructure by Perforce
[MathWorks] Versioning Infrastructure[MathWorks] Versioning Infrastructure
[MathWorks] Versioning Infrastructure
Perforce617 views
Percona xtrabackup - MySQL Meetup @ Mumbai by Nilnandan Joshi
Percona xtrabackup - MySQL Meetup @ MumbaiPercona xtrabackup - MySQL Meetup @ Mumbai
Percona xtrabackup - MySQL Meetup @ Mumbai
Nilnandan Joshi3.9K views
Advanced Data Migration Techniques for Amazon RDS (DAT308) | AWS re:Invent 2013 by Amazon Web Services
Advanced Data Migration Techniques for Amazon RDS (DAT308) | AWS re:Invent 2013Advanced Data Migration Techniques for Amazon RDS (DAT308) | AWS re:Invent 2013
Advanced Data Migration Techniques for Amazon RDS (DAT308) | AWS re:Invent 2013
Amazon Web Services16.1K views
How To Install Openbravo ERP 2.50 MP43 in Ubuntu by Wirabumi Software
How To Install Openbravo ERP 2.50 MP43 in UbuntuHow To Install Openbravo ERP 2.50 MP43 in Ubuntu
How To Install Openbravo ERP 2.50 MP43 in Ubuntu
Wirabumi Software1.8K views
Salesforce at Stacki Atlanta Meetup February 2016 by StackIQ
Salesforce at Stacki Atlanta Meetup February 2016Salesforce at Stacki Atlanta Meetup February 2016
Salesforce at Stacki Atlanta Meetup February 2016
StackIQ930 views

More from Brandon Kang

웹에 빠른 날개를 달아주는 웹 성능 향상 이야기 by
웹에 빠른 날개를 달아주는 웹 성능 향상 이야기웹에 빠른 날개를 달아주는 웹 성능 향상 이야기
웹에 빠른 날개를 달아주는 웹 성능 향상 이야기Brandon Kang
23 views43 slides
Web Performance Optimization with HTTP/3 by
Web Performance Optimization with HTTP/3Web Performance Optimization with HTTP/3
Web Performance Optimization with HTTP/3Brandon Kang
184 views37 slides
Scalability strategies for cloud based system architecture by
Scalability strategies for cloud based system architectureScalability strategies for cloud based system architecture
Scalability strategies for cloud based system architectureBrandon Kang
281 views39 slides
HTTP/3 시대의 웹 성능 최적화 기술 이해하기 by
HTTP/3 시대의 웹 성능 최적화 기술 이해하기HTTP/3 시대의 웹 성능 최적화 기술 이해하기
HTTP/3 시대의 웹 성능 최적화 기술 이해하기Brandon Kang
6.1K views39 slides
수요자 중심의 클라우드 운영 및 전략 (CIO Summit 2019) by
수요자 중심의 클라우드 운영 및 전략 (CIO Summit 2019)수요자 중심의 클라우드 운영 및 전략 (CIO Summit 2019)
수요자 중심의 클라우드 운영 및 전략 (CIO Summit 2019)Brandon Kang
254 views37 slides
How to develop and localize Xbox 360 titles by
How to develop and localize Xbox 360 titlesHow to develop and localize Xbox 360 titles
How to develop and localize Xbox 360 titlesBrandon Kang
281 views41 slides

More from Brandon Kang(15)

웹에 빠른 날개를 달아주는 웹 성능 향상 이야기 by Brandon Kang
웹에 빠른 날개를 달아주는 웹 성능 향상 이야기웹에 빠른 날개를 달아주는 웹 성능 향상 이야기
웹에 빠른 날개를 달아주는 웹 성능 향상 이야기
Brandon Kang23 views
Web Performance Optimization with HTTP/3 by Brandon Kang
Web Performance Optimization with HTTP/3Web Performance Optimization with HTTP/3
Web Performance Optimization with HTTP/3
Brandon Kang184 views
Scalability strategies for cloud based system architecture by Brandon Kang
Scalability strategies for cloud based system architectureScalability strategies for cloud based system architecture
Scalability strategies for cloud based system architecture
Brandon Kang281 views
HTTP/3 시대의 웹 성능 최적화 기술 이해하기 by Brandon Kang
HTTP/3 시대의 웹 성능 최적화 기술 이해하기HTTP/3 시대의 웹 성능 최적화 기술 이해하기
HTTP/3 시대의 웹 성능 최적화 기술 이해하기
Brandon Kang6.1K views
수요자 중심의 클라우드 운영 및 전략 (CIO Summit 2019) by Brandon Kang
수요자 중심의 클라우드 운영 및 전략 (CIO Summit 2019)수요자 중심의 클라우드 운영 및 전략 (CIO Summit 2019)
수요자 중심의 클라우드 운영 및 전략 (CIO Summit 2019)
Brandon Kang254 views
How to develop and localize Xbox 360 titles by Brandon Kang
How to develop and localize Xbox 360 titlesHow to develop and localize Xbox 360 titles
How to develop and localize Xbox 360 titles
Brandon Kang281 views
Akamai 서비스 트러블 슈팅 및 테스트 방법과 도구 by Brandon Kang
Akamai 서비스 트러블 슈팅 및 테스트 방법과 도구Akamai 서비스 트러블 슈팅 및 테스트 방법과 도구
Akamai 서비스 트러블 슈팅 및 테스트 방법과 도구
Brandon Kang1.3K views
HTTP 프로토콜의 이해와 활용 by Brandon Kang
HTTP 프로토콜의 이해와 활용HTTP 프로토콜의 이해와 활용
HTTP 프로토콜의 이해와 활용
Brandon Kang180 views
HTTP/2와 웹 성능 최적화 방안 by Brandon Kang
HTTP/2와 웹 성능 최적화 방안HTTP/2와 웹 성능 최적화 방안
HTTP/2와 웹 성능 최적화 방안
Brandon Kang3.9K views
Akamai Korea - Tech Day (2015/03/11) DNS by Brandon Kang
Akamai Korea - Tech Day (2015/03/11) DNSAkamai Korea - Tech Day (2015/03/11) DNS
Akamai Korea - Tech Day (2015/03/11) DNS
Brandon Kang1.4K views
Akamai Korea - Tech Day (2015/03/11) HTTP/2 by Brandon Kang
Akamai Korea - Tech Day (2015/03/11) HTTP/2Akamai Korea - Tech Day (2015/03/11) HTTP/2
Akamai Korea - Tech Day (2015/03/11) HTTP/2
Brandon Kang6.1K views
HTML5 for web app. development by Brandon Kang
HTML5 for web app. developmentHTML5 for web app. development
HTML5 for web app. development
Brandon Kang1.3K views
Agile - SCRUM을 통한 개발관리 by Brandon Kang
Agile - SCRUM을 통한 개발관리Agile - SCRUM을 통한 개발관리
Agile - SCRUM을 통한 개발관리
Brandon Kang13.4K views
XNA2.0 Network Programming by Brandon Kang
XNA2.0 Network ProgrammingXNA2.0 Network Programming
XNA2.0 Network Programming
Brandon Kang1.5K views

Recently uploaded

Short Story Assignment by Kelly Nguyen by
Short Story Assignment by Kelly NguyenShort Story Assignment by Kelly Nguyen
Short Story Assignment by Kelly Nguyenkellynguyen01
19 views17 slides
SUPER STORE SQL PROJECT.pptx by
SUPER STORE SQL PROJECT.pptxSUPER STORE SQL PROJECT.pptx
SUPER STORE SQL PROJECT.pptxkhan888620
12 views16 slides
Advanced_Recommendation_Systems_Presentation.pptx by
Advanced_Recommendation_Systems_Presentation.pptxAdvanced_Recommendation_Systems_Presentation.pptx
Advanced_Recommendation_Systems_Presentation.pptxneeharikasingh29
5 views9 slides
Chapter 3b- Process Communication (1) (1)(1) (1).pptx by
Chapter 3b- Process Communication (1) (1)(1) (1).pptxChapter 3b- Process Communication (1) (1)(1) (1).pptx
Chapter 3b- Process Communication (1) (1)(1) (1).pptxayeshabaig2004
5 views30 slides
[DSC Europe 23] Milos Grubjesic Empowering Business with Pepsico s Advanced M... by
[DSC Europe 23] Milos Grubjesic Empowering Business with Pepsico s Advanced M...[DSC Europe 23] Milos Grubjesic Empowering Business with Pepsico s Advanced M...
[DSC Europe 23] Milos Grubjesic Empowering Business with Pepsico s Advanced M...DataScienceConferenc1
5 views11 slides
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdf by
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdfVikas 500 BIG DATA TECHNOLOGIES LAB.pdf
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdfvikas12611618
8 views30 slides

Recently uploaded(20)

Short Story Assignment by Kelly Nguyen by kellynguyen01
Short Story Assignment by Kelly NguyenShort Story Assignment by Kelly Nguyen
Short Story Assignment by Kelly Nguyen
kellynguyen0119 views
SUPER STORE SQL PROJECT.pptx by khan888620
SUPER STORE SQL PROJECT.pptxSUPER STORE SQL PROJECT.pptx
SUPER STORE SQL PROJECT.pptx
khan88862012 views
Advanced_Recommendation_Systems_Presentation.pptx by neeharikasingh29
Advanced_Recommendation_Systems_Presentation.pptxAdvanced_Recommendation_Systems_Presentation.pptx
Advanced_Recommendation_Systems_Presentation.pptx
Chapter 3b- Process Communication (1) (1)(1) (1).pptx by ayeshabaig2004
Chapter 3b- Process Communication (1) (1)(1) (1).pptxChapter 3b- Process Communication (1) (1)(1) (1).pptx
Chapter 3b- Process Communication (1) (1)(1) (1).pptx
ayeshabaig20045 views
[DSC Europe 23] Milos Grubjesic Empowering Business with Pepsico s Advanced M... by DataScienceConferenc1
[DSC Europe 23] Milos Grubjesic Empowering Business with Pepsico s Advanced M...[DSC Europe 23] Milos Grubjesic Empowering Business with Pepsico s Advanced M...
[DSC Europe 23] Milos Grubjesic Empowering Business with Pepsico s Advanced M...
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdf by vikas12611618
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdfVikas 500 BIG DATA TECHNOLOGIES LAB.pdf
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdf
vikas126116188 views
Ukraine Infographic_22NOV2023_v2.pdf by AnastosiyaGurin
Ukraine Infographic_22NOV2023_v2.pdfUkraine Infographic_22NOV2023_v2.pdf
Ukraine Infographic_22NOV2023_v2.pdf
AnastosiyaGurin1.4K views
CRIJ4385_Death Penalty_F23.pptx by yvettemm100
CRIJ4385_Death Penalty_F23.pptxCRIJ4385_Death Penalty_F23.pptx
CRIJ4385_Death Penalty_F23.pptx
yvettemm1006 views
Cross-network in Google Analytics 4.pdf by GA4 Tutorials
Cross-network in Google Analytics 4.pdfCross-network in Google Analytics 4.pdf
Cross-network in Google Analytics 4.pdf
GA4 Tutorials6 views
[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx by DataScienceConferenc1
[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx
[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx
Organic Shopping in Google Analytics 4.pdf by GA4 Tutorials
Organic Shopping in Google Analytics 4.pdfOrganic Shopping in Google Analytics 4.pdf
Organic Shopping in Google Analytics 4.pdf
GA4 Tutorials12 views
Survey on Factuality in LLM's.pptx by NeethaSherra1
Survey on Factuality in LLM's.pptxSurvey on Factuality in LLM's.pptx
Survey on Factuality in LLM's.pptx
NeethaSherra15 views
[DSC Europe 23] Spela Poklukar & Tea Brasanac - Retrieval Augmented Generation by DataScienceConferenc1
[DSC Europe 23] Spela Poklukar & Tea Brasanac - Retrieval Augmented Generation[DSC Europe 23] Spela Poklukar & Tea Brasanac - Retrieval Augmented Generation
[DSC Europe 23] Spela Poklukar & Tea Brasanac - Retrieval Augmented Generation

How to Replicate PostgreSQL Database

  • 1. Service Platform Architect Brandon Kang sangjinn@gmail.com https://tech.brandonkang.net July 2020 How to Replicate PostgreSQL Database / / 0 2 / . 2 : / 2 . / A @ /: / / /
  • 2. Replication Overall Primary Server • A server for both READ and WRITE Standby Server = Slave server, Backup server, Replica, etc. • A server where the data is kept in sync with the master continuously • A warm standby server can’t be connected until it is promoted to primary • A hot standby server accepts connections and serves read-only queries • Data is written to the master server and propagated to the slave servers • When primary server has an issue, a standby server will take over and continue to take ‘WRITE” process
  • 3. WAL Shipping Replication WAL(Write-Ahead Logging) • A log file where all the modifications to the database • WAL is used for recovery after a database crash, ensuring data integrity • WAL is used in database systems to achieve atomicity and durability WAL based Replication ­ Streaming WAL Records • Write-ahead log records are used to keep the data in sync • WAL record chunks are streamed by database servers to synchronize • Standby server connects to the master to receive the WAL chunks • WAL records are streamed as they are generated • The streaming of WAL records need not wait for the WAL file to be filled
  • 4. Streaming Replication PRIMARY Server Standby Server WAL Sender WAL Receiver WAL Record READ ONLYREAD/WRITE pg_wal directory WAL File pg_wal directory WAL File Synchronize - WAL Record1 - WAL Record2 - WAL Record3 ……
  • 5. Replication Configuration Primary Node ­ pg_hba.conf /PG_HOME/DATA/pg_hba.conf # Allow replication connections from localhost, # by a user with the replication privilege. # TYPE DATABASE USER ADDRESS METHOD host replication repl_user IPaddress(CIDR) md5 Restart PostgreSQL service on the primary node Internal IP ranges Firewall Open for this.
  • 6. Replication Configuration Primary Node ­/PG_HOME/DATA/postgres.conf # Possible values are replica|minimal|logical wal_level = hot_standby archive_mode = on #Syncronize with Primany node using wal archive archive_command = ‘cp %p /PG_TBS/backup/archive/%f’ #psql_superuser archive backup # required for pg_rewind capability when standby goes out of sync with master wal_log_hints = on # sets the maximum number of concurrent connections from the standby servers. max_wal_senders = 2 # The below parameter is used to tell the master to keep the minimum number of # segments of WAL logs so that they are not deleted before standby consumes them. # each segment is 16MB wal_keep_segments = 16
  • 7. Replication Configuration Secondary Node ­/PG_HOME/DATA/postgres.conf hot_standby = on Secondary Node ­/PG_HOME/DATA/recovery.conf standby_mode = ‘on’ restore_command = ‘cp %p /PG_TBS/backup/archive/%f “%p”’ Primary_conninfo = ‘host=… ports=… user=postgres password= application_name=slave1’ # Explaining a few options used for pg_basebackup utility # -X option is used to include the required transaction log files (WAL files) in the # backup. When you specify stream, this will open a second connection to the server # and start streaming the transaction log at the same time as running the backup. # -c is the checkpoint option. Setting it to fast will force the checkpoint to be # created soon. # -W forces pg_basebackup to prompt for a password before connecting # to a database. pg_basebackup -D <data_directory> -h <master_host> -X stream -c fast -U repl_user -W
  • 8. Replication Configuration Secondary Node ­ pg_basebackup utility # Explaining a few options used for pg_basebackup utility # -X option is used to include the required transaction log files (WAL files) in the # backup. When you specify stream, this will open a second connection to the server # and start streaming the transaction log at the same time as running the backup. # -c is the checkpoint option. Setting it to fast will force the checkpoint to be # created soon. # -W forces pg_basebackup to prompt for a password before connecting # to a database. pg_basebackup -D <data_directory> -h <master_host> -X stream -c fast -U repl_user -W Example) $pg_basebackup ­h localhost ­p 5170 -u postgres ­D /PG_TBS/cluster -checkpoint=fast --progress
  • 9. Replication Configuration Secondary Node ­ Replication configuration file # Specifies whether to start the server as a standby. In streaming replication, # this parameter must be set to on. standby_mode = ‘on’ # Specifies a connection string which is used for the standby server to connect # with the primary/master. primary_conninfo = ‘host=<master_host> port=<postgres_port> user=<replication_user> password=<password> application_name=”host_name”’ # Specifies recovering to a particular timeline. The default is to recover along the # same timeline that was current when the base backup was taken. # Setting this to latest recovers to the latest timeline found # in the archive, which is useful in a standby server. recovery_target_timeline = ‘latest’ Start PostgreSQL service on the Standby node
  • 10. Replication Testing postgres=# select * from pg_stat_replication ; -[ RECORD 1 ]----+--------------------------------- pid | 1114 usesysid | 16384 usename | repuser application_name | walreceiver client_addr | 127.0.0.1 client_hostname | client_port | 52444 backend_start | 08-MAR-20 19:54:05.535695 -04:00 state | streaming .. sync_priority | 0 sync_state | async ps ­ef | grep postgres [Master] wal sender process check [Standby] wal receiver & startup process check SELECT * FROM pg_stat_replication; Query execution on the Primary/Standby nodes
  • 11. Replication Testing pg_is_in_recovery(): A function to check if standby server is still in recovery mode or not postgres=# select pg_is_in_recovery(); pg_is_in_recovery ------------------- t (1 row) pg_last_xact_replay_timestamp(): A function shows time stamp of last replica transaction postgres=# select pg_last_xact_replay_timestamp(); pg_last_xact_replay_timestamp ---------------------------------- 08-MAR-20 20:54:27.635591 -04:00 (1 row) SELECT CASE WHEN pg_last_xlog_receive_location() = pg_last_xlog_replay_location() THEN 0 ELSE EXTRACT (EPOCH FROM now() - pg_last_xact_replay_timestamp()) END AS log_delay; Calculating logs in seconds
  • 12. Scaling PostgreSQL PRIMARY Server Standby Server WAL Sender WAL Receiver WAL Record WRITE Synchronize HAProxy / NGINX / F5 READ WRITE READ pgBouncer primary_db standby_db Application
  • 13. - Thank You. - Service Platform Architect Brandon Kang sangjinn@gmail.com https://tech.brandonkang.net