Share E-Book

PostgreSQL Replication (Hans-Jurgen Schonig) (z-library.sk, 1lib.sk, z-lib.sk)

Author

Rating 3.5 AI initial rating

Log in to rate

SQL
Language English

Leverage the power of PostgreSQL replication to make your databases more robust, secure, scalable, and fast About This Book Efficiently replicate PostgreSQL using high-end techniques to protect your data and run your server without interruptions Improve reliability, fault-tolerance, and accessibility by maintaining consistency between redundant resources Get grips with the latest version of PostgreSQL with this example-based guide Who This Book Is For This book is ideal for PostgreSQL administrators who want to set up and understand replication. By the end of the book, you will be able to make your databases more robust and secure by getting to grips with PostgreSQL replication. What You Will Learn Use Point-in-time Recovery to perform data recovery as well as replication Set up synchronous as well as asynchronous streaming replication Get familiarized with the transaction log, the core component of most replication setups and its purpose Improve speed and reliability with an understanding of pgpool and PgBouncer Increase your data security and geographically distribute data Make your systems more available and secure with Linux High Availability Scale out with PL/Proxy and Postgres-XC Detect, investigate, and solve replication-related problems In Detail PostgreSQL offers a comprehensive set of replication related features. Unleashing the power of PostgreSQL provides you with countless opportunities and a competitive advantage over other database systems. This book will guide you through the most important concepts of PostgreSQL replication. It contains all the information you need to design and operate replicated setups. Beginning by giving you an understanding of replication concepts, the PostgreSQL transaction log, and Point-in-time Recovery, we gradually move on to setting up asynchronous and synchronous replication. Next up, you will learn to monitor a PostgreSQL cluster setup, deal with monitoring tools, and then move on to understanding Linux High Availab

Format PDF
Size 2.9 MB
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
PostgreSQL Replication Second Edition Leverage the power of PostgreSQL replication to make your databases more robust, secure, scalable, and fast Hans-Jürgen Schönig BIRMINGHAM - MUMBAI
Page 3
PostgreSQL Replication Second Edition Copyright © 2015 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: August 2013 Second edition: July 2015 Production reference: 1240715 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78355-060-9 www.packtpub.com
Page 4
Credits Author Hans-Jürgen Schönig Reviewers Swathi Kurunji Jeff Lawson Maurício Linhares Shaun M. Thomas Tomas Vondra Commissioning Editor Kartikey Pandey Acquisition Editor Larissa Pinto Content Development Editor Nikhil Potdukhe Technical Editor Manali Gonsalves Copy Editors Dipti Mankame Vikrant Phadke Project Coordinator Vijay Kushlani Proofreader Safis Editing Indexer Priya Sane Graphics Sheetal Aute Production Coordinator Komal Ramchandani Cover Work Komal Ramchandani
Page 5
About the Author Hans-Jürgen Schönig has 15 years of experience with PostgreSQL. He is the CEO of a PostgreSQL consulting and support company called Cybertec Schönig & Schönig GmbH (www.postgresql-support.de). It has successfully served countless customers around the globe. Before founding Cybertec Schönig & Schönig GmbH in 2000, he worked as a database developer at a private research company focusing on the Austrian labor market, where he primarily focused on data mining and forecast models. He has also written several books about PostgreSQL. This book is dedicated to all the members of the Cybertec family, who have supported me over the years and have proven to be true professionals. Without my fellow technicians here at Cybertec, this book would not have existed. I especially want to thank Ants Aasma for his technical input and Florian Ziegler for helping out with the proofreading and graphical stuff. Special thanks also go to my girl, Sonja Städtner, who has given me all the personal support. Somehow, she managed to make me go to sleep when I was up late at night working on the initial drafts.
Page 6
About the Reviewers Swathi Kurunji is a software engineer at Actian Corporation. She recently completed her PhD in computer science from the University of Massachusetts Lowell (UMass Lowell), USA. She has a keen interest in database systems. Her PhD research involved query optimization, big data analysis, data warehousing, and cloud computing. Swathi has shown excellence in her field of study through research publications at international conferences and in journals. She has received awards and scholarships from UMass Lowell for research and academics. Swathi also has a master's of science degree in computer science from UMass Lowell and a bachelor's of engineering degree in information science from KVGCE in India. During her studies at UMass Lowell, she worked as a teaching assistant, helping professors in teaching classes and labs, designing projects, and grading exams. She has worked as a software development intern with IT companies such as EMC and SAP. At EMC, she gained experience on Apache Cassandra data modeling and performance analysis. At SAP, she gained experience on the infrastructure/cluster management components of the Sybase IQ product. She has also worked with Wipro Technologies in India as a project engineer, managing application servers. She has extensive experience with database systems such as Apache Cassandra, Sybase IQ, Oracle, MySQL, and MS Access. Her interests include software design and development, big data analysis, optimization of databases, and cloud computing. Her LinkedIn profile is http://www.linkedin.com/pub/swathi- kurunji/49/578/30a/. Swathi has previously reviewed two books, Cassandra Data Modeling and Analysis and Mastering Apache Cassandra, both by Packt Publishing. I would like to thank my husband and my family for all their support.
Page 7
Jeff Lawson has been a user and fan of PostgreSQL since he noticed it in 2001. Over the years, he has also developed and deployed applications for IBM DB2, Oracle, MySQL, Microsoft SQL Server, Sybase, and others, but he has always preferred PostgreSQL because of its balance of features and openness. Much of his experience has spanned development for Internet-facing websites and projects that required highly scalable databases with high availability or provisions for disaster recovery. Jeff currently works as the director of software development at FlightAware, which is an airplane tracking website that uses PostgreSQL and other pieces of open source software to store and analyze the positions of thousands of flights that fly worldwide every day. He has extensive experience in software architecture, data security, and networking protocol design because of his roles as a software engineer at Univa/ United Devices, Microsoft, NASA's Jet Propulsion Laboratory, and WolfeTech. He was a founder of distributed.net, which pioneered distributed computing in the 1990s, and continues to serve as the chief of operations and a member of the board. He earned a BSc in computer science from Harvey Mudd College. Jeff is fond of cattle, holds an FAA private pilot certificate, and owns an airplane in Houston, Texas. Maurício Linhares is a technical leader of the parsing and machine learning team at The Neat Company. At Neat, he helps his team scale their solutions on the cloud and deliver fast results to customers. He is the creator and maintainer of async, a Scala-based PostgreSQL database driver (https://github.com/mauricio/ postgresql-async), and has been a PostgreSQL user and proponent for many years. Shaun M. Thomas has been working with PostgreSQL since late 2000. He has presented at Postgres open conferences in 2011, 2012, and 2014 on topics such as handling extreme throughput, high availability, server redundancy, failover techniques, and system monitoring. With the recent publication of Packt Publishing's PostgreSQL 9 High Availability Cookbook, he hopes to make life easier for DBAs using PostgreSQL in enterprise environments. Currently, Shaun serves as the database architect at Peak6, an options trading firm with a PostgreSQL constellation of over 100 instances, one of which is over 15 TB in size. He wants to prove that PostgreSQL is more than ready for major installations.
Page 8
Tomas Vondra has been working with PostgreSQL since 2003, and although he had worked with various other databases—both open-source and proprietary—he instantly fell in love with PostgreSQL and the community around it. He is currently working as an engineer at 2ndQuadrant, one of the companies that provide support, training, and other services related to PostgreSQL. Previously, he worked as a PostgreSQL specialist for GoodData, a company that operates a BI cloud platform built on PostgreSQL. He has extensive experience with performance troubleshooting, tuning, and benchmarking. In his free time, he usually writes PostgreSQL extensions or patches, or he hacks something related to PostgreSQL.
Page 9
www.PacktPub.com Support files, eBooks, discount offers, and more For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub. com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books. Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print, and bookmark content • On demand and accessible via a web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Page 10
[ i ] Table of Contents Preface xi Chapter 1: Understanding the Concepts of Replication 1 The CAP theorem and physical limitations of replication 2 Understanding the CAP theorem 2 Understanding the limits of physics 4 Different types of replication 5 Synchronous versus asynchronous replication 6 Considering performance issues 7 Understanding replication and data loss 7 Single-master versus multimaster replication 8 Logical versus physical replication 9 When to use physical replication 10 When to use logical replication 10 Using sharding and data distribution 11 Understanding the purpose of sharding 11 Designing a sharded system 11 Querying different fields 12 Pros and cons of sharding 13 Choosing between sharding and redundancy 14 Increasing and decreasing the size of a cluster 15 Combining sharding and replication 17 Various sharding solutions 18 PostgreSQL-based sharding 19 Summary 19
Page 11
Table of Contents [ ii ] Chapter 2: Understanding the PostgreSQL Transaction Log 21 How PostgreSQL writes data 21 The PostgreSQL disk layout 22 Looking into the data directory 22 PG_VERSION – the PostgreSQL version number 23 base – the actual data directory 23 global – the global data 25 pg_clog – the commit log 25 pg_dynshmem – shared memory 26 pg_hba.conf – host-based network configuration 26 pg_ident.conf – ident authentication 26 pg_logical – logical decoding 26 pg_multixact – multitransaction status data 26 pg_notify – LISTEN/NOTIFY data 27 pg_replslot – replication slots 27 pg_serial – information about committed serializable transactions 27 pg_snapshot – exported snapshots 27 pg_stat – permanent statistics 27 pg_stat_tmp – temporary statistics data 27 pg_subtrans – subtransaction data 27 pg_tblspc – symbolic links to tablespaces 28 pg_twophase – information about prepared statements 28 pg_xlog – the PostgreSQL transaction log (WAL) 28 postgresql.conf – the central PostgreSQL configuration file 29 Writing one row of data 30 A simple INSERT statement 30 Read consistency 33 The purpose of the shared buffer 34 Mixed reads and writes 35 The format of the XLOG 36 The XLOG and replication 38 Understanding consistency and data loss 38 All the way to the disk 39 From memory to memory 39 From the memory to the disk 40 A word about batteries 42 Beyond the fsync function 42 PostgreSQL consistency levels 43 Tuning checkpoints and the XLOG 44 Understanding the checkpoints 45 Configuring the checkpoints 45 Segments and timeouts 45 To write or not to write? 46 Tweaking WAL buffers 49
Page 12
Table of Contents [ iii ] Experiencing the XLOG in action 49 Understanding the XLOG records 50 Making the XLOG deterministic 50 Making the XLOG reliable 50 LSNs and shared buffer interaction 51 Debugging the XLOG and putting it all together 52 Making use of replication slots 53 Physical replication slots 54 Logical replication slots 56 Configuring replication identities 59 Summary 61 Chapter 3: Understanding Point-in-time Recovery 63 Understanding the purpose of PITR 64 Moving to the bigger picture 64 Archiving the transaction log 66 Taking base backups 68 Using pg_basebackup 69 Modifying pg_hba.conf 69 Signaling the master server 70 pg_basebackup – basic features 70 Making use of traditional methods to create base backups 73 Tablespace issues 74 Keeping an eye on the network bandwidth 74 Replaying the transaction log 75 Performing a basic recovery 75 More sophisticated positioning in the XLOG 78 Cleaning up the XLOG on the way 80 Switching the XLOG files 81 Summary 82 Chapter 4: Setting Up Asynchronous Replication 83 Setting up streaming replication 83 Tweaking the config files on the master 84 Handling pg_basebackup and recovery.conf 85 Making the slave readable 86 The underlying protocol 87 Configuring a cascaded replication 88 Turning slaves into masters 90 Mixing streaming-based and file-based recovery 91 The master configuration 92 The slave configuration 92
Page 13
Table of Contents [ iv ] Error scenarios 93 Network connection between the master and slave is dead 93 Rebooting the slave 94 Rebooting the master 94 Corrupted XLOG in the archive 94 Making streaming-only replication more robust 95 Using wal_keep_segments 95 Utilizing replication slots 96 Efficient cleanup and the end of recovery 97 Gaining control over the restart points 97 Tweaking the end of your recovery 98 Conflict management 98 Dealing with timelines 101 Delayed replicas 102 Handling crashes 103 Summary 103 Chapter 5: Setting Up Synchronous Replication 105 Synchronous replication setup 105 Understanding the downside to synchronous replication 106 Understanding the application_name parameter 106 Making synchronous replication work 107 Checking the replication 109 Understanding performance issues 110 Setting synchronous_commit to on 111 Setting synchronous_commit to remote_write 111 Setting synchronous_commit to off 111 Setting synchronous_commit to local 112 Changing durability settings on the fly 112 Understanding the practical implications and performance 113 Redundancy and stopping replication 115 Summary 115 Chapter 6: Monitoring Your Setup 117 Checking your archive 117 Checking archive_command 118 Monitoring the transaction log archive 118 Checking pg_stat_replication 119 Relevant fields in pg_stat_replication 120 Checking for operating system processes 121 Checking for replication slots 122
Page 14
Table of Contents [ v ] Dealing with monitoring tools 123 Installing check_postgres 124 Deciding on a monitoring strategy 124 Summary 125 Chapter 7: Understanding Linux High Availability 127 Understanding the purpose of High Availability 127 Measuring availability 128 Durability and availability 129 Detecting failures 130 The split-brain syndrome 131 Understanding Linux-HA 132 Corosync 132 Pacemaker 132 Resource agents / fence agents 133 PCS 133 The PostgreSQL resource agent 133 Setting up a simple HA cluster 135 Preparing the servers 135 Installing the necessary software 136 Configuring the clustering software 136 Preparing for the PostgreSQL installation 137 Syncing the standby 139 Configuring the cluster 139 Configuring cluster resources 140 Configuring the constraints 143 Setting up fencing 144 Verifying the setup 145 Common maintenance tasks 147 Performing maintenance on a single node 147 Forcing a failover 148 Recovering from failed PostgreSQL starts 148 Performing cluster-wide maintenance 148 Resynchronizing after master failure 149 Summary 149 Chapter 8: Working with PgBouncer 151 Understanding the fundamental PgBouncer concepts 152 Installing PgBouncer 152 Configuring your first PgBouncer setup 153
Page 15
Table of Contents [ vi ] Writing a simple config file and starting PgBouncer up 153 Dispatching requests 154 More basic settings 155 Handling pool sizes 156 max_client_conn 156 default_pool_size 156 min_pool_size 156 reserve_pool_size 156 pool_size 156 Authentication 157 Connecting to PgBouncer 157 Java issues 158 Pool modes 158 Cleanup issues 159 Improving performance 160 A simple benchmark 161 Maintaining PgBouncer 162 Configuring the admin interface 163 Using the management database 163 Extracting runtime information 164 Suspending and resuming operations 167 Summary 168 Chapter 9: Working with pgpool 169 Installing pgpool 169 Installing additional modules 170 Understanding the features of pgpool 171 Understanding the pgpool architecture 172 Setting up replication and load balancing 173 Password authentication 176 Firing up pgpool and testing the setup 176 Attaching hosts 177 Checking the replication 179 Running pgpool with streaming replication 180 Optimizing the pgpool configuration for master/slave mode 181 Dealing with failovers and high availability 182 Using PostgreSQL streaming and Linux HA 182 pgpool mechanisms for high availability and failover 183 Summary 184
Page 16
Table of Contents [ vii ] Chapter 10: Configuring Slony 185 Installing Slony 185 Understanding how Slony works 186 Dealing with logical replication 187 The slon daemon 188 Replicating your first database 189 Deploying DDLs 194 Adding tables to replication and managing problems 196 Performing failovers 200 Planned failovers 200 Unplanned failovers 202 Summary 203 Chapter 11: Using SkyTools 205 Installing SkyTools 205 Dissecting SkyTools 206 Managing pgq queues 206 Running pgq 207 Creating queues and adding data 208 Adding consumers 210 Configuring the ticker 210 Consuming messages 212 Dropping queues 215 Using pgq for large projects 216 Using Londiste to replicate data 216 Replicating our first table 217 A word about walmgr 221 Summary 222 Chapter 12: Working with Postgres-XC 223 Understanding the Postgres-XC architecture 224 Data nodes 224 GTM 225 Coordinators 225 GTM proxy 225 Installing Postgres-XC 225 Configuring a simple cluster 226 Creating the GTM 226 Optimizing for performance 230 Dispatching the tables 231
Page 17
Table of Contents [ viii ] Optimizing joins 232 Optimizing for warehousing 232 Creating a GTM proxy 233 Creating tables and issuing queries 234 Adding nodes 235 Rebalancing data 236 Handling failovers and dropping nodes 236 Handling node failovers 236 Replacing the nodes 237 Running a GTM standby 238 Summary 239 Chapter 13: Scaling with PL/Proxy 241 Understanding the basic concepts 241 Dealing with the bigger picture 242 Partitioning the data 243 Setting up PL/Proxy 244 A basic example 245 Partitioned reads and writes 247 Extending and handling clusters in a clever way 250 Adding and moving partitions 250 Increasing the availability 251 Managing foreign keys 252 Upgrading the PL/Proxy nodes 253 Summary 254 Chapter 14: Scaling with BDR 255 Understanding BDR replication concepts 255 Understanding eventual consistency 256 Handling conflicts 256 Distributing sequences 257 Handling DDLs 257 Use cases for BDR 258 Good use cases for BDR 258 Bad use cases for BDR 258 Logical decoding does the trick 259 Installing BDR 259 Installing binary packages 259 Setting up a simple cluster 260 Arranging storage 260 Creating database instances 261
Page 18
Table of Contents [ ix ] Loading modules and firing up the cluster 262 Checking your setup 264 Handling conflicts 266 Understanding sets 268 Unidirectional replication 268 Handling data tables 269 Controlling replication 269 Summary 270 Chapter 15: Working with Walbouncer 271 The concepts of walbouncer 271 Filtering XLOG 273 Installing walbouncer 273 Configuring walbouncer 274 Creating a base backup 275 Firing up walbouncer 277 Using additional configuration options 280 Adjusting filtering rules 281 Removing and filtering objects 281 Adding objects to slaves 283 Summary 283 Index 285
Page 19
(This page has no text content)
Page 20
[ xi ] Preface Since the first edition of PostgreSQL Replication many new technologies have emerged or improved. In the PostgreSQL community, countless people around the globe have been working on important techniques and technologies to make PostgreSQL even more useful and more powerful. To make sure that readers can enjoy all those new features and powerful tools, I have decided to write a second, improved edition of PostgreSQL Replication. Due to the success of the first edition, the hope is to make this one even more useful to administrators and developers alike around the globe. All the important new developments have been covered and most chapters have been reworked to make them easier to understand, more complete and absolutely up to date. I hope that all of you can enjoy this book and benefit from it. What this book covers This book will guide you through a variety of topics related to PostgreSQL replication. We will present all the important facts in 15 practical and easy-to-read chapters: Chapter 1, Understanding the Concepts of Replication, guides you through fundamental replication concepts such as synchronous, as well as asynchronous, replication. You will learn about the physical limitations of replication, which options you have and what kind of distinctions there are. Chapter 2, Understanding the PostgreSQL Transaction Log, introduces you to the PostgreSQL internal transaction log machinery and presents concepts essential to many replication techniques.
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List