SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
The Magic of Hot
Streaming Replication
BRUCE MOMJIAN,
ENTERPRISEDB
October, 2010
Abstract
POSTGRESQL 9.0 offers new facilities for maintaining a current
standby server and for issuing read-only queries on the standby
server. This tutorial covers these new facilities.
Creative Commons Attribution License http://momjian.us/presentations
Introduction
 
How does WAL combined with a disk image enable standby servers?
(review)
 
How do you configure continuous archiving?
 
How do you configure a streaming, read-only server?
 
Multi-Server complexities
 
Primary/Standby synchronization complexities
The Magic of Hot Streaming Replication 2
Write-Ahead Logging (xlog)
fsync
fsync
Backend
Postgres
Backend
Postgres
Backend
Postgres
PostgreSQL Shared Buffer Cache Write−Ahead Log
Kernel Disk Buffer Cache
Disk Blocks
The Magic of Hot Streaming Replication 3
Pre-9.0 Continuous Archiving /
Point-In-Time Recovery (PITR)0200
1100
0900
1300
W
AL
W
ALWAL
ContinuousFile System−
Level Backup Archive (WAL)
The Magic of Hot Streaming Replication 4
PITR Backup Procedures
1. archive_command = ’cp -i %p /mnt/server/pgsql/%f < /dev/null’
2. SELECT pg_start_backup(’label’);
3. Perform file system-level backup (can be inconsistent)
4. SELECT pg_stop_backup();
The Magic of Hot Streaming Replication 5
PITR Recovery
W
AL
W
AL
1700
1730
1740
1755
WAL
ContinuousFile System−
Level Backup Archive (WAL)
The Magic of Hot Streaming Replication 6
PITR Recovery Procedures
1. Stop postmaster
2. Restore file system-level backup
3. Make adjustments as outlined in the documentation
4. Create recovery.conf
5. restore_command = ’cp /mnt/server/pgsql/%f %p’
6. Start the postmaster
The Magic of Hot Streaming Replication 7
Disadvantages
 
Only complete 16MB files can be shipped
 
archive_timeout can be used to force more frequent shipping (this
increases archive storage requirements)
 
No queries on the standby
The Magic of Hot Streaming Replication 8
9.0 Streaming Replication / Hot Standby
 
Changes are streamed to the standby, greatly reducing log shipping
delays
 
Standby can accept read-only queries
The Magic of Hot Streaming Replication 9
Streaming Replication Differs from PITR
 
File system backup is restored immediately on the standby server
 
WAL files are streamed to the slave
 
WAL files can also be archived if point-in-time recovery (PITR) is
desired
The Magic of Hot Streaming Replication 10
How Does Streaming Replication Work?
0200
1100
0900
1300
W
AL
W
ALWAL
File System−
Level Backup Server
Standby
The Magic of Hot Streaming Replication 11
Live Streaming Replication
archive
command
archive
command
Primary Standby
Network
/pg_xlog/pg_xlog
Archive
Directory
WAL
The Magic of Hot Streaming Replication 12
Enable Streaming to the Standby
Enable the proper WAL contents:
wal_level = hot_standby
Retain WAL files needed by the standby:
wal_keep_segments = 50
Enable the ability to stream WAL to the standby:
max_wal_senders = 1
The Magic of Hot Streaming Replication 13
Enable Standby Connection Permissions
Add permission for replication to pg_hba.conf:
host replication all 127.0.0.1/32 trust
Start the primary server:
pg_ctl -l /u/pg/data/server.log start
The Magic of Hot Streaming Replication 14
Perform a WAL-Supported File System Backup
Start psql and issue:
SELECT pg_start_backup(’testing’);
Copy the database /u/pg/data to a new directory, /u/pg/data2:
cp -p -R /u/pg/data /u/pg/data2
Dash-p preserves ownership. The copy is inconsistent, but that is okay
(WAL replay will correct that).
Signal the backup is complete from psql:
SELECT pg_stop_backup();
The Magic of Hot Streaming Replication 15
Configure the Standby
Remove /data2/postmaster.pid so the standby server does not see the
primary server’s pid as its own:
rm /u/pg/data2/postmaster.pid
(This is only necessary because we are testing with the primary and slave
on the same computer.)
Edit postgresql.conf on the standby and change the port to 5433
port = 5433
Enable hot standby in postgresql.conf:
hot_standby = on
The Magic of Hot Streaming Replication 16
Configure the Standby For Streaming Replication
Create recovery.conf:
cp /u/pg/share/recovery.conf.sample /u/pg/data2/recovery.conf
Enable streaming in recovery.conf:
standby_mode = ’on’
primary_conninfo = ’host=localhost port=5432’
Start the standby server:
PGDATA=/u/pg/data2 pg_ctl -l /u/pg/data2/server.log start
The Magic of Hot Streaming Replication 17
Test Streaming Replication and Hot Standby
$ psql -p 5432 -c ’CREATE TABLE streamtest(x int)’ postgres
$ psql -p 5433 -c ’d’ postgres
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | streamtest | table | postgres
(1 row)
$ psql -p 5432 -c ’INSERT INTO streamtest VALUES (1)’ postgres
INSERT 0 1
$ psql -p 5433 -c ’INSERT INTO streamtest VALUES (1)’ postgres
ERROR: cannot execute INSERT in a read-only transaction
The Magic of Hot Streaming Replication 18
Additional Complexities
 
Multi-server permissions
 
Stream from /pg_xlog and the continuous archive directory if
archive_mode is enabled on the primary
The Magic of Hot Streaming Replication 19
Primary/Standby Synchronization Issues
The primary server can take actions that cause long-running queries on
the standby to be cancelled. Specifically, the cleanup of unnecessary
rows that are still of interest to long-running queries on the standby can
cause long-running queries to be cancelled on the standby. Standby
query cancellation can be minimized in two ways:
1. Delay cleanup of old records on the primary with
vacuum_defer_cleanup_age in postgresql.conf.
2. Delay application of WAL logs on the standby with max_standby_delay
in postgresql.conf. The default is 30 seconds; -1 causes application to
delay indefinitely to prevent query cancellation. This also delays
changes from appearing on the standby and can lengthen the time
required for failover to the slave.
The Magic of Hot Streaming Replication 20
Conclusion
http://momjian.us/presentations Manet, Bar at Folies Bergère
The Magic of Hot Streaming Replication 21

Weitere ähnliche Inhalte

Was ist angesagt?

MySQL replication & cluster
MySQL replication & clusterMySQL replication & cluster
MySQL replication & cluster
elliando dias
 
Schema replication using oracle golden gate 12c
Schema replication using oracle golden gate 12cSchema replication using oracle golden gate 12c
Schema replication using oracle golden gate 12c
uzzal basak
 
Out of the Box Replication in Postgres 9.4(pgconfsf)
Out of the Box Replication in Postgres 9.4(pgconfsf)Out of the Box Replication in Postgres 9.4(pgconfsf)
Out of the Box Replication in Postgres 9.4(pgconfsf)
Denish Patel
 
TOROS: Python Framework for Recommender System
TOROS: Python Framework for Recommender SystemTOROS: Python Framework for Recommender System
TOROS: Python Framework for Recommender System
Kwangseob Kim
 
Velocity 2017 Performance analysis superpowers with Linux eBPF
Velocity 2017 Performance analysis superpowers with Linux eBPFVelocity 2017 Performance analysis superpowers with Linux eBPF
Velocity 2017 Performance analysis superpowers with Linux eBPF
Brendan Gregg
 
Running hadoop on ubuntu linux
Running hadoop on ubuntu linuxRunning hadoop on ubuntu linux
Running hadoop on ubuntu linux
TRCK
 

Was ist angesagt? (20)

Postgres-BDR with Google Cloud Platform
Postgres-BDR with Google Cloud PlatformPostgres-BDR with Google Cloud Platform
Postgres-BDR with Google Cloud Platform
 
MySQL replication & cluster
MySQL replication & clusterMySQL replication & cluster
MySQL replication & cluster
 
Python, Keras, Hello world, Installation, Binary Classification
Python, Keras, Hello world, Installation, Binary ClassificationPython, Keras, Hello world, Installation, Binary Classification
Python, Keras, Hello world, Installation, Binary Classification
 
1 m+ qps on mysql galera cluster
1 m+ qps on mysql galera cluster1 m+ qps on mysql galera cluster
1 m+ qps on mysql galera cluster
 
Schema replication using oracle golden gate 12c
Schema replication using oracle golden gate 12cSchema replication using oracle golden gate 12c
Schema replication using oracle golden gate 12c
 
Training Slides: Basics 105: Backup, Recovery and Provisioning Within Tungste...
Training Slides: Basics 105: Backup, Recovery and Provisioning Within Tungste...Training Slides: Basics 105: Backup, Recovery and Provisioning Within Tungste...
Training Slides: Basics 105: Backup, Recovery and Provisioning Within Tungste...
 
Hmc installation .
Hmc installation . Hmc installation .
Hmc installation .
 
Dev ops
Dev opsDev ops
Dev ops
 
Out of the Box Replication in Postgres 9.4(pgconfsf)
Out of the Box Replication in Postgres 9.4(pgconfsf)Out of the Box Replication in Postgres 9.4(pgconfsf)
Out of the Box Replication in Postgres 9.4(pgconfsf)
 
TOROS: Python Framework for Recommender System
TOROS: Python Framework for Recommender SystemTOROS: Python Framework for Recommender System
TOROS: Python Framework for Recommender System
 
Kernel Recipes 2015: Introduction to Kernel Power Management
Kernel Recipes 2015: Introduction to Kernel Power ManagementKernel Recipes 2015: Introduction to Kernel Power Management
Kernel Recipes 2015: Introduction to Kernel Power Management
 
Troubleshooting PostgreSQL with pgCenter
Troubleshooting PostgreSQL with pgCenterTroubleshooting PostgreSQL with pgCenter
Troubleshooting PostgreSQL with pgCenter
 
How To Protect SSH Access with Fail2Ban on RHEL 7
How To Protect SSH Access with Fail2Ban on RHEL 7How To Protect SSH Access with Fail2Ban on RHEL 7
How To Protect SSH Access with Fail2Ban on RHEL 7
 
nouka inventry manager
nouka inventry managernouka inventry manager
nouka inventry manager
 
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
 
How to Upgrade Openfire on CentOS 7
How to Upgrade Openfire on CentOS 7How to Upgrade Openfire on CentOS 7
How to Upgrade Openfire on CentOS 7
 
agri inventory - nouka data collector / yaoya data convertor
agri inventory - nouka data collector / yaoya data convertoragri inventory - nouka data collector / yaoya data convertor
agri inventory - nouka data collector / yaoya data convertor
 
PostgreSQL Replication with Bucardo
PostgreSQL Replication with BucardoPostgreSQL Replication with Bucardo
PostgreSQL Replication with Bucardo
 
Velocity 2017 Performance analysis superpowers with Linux eBPF
Velocity 2017 Performance analysis superpowers with Linux eBPFVelocity 2017 Performance analysis superpowers with Linux eBPF
Velocity 2017 Performance analysis superpowers with Linux eBPF
 
Running hadoop on ubuntu linux
Running hadoop on ubuntu linuxRunning hadoop on ubuntu linux
Running hadoop on ubuntu linux
 

Ähnlich wie The Magic of Hot Streaming Replication, Bruce Momjian

The Magic of Hot Streaming Replication (Bruce Momjian)
The Magic of Hot Streaming Replication (Bruce Momjian)The Magic of Hot Streaming Replication (Bruce Momjian)
The Magic of Hot Streaming Replication (Bruce Momjian)
Ontico
 
Built-in-Physical-and-Logical-Replication-in-Postgresql-Firat-Gulec.pptx
Built-in-Physical-and-Logical-Replication-in-Postgresql-Firat-Gulec.pptxBuilt-in-Physical-and-Logical-Replication-in-Postgresql-Firat-Gulec.pptx
Built-in-Physical-and-Logical-Replication-in-Postgresql-Firat-Gulec.pptx
nadirpervez2
 
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
 
Out of the Box Replication in Postgres 9.4(PgCon)
Out of the Box Replication in Postgres 9.4(PgCon)Out of the Box Replication in Postgres 9.4(PgCon)
Out of the Box Replication in Postgres 9.4(PgCon)
Denish Patel
 
Out of the Box Replication in Postgres 9.4(PgCon)
Out of the Box Replication in Postgres 9.4(PgCon)Out of the Box Replication in Postgres 9.4(PgCon)
Out of the Box Replication in Postgres 9.4(PgCon)
Denish Patel
 
2011 384 hackworth_ppt
2011 384 hackworth_ppt2011 384 hackworth_ppt
2011 384 hackworth_ppt
maclean liu
 
Adventures in Dataguard
Adventures in DataguardAdventures in Dataguard
Adventures in Dataguard
Jason Arneil
 

Ähnlich wie The Magic of Hot Streaming Replication, Bruce Momjian (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...
 
The Magic of Hot Streaming Replication (Bruce Momjian)
The Magic of Hot Streaming Replication (Bruce Momjian)The Magic of Hot Streaming Replication (Bruce Momjian)
The Magic of Hot Streaming Replication (Bruce Momjian)
 
Built-in-Physical-and-Logical-Replication-in-Postgresql-Firat-Gulec.pptx
Built-in-Physical-and-Logical-Replication-in-Postgresql-Firat-Gulec.pptxBuilt-in-Physical-and-Logical-Replication-in-Postgresql-Firat-Gulec.pptx
Built-in-Physical-and-Logical-Replication-in-Postgresql-Firat-Gulec.pptx
 
Built in physical and logical replication in postgresql-Firat Gulec
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 Gulec
 
Streaming replication in practice
Streaming replication in practiceStreaming replication in practice
Streaming replication in practice
 
Physical_Standby_Database_R12.2.4
Physical_Standby_Database_R12.2.4Physical_Standby_Database_R12.2.4
Physical_Standby_Database_R12.2.4
 
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)
 
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)
 
Oracle Data Guard
Oracle Data GuardOracle Data Guard
Oracle Data Guard
 
Salesforce at Stacki Atlanta Meetup February 2016
Salesforce at Stacki Atlanta Meetup February 2016Salesforce at Stacki Atlanta Meetup February 2016
Salesforce at Stacki Atlanta Meetup February 2016
 
How to Replicate PostgreSQL Database
How to Replicate PostgreSQL DatabaseHow to Replicate PostgreSQL Database
How to Replicate PostgreSQL Database
 
PostgreSQL : Introduction
PostgreSQL : IntroductionPostgreSQL : Introduction
PostgreSQL : Introduction
 
Out of the Box Replication in Postgres 9.4(PgCon)
Out of the Box Replication in Postgres 9.4(PgCon)Out of the Box Replication in Postgres 9.4(PgCon)
Out of the Box Replication in Postgres 9.4(PgCon)
 
Out of the Box Replication in Postgres 9.4(PgCon)
Out of the Box Replication in Postgres 9.4(PgCon)Out of the Box Replication in Postgres 9.4(PgCon)
Out of the Box Replication in Postgres 9.4(PgCon)
 
Out of the box replication in postgres 9.4
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.4
 
2011 384 hackworth_ppt
2011 384 hackworth_ppt2011 384 hackworth_ppt
2011 384 hackworth_ppt
 
Adventures in Dataguard
Adventures in DataguardAdventures in Dataguard
Adventures in Dataguard
 
Data Guard New Features
Data Guard New FeaturesData Guard New Features
Data Guard New Features
 
Streaming Replication Made Easy in v9.3
Streaming Replication Made Easy in v9.3Streaming Replication Made Easy in v9.3
Streaming Replication Made Easy in v9.3
 
Stacki - The1600+ Server Journey
Stacki - The1600+ Server JourneyStacki - The1600+ Server Journey
Stacki - The1600+ Server Journey
 

Mehr von Fuenteovejuna

Facebook, Robert Johnson
Facebook, Robert JohnsonFacebook, Robert Johnson
Facebook, Robert Johnson
Fuenteovejuna
 
Интеграция открытых технологий и взаимодействие со сторонними проектами в усл...
Интеграция открытых технологий и взаимодействие со сторонними проектами в усл...Интеграция открытых технологий и взаимодействие со сторонними проектами в усл...
Интеграция открытых технологий и взаимодействие со сторонними проектами в усл...
Fuenteovejuna
 
Shared Personalization Service - How To Scale to 15K RPS, Patrice Pelland
Shared Personalization Service - How To Scale to 15K RPS, Patrice PellandShared Personalization Service - How To Scale to 15K RPS, Patrice Pelland
Shared Personalization Service - How To Scale to 15K RPS, Patrice Pelland
Fuenteovejuna
 
Оптимизация одного из топовых приложений для социальной сети ВКонтакте: 1000 ...
Оптимизация одного из топовых приложений для социальной сети ВКонтакте: 1000 ...Оптимизация одного из топовых приложений для социальной сети ВКонтакте: 1000 ...
Оптимизация одного из топовых приложений для социальной сети ВКонтакте: 1000 ...
Fuenteovejuna
 
Практическое создание крупного масштабируемого web 20 c нуля, Дмитрий Бородин
Практическое создание крупного масштабируемого web 20 c нуля, Дмитрий БородинПрактическое создание крупного масштабируемого web 20 c нуля, Дмитрий Бородин
Практическое создание крупного масштабируемого web 20 c нуля, Дмитрий Бородин
Fuenteovejuna
 
Social Monitoring Tool codename Looking Glass, Patrice Pelland
Social Monitoring Tool codename Looking Glass, Patrice PellandSocial Monitoring Tool codename Looking Glass, Patrice Pelland
Social Monitoring Tool codename Looking Glass, Patrice Pelland
Fuenteovejuna
 
Профилирование памяти в приложениях на Python, Антон Грицай
Профилирование памяти в приложениях на Python, Антон ГрицайПрофилирование памяти в приложениях на Python, Антон Грицай
Профилирование памяти в приложениях на Python, Антон Грицай
Fuenteovejuna
 
Компиляция скриптов PHP. Алексей Романенко
Компиляция скриптов PHP. Алексей РоманенкоКомпиляция скриптов PHP. Алексей Романенко
Компиляция скриптов PHP. Алексей Романенко
Fuenteovejuna
 
Сервер-агрегатор на python (аля Xscript FEST), Сумин Андрей, Сабуренков Михаи...
Сервер-агрегатор на python (аля Xscript FEST), Сумин Андрей, Сабуренков Михаи...Сервер-агрегатор на python (аля Xscript FEST), Сумин Андрей, Сабуренков Михаи...
Сервер-агрегатор на python (аля Xscript FEST), Сумин Андрей, Сабуренков Михаи...
Fuenteovejuna
 
Использование 0MQ для построения low latency распределёных систем, Андрей Охл...
Использование 0MQ для построения low latency распределёных систем, Андрей Охл...Использование 0MQ для построения low latency распределёных систем, Андрей Охл...
Использование 0MQ для построения low latency распределёных систем, Андрей Охл...
Fuenteovejuna
 
Некоторые аспекты влияния сходимости протокола BGP на доступность сетевых рес...
Некоторые аспекты влияния сходимости протокола BGP на доступность сетевых рес...Некоторые аспекты влияния сходимости протокола BGP на доступность сетевых рес...
Некоторые аспекты влияния сходимости протокола BGP на доступность сетевых рес...
Fuenteovejuna
 
Тандемные DDoS-атаки. Проблематика уязвимостей в спецификации TCP IP (фундаме...
Тандемные DDoS-атаки. Проблематика уязвимостей в спецификации TCP IP (фундаме...Тандемные DDoS-атаки. Проблематика уязвимостей в спецификации TCP IP (фундаме...
Тандемные DDoS-атаки. Проблематика уязвимостей в спецификации TCP IP (фундаме...
Fuenteovejuna
 
Динамика DDoS-атак в России, Александр Лямин
Динамика DDoS-атак в России, Александр ЛяминДинамика DDoS-атак в России, Александр Лямин
Динамика DDoS-атак в России, Александр Лямин
Fuenteovejuna
 
Быстрое развёртывание шаблонов и статики в Mail.ru, Николай Кондратов
Быстрое развёртывание шаблонов и статики в Mail.ru, Николай КондратовБыстрое развёртывание шаблонов и статики в Mail.ru, Николай Кондратов
Быстрое развёртывание шаблонов и статики в Mail.ru, Николай Кондратов
Fuenteovejuna
 
Extreme Cloud Storage on FreeBSD, Андрей Пантюхин
Extreme Cloud Storage on FreeBSD, Андрей ПантюхинExtreme Cloud Storage on FreeBSD, Андрей Пантюхин
Extreme Cloud Storage on FreeBSD, Андрей Пантюхин
Fuenteovejuna
 
Мониторинг XXI-век, Алиса Смирнова, Дима Никоненко
Мониторинг XXI-век, Алиса Смирнова, Дима НиконенкоМониторинг XXI-век, Алиса Смирнова, Дима Никоненко
Мониторинг XXI-век, Алиса Смирнова, Дима Никоненко
Fuenteovejuna
 
Native Client, Евгений Эльцин
Native Client, Евгений ЭльцинNative Client, Евгений Эльцин
Native Client, Евгений Эльцин
Fuenteovejuna
 
Tarantool Silverbox, Юрий Востриков
Tarantool Silverbox, Юрий ВостриковTarantool Silverbox, Юрий Востриков
Tarantool Silverbox, Юрий Востриков
Fuenteovejuna
 
Real time indexes in Sphinx, Yaroslav Vorozhko
Real time indexes in Sphinx, Yaroslav VorozhkoReal time indexes in Sphinx, Yaroslav Vorozhko
Real time indexes in Sphinx, Yaroslav Vorozhko
Fuenteovejuna
 
Sphinx для высоко-нагруженных и масштабируемых проектов, Вячеслав Крюков
Sphinx для высоко-нагруженных и масштабируемых проектов, Вячеслав КрюковSphinx для высоко-нагруженных и масштабируемых проектов, Вячеслав Крюков
Sphinx для высоко-нагруженных и масштабируемых проектов, Вячеслав Крюков
Fuenteovejuna
 

Mehr von Fuenteovejuna (20)

Facebook, Robert Johnson
Facebook, Robert JohnsonFacebook, Robert Johnson
Facebook, Robert Johnson
 
Интеграция открытых технологий и взаимодействие со сторонними проектами в усл...
Интеграция открытых технологий и взаимодействие со сторонними проектами в усл...Интеграция открытых технологий и взаимодействие со сторонними проектами в усл...
Интеграция открытых технологий и взаимодействие со сторонними проектами в усл...
 
Shared Personalization Service - How To Scale to 15K RPS, Patrice Pelland
Shared Personalization Service - How To Scale to 15K RPS, Patrice PellandShared Personalization Service - How To Scale to 15K RPS, Patrice Pelland
Shared Personalization Service - How To Scale to 15K RPS, Patrice Pelland
 
Оптимизация одного из топовых приложений для социальной сети ВКонтакте: 1000 ...
Оптимизация одного из топовых приложений для социальной сети ВКонтакте: 1000 ...Оптимизация одного из топовых приложений для социальной сети ВКонтакте: 1000 ...
Оптимизация одного из топовых приложений для социальной сети ВКонтакте: 1000 ...
 
Практическое создание крупного масштабируемого web 20 c нуля, Дмитрий Бородин
Практическое создание крупного масштабируемого web 20 c нуля, Дмитрий БородинПрактическое создание крупного масштабируемого web 20 c нуля, Дмитрий Бородин
Практическое создание крупного масштабируемого web 20 c нуля, Дмитрий Бородин
 
Social Monitoring Tool codename Looking Glass, Patrice Pelland
Social Monitoring Tool codename Looking Glass, Patrice PellandSocial Monitoring Tool codename Looking Glass, Patrice Pelland
Social Monitoring Tool codename Looking Glass, Patrice Pelland
 
Профилирование памяти в приложениях на Python, Антон Грицай
Профилирование памяти в приложениях на Python, Антон ГрицайПрофилирование памяти в приложениях на Python, Антон Грицай
Профилирование памяти в приложениях на Python, Антон Грицай
 
Компиляция скриптов PHP. Алексей Романенко
Компиляция скриптов PHP. Алексей РоманенкоКомпиляция скриптов PHP. Алексей Романенко
Компиляция скриптов PHP. Алексей Романенко
 
Сервер-агрегатор на python (аля Xscript FEST), Сумин Андрей, Сабуренков Михаи...
Сервер-агрегатор на python (аля Xscript FEST), Сумин Андрей, Сабуренков Михаи...Сервер-агрегатор на python (аля Xscript FEST), Сумин Андрей, Сабуренков Михаи...
Сервер-агрегатор на python (аля Xscript FEST), Сумин Андрей, Сабуренков Михаи...
 
Использование 0MQ для построения low latency распределёных систем, Андрей Охл...
Использование 0MQ для построения low latency распределёных систем, Андрей Охл...Использование 0MQ для построения low latency распределёных систем, Андрей Охл...
Использование 0MQ для построения low latency распределёных систем, Андрей Охл...
 
Некоторые аспекты влияния сходимости протокола BGP на доступность сетевых рес...
Некоторые аспекты влияния сходимости протокола BGP на доступность сетевых рес...Некоторые аспекты влияния сходимости протокола BGP на доступность сетевых рес...
Некоторые аспекты влияния сходимости протокола BGP на доступность сетевых рес...
 
Тандемные DDoS-атаки. Проблематика уязвимостей в спецификации TCP IP (фундаме...
Тандемные DDoS-атаки. Проблематика уязвимостей в спецификации TCP IP (фундаме...Тандемные DDoS-атаки. Проблематика уязвимостей в спецификации TCP IP (фундаме...
Тандемные DDoS-атаки. Проблематика уязвимостей в спецификации TCP IP (фундаме...
 
Динамика DDoS-атак в России, Александр Лямин
Динамика DDoS-атак в России, Александр ЛяминДинамика DDoS-атак в России, Александр Лямин
Динамика DDoS-атак в России, Александр Лямин
 
Быстрое развёртывание шаблонов и статики в Mail.ru, Николай Кондратов
Быстрое развёртывание шаблонов и статики в Mail.ru, Николай КондратовБыстрое развёртывание шаблонов и статики в Mail.ru, Николай Кондратов
Быстрое развёртывание шаблонов и статики в Mail.ru, Николай Кондратов
 
Extreme Cloud Storage on FreeBSD, Андрей Пантюхин
Extreme Cloud Storage on FreeBSD, Андрей ПантюхинExtreme Cloud Storage on FreeBSD, Андрей Пантюхин
Extreme Cloud Storage on FreeBSD, Андрей Пантюхин
 
Мониторинг XXI-век, Алиса Смирнова, Дима Никоненко
Мониторинг XXI-век, Алиса Смирнова, Дима НиконенкоМониторинг XXI-век, Алиса Смирнова, Дима Никоненко
Мониторинг XXI-век, Алиса Смирнова, Дима Никоненко
 
Native Client, Евгений Эльцин
Native Client, Евгений ЭльцинNative Client, Евгений Эльцин
Native Client, Евгений Эльцин
 
Tarantool Silverbox, Юрий Востриков
Tarantool Silverbox, Юрий ВостриковTarantool Silverbox, Юрий Востриков
Tarantool Silverbox, Юрий Востриков
 
Real time indexes in Sphinx, Yaroslav Vorozhko
Real time indexes in Sphinx, Yaroslav VorozhkoReal time indexes in Sphinx, Yaroslav Vorozhko
Real time indexes in Sphinx, Yaroslav Vorozhko
 
Sphinx для высоко-нагруженных и масштабируемых проектов, Вячеслав Крюков
Sphinx для высоко-нагруженных и масштабируемых проектов, Вячеслав КрюковSphinx для высоко-нагруженных и масштабируемых проектов, Вячеслав Крюков
Sphinx для высоко-нагруженных и масштабируемых проектов, Вячеслав Крюков
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

The Magic of Hot Streaming Replication, Bruce Momjian

  • 1. The Magic of Hot Streaming Replication BRUCE MOMJIAN, ENTERPRISEDB October, 2010 Abstract POSTGRESQL 9.0 offers new facilities for maintaining a current standby server and for issuing read-only queries on the standby server. This tutorial covers these new facilities. Creative Commons Attribution License http://momjian.us/presentations
  • 2. Introduction   How does WAL combined with a disk image enable standby servers? (review)   How do you configure continuous archiving?   How do you configure a streaming, read-only server?   Multi-Server complexities   Primary/Standby synchronization complexities The Magic of Hot Streaming Replication 2
  • 3. Write-Ahead Logging (xlog) fsync fsync Backend Postgres Backend Postgres Backend Postgres PostgreSQL Shared Buffer Cache Write−Ahead Log Kernel Disk Buffer Cache Disk Blocks The Magic of Hot Streaming Replication 3
  • 4. Pre-9.0 Continuous Archiving / Point-In-Time Recovery (PITR)0200 1100 0900 1300 W AL W ALWAL ContinuousFile System− Level Backup Archive (WAL) The Magic of Hot Streaming Replication 4
  • 5. PITR Backup Procedures 1. archive_command = ’cp -i %p /mnt/server/pgsql/%f < /dev/null’ 2. SELECT pg_start_backup(’label’); 3. Perform file system-level backup (can be inconsistent) 4. SELECT pg_stop_backup(); The Magic of Hot Streaming Replication 5
  • 6. PITR Recovery W AL W AL 1700 1730 1740 1755 WAL ContinuousFile System− Level Backup Archive (WAL) The Magic of Hot Streaming Replication 6
  • 7. PITR Recovery Procedures 1. Stop postmaster 2. Restore file system-level backup 3. Make adjustments as outlined in the documentation 4. Create recovery.conf 5. restore_command = ’cp /mnt/server/pgsql/%f %p’ 6. Start the postmaster The Magic of Hot Streaming Replication 7
  • 8. Disadvantages   Only complete 16MB files can be shipped   archive_timeout can be used to force more frequent shipping (this increases archive storage requirements)   No queries on the standby The Magic of Hot Streaming Replication 8
  • 9. 9.0 Streaming Replication / Hot Standby   Changes are streamed to the standby, greatly reducing log shipping delays   Standby can accept read-only queries The Magic of Hot Streaming Replication 9
  • 10. Streaming Replication Differs from PITR   File system backup is restored immediately on the standby server   WAL files are streamed to the slave   WAL files can also be archived if point-in-time recovery (PITR) is desired The Magic of Hot Streaming Replication 10
  • 11. How Does Streaming Replication Work? 0200 1100 0900 1300 W AL W ALWAL File System− Level Backup Server Standby The Magic of Hot Streaming Replication 11
  • 12. Live Streaming Replication archive command archive command Primary Standby Network /pg_xlog/pg_xlog Archive Directory WAL The Magic of Hot Streaming Replication 12
  • 13. Enable Streaming to the Standby Enable the proper WAL contents: wal_level = hot_standby Retain WAL files needed by the standby: wal_keep_segments = 50 Enable the ability to stream WAL to the standby: max_wal_senders = 1 The Magic of Hot Streaming Replication 13
  • 14. Enable Standby Connection Permissions Add permission for replication to pg_hba.conf: host replication all 127.0.0.1/32 trust Start the primary server: pg_ctl -l /u/pg/data/server.log start The Magic of Hot Streaming Replication 14
  • 15. Perform a WAL-Supported File System Backup Start psql and issue: SELECT pg_start_backup(’testing’); Copy the database /u/pg/data to a new directory, /u/pg/data2: cp -p -R /u/pg/data /u/pg/data2 Dash-p preserves ownership. The copy is inconsistent, but that is okay (WAL replay will correct that). Signal the backup is complete from psql: SELECT pg_stop_backup(); The Magic of Hot Streaming Replication 15
  • 16. Configure the Standby Remove /data2/postmaster.pid so the standby server does not see the primary server’s pid as its own: rm /u/pg/data2/postmaster.pid (This is only necessary because we are testing with the primary and slave on the same computer.) Edit postgresql.conf on the standby and change the port to 5433 port = 5433 Enable hot standby in postgresql.conf: hot_standby = on The Magic of Hot Streaming Replication 16
  • 17. Configure the Standby For Streaming Replication Create recovery.conf: cp /u/pg/share/recovery.conf.sample /u/pg/data2/recovery.conf Enable streaming in recovery.conf: standby_mode = ’on’ primary_conninfo = ’host=localhost port=5432’ Start the standby server: PGDATA=/u/pg/data2 pg_ctl -l /u/pg/data2/server.log start The Magic of Hot Streaming Replication 17
  • 18. Test Streaming Replication and Hot Standby $ psql -p 5432 -c ’CREATE TABLE streamtest(x int)’ postgres $ psql -p 5433 -c ’d’ postgres List of relations Schema | Name | Type | Owner --------+------------+-------+---------- public | streamtest | table | postgres (1 row) $ psql -p 5432 -c ’INSERT INTO streamtest VALUES (1)’ postgres INSERT 0 1 $ psql -p 5433 -c ’INSERT INTO streamtest VALUES (1)’ postgres ERROR: cannot execute INSERT in a read-only transaction The Magic of Hot Streaming Replication 18
  • 19. Additional Complexities   Multi-server permissions   Stream from /pg_xlog and the continuous archive directory if archive_mode is enabled on the primary The Magic of Hot Streaming Replication 19
  • 20. Primary/Standby Synchronization Issues The primary server can take actions that cause long-running queries on the standby to be cancelled. Specifically, the cleanup of unnecessary rows that are still of interest to long-running queries on the standby can cause long-running queries to be cancelled on the standby. Standby query cancellation can be minimized in two ways: 1. Delay cleanup of old records on the primary with vacuum_defer_cleanup_age in postgresql.conf. 2. Delay application of WAL logs on the standby with max_standby_delay in postgresql.conf. The default is 30 seconds; -1 causes application to delay indefinitely to prevent query cancellation. This also delays changes from appearing on the standby and can lengthen the time required for failover to the slave. The Magic of Hot Streaming Replication 20
  • 21. Conclusion http://momjian.us/presentations Manet, Bar at Folies Bergère The Magic of Hot Streaming Replication 21