SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Pgbr 2013 postgres on aws
Pgbr 2013   postgres on awsPgbr 2013   postgres on aws
Pgbr 2013 postgres on aws
Emanuel Calvo
 
HBase Coprocessor Introduction
HBase Coprocessor IntroductionHBase Coprocessor Introduction
HBase Coprocessor Introduction
Schubert Zhang
 
ProstgreSQLFailoverConfiguration
ProstgreSQLFailoverConfigurationProstgreSQLFailoverConfiguration
ProstgreSQLFailoverConfiguration
Suyog Shirgaonkar
 
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)
Out of the box replication in postgres 9.4(pg confus)
Denish Patel
 
Streaming replication in practice
Streaming replication in practiceStreaming replication in practice
Streaming replication in practice
Alexey Lesovsky
 
PostgreSQL Replication Tutorial
PostgreSQL Replication TutorialPostgreSQL Replication Tutorial
PostgreSQL Replication Tutorial
Hans-Jürgen Schönig
 
Failsafe Mechanism for Yahoo Homepage
Failsafe Mechanism for Yahoo HomepageFailsafe Mechanism for Yahoo Homepage
Failsafe Mechanism for Yahoo Homepage
Kit Chan
 
Scaling PostgreSQL with Skytools
Scaling PostgreSQL with SkytoolsScaling PostgreSQL with Skytools
Scaling PostgreSQL with Skytools
Gavin Roy
 
plProxy, pgBouncer, pgBalancer
plProxy, pgBouncer, pgBalancerplProxy, pgBouncer, pgBalancer
plProxy, pgBouncer, pgBalancer
elliando dias
 
Resources, Providers, and Helpers Oh My!
Resources, Providers, and Helpers Oh My!Resources, Providers, and Helpers Oh My!
Resources, Providers, and Helpers Oh My!
Brian Stajkowski
 
HBaseCon 2013: A Developer’s Guide to Coprocessors
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.
 
Replacing Squid with ATS
Replacing Squid with ATSReplacing Squid with ATS
Replacing Squid with ATS
Kit Chan
 
Postgresql database administration volume 1
Postgresql database administration volume 1Postgresql database administration volume 1
Postgresql database administration volume 1
Federico Campoli
 
Kafka Tutorial: Advanced Producers
Kafka Tutorial: Advanced ProducersKafka Tutorial: Advanced Producers
Kafka Tutorial: Advanced Producers
Jean-Paul Azar
 
Kafka: Internals
Kafka: InternalsKafka: Internals
Kafka: Internals
Knoldus Inc.
 
GitLab PostgresMortem: Lessons Learned
GitLab PostgresMortem: Lessons LearnedGitLab PostgresMortem: Lessons Learned
GitLab PostgresMortem: Lessons Learned
Alexey Lesovsky
 
On The Building Of A PostgreSQL Cluster
On The Building Of A PostgreSQL ClusterOn The Building Of A PostgreSQL Cluster
On The Building Of A PostgreSQL Cluster
Srihari Sriraman
 
PostgreSQL Performance Tuning
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuning
elliando dias
 
Apache lb
Apache lbApache lb
Apache lb
Ksd Che
 
Kafka meetup JP #3 - Engineering Apache Kafka at LINE
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
kawamuray
 
Pgbr 2013 postgres on aws
Pgbr 2013   postgres on awsPgbr 2013   postgres on aws
Pgbr 2013 postgres on aws
Emanuel Calvo
 
HBase Coprocessor Introduction
HBase Coprocessor IntroductionHBase Coprocessor Introduction
HBase Coprocessor Introduction
Schubert Zhang
 
ProstgreSQLFailoverConfiguration
ProstgreSQLFailoverConfigurationProstgreSQLFailoverConfiguration
ProstgreSQLFailoverConfiguration
Suyog Shirgaonkar
 
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)
Out of the box replication in postgres 9.4(pg confus)
Denish Patel
 
Streaming replication in practice
Streaming replication in practiceStreaming replication in practice
Streaming replication in practice
Alexey Lesovsky
 
Failsafe Mechanism for Yahoo Homepage
Failsafe Mechanism for Yahoo HomepageFailsafe Mechanism for Yahoo Homepage
Failsafe Mechanism for Yahoo Homepage
Kit Chan
 
Scaling PostgreSQL with Skytools
Scaling PostgreSQL with SkytoolsScaling PostgreSQL with Skytools
Scaling PostgreSQL with Skytools
Gavin Roy
 
plProxy, pgBouncer, pgBalancer
plProxy, pgBouncer, pgBalancerplProxy, pgBouncer, pgBalancer
plProxy, pgBouncer, pgBalancer
elliando dias
 
Resources, Providers, and Helpers Oh My!
Resources, Providers, and Helpers Oh My!Resources, Providers, and Helpers Oh My!
Resources, Providers, and Helpers Oh My!
Brian Stajkowski
 
HBaseCon 2013: A Developer’s Guide to Coprocessors
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.
 
Replacing Squid with ATS
Replacing Squid with ATSReplacing Squid with ATS
Replacing Squid with ATS
Kit Chan
 
Postgresql database administration volume 1
Postgresql database administration volume 1Postgresql database administration volume 1
Postgresql database administration volume 1
Federico Campoli
 
Kafka Tutorial: Advanced Producers
Kafka Tutorial: Advanced ProducersKafka Tutorial: Advanced Producers
Kafka Tutorial: Advanced Producers
Jean-Paul Azar
 
GitLab PostgresMortem: Lessons Learned
GitLab PostgresMortem: Lessons LearnedGitLab PostgresMortem: Lessons Learned
GitLab PostgresMortem: Lessons Learned
Alexey Lesovsky
 
On The Building Of A PostgreSQL Cluster
On The Building Of A PostgreSQL ClusterOn The Building Of A PostgreSQL Cluster
On The Building Of A PostgreSQL Cluster
Srihari Sriraman
 
PostgreSQL Performance Tuning
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuning
elliando dias
 
Apache lb
Apache lbApache lb
Apache lb
Ksd Che
 
Kafka meetup JP #3 - Engineering Apache Kafka at LINE
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
kawamuray
 

Similar to How to Replicate PostgreSQL Database (20)

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...
Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...
Command Prompt., Inc
 
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...
PuppetConf 2016: An Introduction to Measuring and Tuning PE Performance – Cha...
Puppet
 
StreSd332g_ReplADSSAon_aerasd333333.pptx
StreSd332g_ReplADSSAon_aerasd333333.pptxStreSd332g_ReplADSSAon_aerasd333333.pptx
StreSd332g_ReplADSSAon_aerasd333333.pptx
anand90rm
 
Percona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient BackupsPercona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient Backups
Mydbops
 
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)
Out of the Box Replication in Postgres 9.4(PgConfUS)
Denish Patel
 
The Essential postgresql.conf
The Essential postgresql.confThe Essential postgresql.conf
The Essential postgresql.conf
Robert Treat
 
Highly efficient backups with percona xtrabackup
Highly efficient backups with percona xtrabackupHighly efficient backups with percona xtrabackup
Highly efficient backups with percona xtrabackup
Nilnandan Joshi
 
The Magic of Hot Streaming Replication, Bruce Momjian
The Magic of Hot Streaming Replication, Bruce MomjianThe Magic of Hot Streaming Replication, Bruce Momjian
The Magic of Hot Streaming Replication, Bruce Momjian
Fuenteovejuna
 
Configuring Your First Hadoop Cluster On EC2
Configuring Your First Hadoop Cluster On EC2Configuring Your First Hadoop Cluster On EC2
Configuring Your First Hadoop Cluster On EC2
benjaminwootton
 
Percona Cluster with Master_Slave for Disaster Recovery
Percona Cluster with Master_Slave for Disaster RecoveryPercona Cluster with Master_Slave for Disaster Recovery
Percona Cluster with Master_Slave for Disaster Recovery
Ram Gautam
 
MySQL database replication
MySQL database replicationMySQL database replication
MySQL database replication
PoguttuezhiniVP
 
Best Practices: Migrating a Postgres Production Database to the Cloud
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
EDB
 
[MathWorks] Versioning Infrastructure
[MathWorks] Versioning Infrastructure[MathWorks] Versioning Infrastructure
[MathWorks] Versioning Infrastructure
Perforce
 
PG_Phsycal_logical_study_Replication.pptx
PG_Phsycal_logical_study_Replication.pptxPG_Phsycal_logical_study_Replication.pptx
PG_Phsycal_logical_study_Replication.pptx
ankitmodidba
 
Scale Apache with Nginx
Scale Apache with NginxScale Apache with Nginx
Scale Apache with Nginx
Bud Siddhisena
 
Percona xtrabackup - MySQL Meetup @ Mumbai
Percona xtrabackup - MySQL Meetup @ MumbaiPercona xtrabackup - MySQL Meetup @ Mumbai
Percona xtrabackup - MySQL Meetup @ Mumbai
Nilnandan Joshi
 
515689311-Postgresql-DBA-Architecture.pptx
515689311-Postgresql-DBA-Architecture.pptx515689311-Postgresql-DBA-Architecture.pptx
515689311-Postgresql-DBA-Architecture.pptx
ssuser03ec3c
 
Architecting cloud
Architecting cloudArchitecting cloud
Architecting cloud
Tahsin Hasan
 
How To Install Openbravo ERP 2.50 MP43 in Ubuntu
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 Software
 
Database Replication
Database ReplicationDatabase Replication
Database Replication
Vatroslav Mileusnić
 
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...
Building tungsten-clusters-with-postgre sql-hot-standby-and-streaming-replica...
Command Prompt., Inc
 
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...
PuppetConf 2016: An Introduction to Measuring and Tuning PE Performance – Cha...
Puppet
 
StreSd332g_ReplADSSAon_aerasd333333.pptx
StreSd332g_ReplADSSAon_aerasd333333.pptxStreSd332g_ReplADSSAon_aerasd333333.pptx
StreSd332g_ReplADSSAon_aerasd333333.pptx
anand90rm
 
Percona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient BackupsPercona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient Backups
Mydbops
 
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)
Out of the Box Replication in Postgres 9.4(PgConfUS)
Denish Patel
 
The Essential postgresql.conf
The Essential postgresql.confThe Essential postgresql.conf
The Essential postgresql.conf
Robert Treat
 
Highly efficient backups with percona xtrabackup
Highly efficient backups with percona xtrabackupHighly efficient backups with percona xtrabackup
Highly efficient backups with percona xtrabackup
Nilnandan Joshi
 
The Magic of Hot Streaming Replication, Bruce Momjian
The Magic of Hot Streaming Replication, Bruce MomjianThe Magic of Hot Streaming Replication, Bruce Momjian
The Magic of Hot Streaming Replication, Bruce Momjian
Fuenteovejuna
 
Configuring Your First Hadoop Cluster On EC2
Configuring Your First Hadoop Cluster On EC2Configuring Your First Hadoop Cluster On EC2
Configuring Your First Hadoop Cluster On EC2
benjaminwootton
 
Percona Cluster with Master_Slave for Disaster Recovery
Percona Cluster with Master_Slave for Disaster RecoveryPercona Cluster with Master_Slave for Disaster Recovery
Percona Cluster with Master_Slave for Disaster Recovery
Ram Gautam
 
MySQL database replication
MySQL database replicationMySQL database replication
MySQL database replication
PoguttuezhiniVP
 
Best Practices: Migrating a Postgres Production Database to the Cloud
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
EDB
 
[MathWorks] Versioning Infrastructure
[MathWorks] Versioning Infrastructure[MathWorks] Versioning Infrastructure
[MathWorks] Versioning Infrastructure
Perforce
 
PG_Phsycal_logical_study_Replication.pptx
PG_Phsycal_logical_study_Replication.pptxPG_Phsycal_logical_study_Replication.pptx
PG_Phsycal_logical_study_Replication.pptx
ankitmodidba
 
Scale Apache with Nginx
Scale Apache with NginxScale Apache with Nginx
Scale Apache with Nginx
Bud Siddhisena
 
Percona xtrabackup - MySQL Meetup @ Mumbai
Percona xtrabackup - MySQL Meetup @ MumbaiPercona xtrabackup - MySQL Meetup @ Mumbai
Percona xtrabackup - MySQL Meetup @ Mumbai
Nilnandan Joshi
 
515689311-Postgresql-DBA-Architecture.pptx
515689311-Postgresql-DBA-Architecture.pptx515689311-Postgresql-DBA-Architecture.pptx
515689311-Postgresql-DBA-Architecture.pptx
ssuser03ec3c
 
Architecting cloud
Architecting cloudArchitecting cloud
Architecting cloud
Tahsin Hasan
 
How To Install Openbravo ERP 2.50 MP43 in Ubuntu
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 Software
 
Ad

More from SangJin Kang (15)

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

Recently uploaded (20)

Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..
yuvarajreddy2002
 
Simple_AI_Explanation_English somplr.pptx
Simple_AI_Explanation_English somplr.pptxSimple_AI_Explanation_English somplr.pptx
Simple_AI_Explanation_English somplr.pptx
ssuser2aa19f
 
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
gmuir1066
 
VKS-Python-FIe Handling text CSV Binary.pptx
VKS-Python-FIe Handling text CSV Binary.pptxVKS-Python-FIe Handling text CSV Binary.pptx
VKS-Python-FIe Handling text CSV Binary.pptx
Vinod Srivastava
 
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
ThanushsaranS
 
FPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptxFPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptx
ssuser4ef83d
 
Data Analytics Overview and its applications
Data Analytics Overview and its applicationsData Analytics Overview and its applications
Data Analytics Overview and its applications
JanmejayaMishra7
 
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjks
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjksPpt. Nikhil.pptxnshwuudgcudisisshvehsjks
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjks
panchariyasahil
 
Ch3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendencyCh3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendency
ayeleasefa2
 
chapter3 Central Tendency statistics.ppt
chapter3 Central Tendency statistics.pptchapter3 Central Tendency statistics.ppt
chapter3 Central Tendency statistics.ppt
justinebandajbn
 
03 Daniel 2-notes.ppt seminario escatologia
03 Daniel 2-notes.ppt seminario escatologia03 Daniel 2-notes.ppt seminario escatologia
03 Daniel 2-notes.ppt seminario escatologia
Alexander Romero Arosquipa
 
Deloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit contextDeloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit context
Process mining Evangelist
 
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Abodahab
 
How to join illuminati Agent in uganda call+256776963507/0741506136
How to join illuminati Agent in uganda call+256776963507/0741506136How to join illuminati Agent in uganda call+256776963507/0741506136
How to join illuminati Agent in uganda call+256776963507/0741506136
illuminati Agent uganda call+256776963507/0741506136
 
Developing Security Orchestration, Automation, and Response Applications
Developing Security Orchestration, Automation, and Response ApplicationsDeveloping Security Orchestration, Automation, and Response Applications
Developing Security Orchestration, Automation, and Response Applications
VICTOR MAESTRE RAMIREZ
 
183409-christina-rossetti.pdfdsfsdasggsag
183409-christina-rossetti.pdfdsfsdasggsag183409-christina-rossetti.pdfdsfsdasggsag
183409-christina-rossetti.pdfdsfsdasggsag
fardin123rahman07
 
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.pptJust-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
ssuser5f8f49
 
computer organization and assembly language.docx
computer organization and assembly language.docxcomputer organization and assembly language.docx
computer organization and assembly language.docx
alisoftwareengineer1
 
LLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bertLLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bert
ChadapornK
 
Digilocker under workingProcess Flow.pptx
Digilocker  under workingProcess Flow.pptxDigilocker  under workingProcess Flow.pptx
Digilocker under workingProcess Flow.pptx
satnamsadguru491
 
Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..
yuvarajreddy2002
 
Simple_AI_Explanation_English somplr.pptx
Simple_AI_Explanation_English somplr.pptxSimple_AI_Explanation_English somplr.pptx
Simple_AI_Explanation_English somplr.pptx
ssuser2aa19f
 
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
gmuir1066
 
VKS-Python-FIe Handling text CSV Binary.pptx
VKS-Python-FIe Handling text CSV Binary.pptxVKS-Python-FIe Handling text CSV Binary.pptx
VKS-Python-FIe Handling text CSV Binary.pptx
Vinod Srivastava
 
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
ThanushsaranS
 
FPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptxFPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptx
ssuser4ef83d
 
Data Analytics Overview and its applications
Data Analytics Overview and its applicationsData Analytics Overview and its applications
Data Analytics Overview and its applications
JanmejayaMishra7
 
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjks
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjksPpt. Nikhil.pptxnshwuudgcudisisshvehsjks
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjks
panchariyasahil
 
Ch3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendencyCh3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendency
ayeleasefa2
 
chapter3 Central Tendency statistics.ppt
chapter3 Central Tendency statistics.pptchapter3 Central Tendency statistics.ppt
chapter3 Central Tendency statistics.ppt
justinebandajbn
 
Deloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit contextDeloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit context
Process mining Evangelist
 
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Abodahab
 
Developing Security Orchestration, Automation, and Response Applications
Developing Security Orchestration, Automation, and Response ApplicationsDeveloping Security Orchestration, Automation, and Response Applications
Developing Security Orchestration, Automation, and Response Applications
VICTOR MAESTRE RAMIREZ
 
183409-christina-rossetti.pdfdsfsdasggsag
183409-christina-rossetti.pdfdsfsdasggsag183409-christina-rossetti.pdfdsfsdasggsag
183409-christina-rossetti.pdfdsfsdasggsag
fardin123rahman07
 
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.pptJust-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
ssuser5f8f49
 
computer organization and assembly language.docx
computer organization and assembly language.docxcomputer organization and assembly language.docx
computer organization and assembly language.docx
alisoftwareengineer1
 
LLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bertLLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bert
ChadapornK
 
Digilocker under workingProcess Flow.pptx
Digilocker  under workingProcess Flow.pptxDigilocker  under workingProcess Flow.pptx
Digilocker under workingProcess Flow.pptx
satnamsadguru491
 

How to Replicate PostgreSQL Database

  • 1. Service Platform Architect Brandon Kang [email protected] 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 [email protected] https://tech.brandonkang.net