27.1. Архитектура #

Благодаря встроенным возможностям отказоустойчивости Postgres Pro позволяет создать кластер с одним узлом-лидером и несколькими узлами-последователями. Лидер является ведущим сервером BiHA-кластера, а последователи — репликами лидера.

Утилита bihactl позволяет инициализировать кластер и создавать узел-лидер, добавлять узлы-последователи, преобразовывать существующий узел в узел-лидер или узел-последователь в BiHA-кластере, а также проверять статус узлов кластера. Лидер доступен для чтения и записи, в то время как последователи доступны только для чтения и реплицируют данные с лидера в синхронном или асинхронном режиме.

Физическая потоковая репликация, реализованная в BiHA , обеспечивает отказоустойчивость, защищая от отказов серверов и системы хранения данных. При физической репликации файлы WAL узла-лидера синхронно или асинхронно отправляются на узел-последователь и применяются на нём. При синхронной репликации для каждой фиксации транзакции пользователь ожидает подтверждения от узла-последователя. Узел-последователь BiHA-кластера может использоваться для выполнения следующих задач:

  • Выполнение читающих транзакций в базе данных.

  • Подготовка отчётов.

  • Создание таблиц в оперативной памяти для пишущих транзакций.

  • Подготовка резервной копии узла-последователя.

  • Восстановление повреждённых блоков данных на узле-лидере путём получения этих блоков с узла-последователя.

  • Проверка повреждённых записей в файлах WAL.

Физическая потоковая репликация, реализованная в BiHA, обеспечивает защиту от следующих видов отказов:

  • Отказ узла-лидера. В этом случае статус узла-последователя повышается, и он становится новым лидером кластера. Повышение выполняется либо вручную с помощью функции biha.set_leader, либо автоматически с помощью выборов.

  • Отказ узла-последователя. Если последователь настроен как асинхронный, отказ никак не отразится на лидере. Если для последователя используется синхронная репликация, отказ приведёт к остановке транзакции на лидере, так как он перестанет получать подтверждение транзакций от последователя и транзакция не сможет завершиться. Подробное описание того, как настроить синхронную репликацию в BiHA-кластере, находится в Настройка репликации.

  • Сбой соединения между узлом-лидером и узлом-последователем. В этом случае лидер не может отправить, а последователь не может получить данные. Обратите внимание, что если пользователи подключены к лидеру, разрешать пишущие транзакции на последователе нельзя. Любые изменения, сделанные на последователях, нельзя будет восстановить на лидере. Чтобы избежать потери изменений, настраивайте сеть с резервными каналами. Лучше всего настроить свой канал передачи данных для каждого последователя, чтобы предупредить проблемы, связанные с единой точкой отказа.

В аварийной ситуации, например отказе операционной системы или оборудования, можно переустановить Postgres Pro и удалить расширение biha из shared_preload_libraries, чтобы вернуться к работе в максимально короткие сроки.

27.1.1. Конфигурация Postgres Pro #

Для корректной работы BiHA устанавливает некоторые параметры конфигурации Postgres Pro и создаёт ряд вспомогательных объектов:

  • Утилита bihactl добавляет biha в переменную shared_preload_libraries в файле postgresql.conf и, если применимо, в файле postgresql.auto.conf:

    shared_preload_libraries = 'biha'

    Этот параметр необходим для работы BiHA-кластера. Если в shared_preload_libraries уже имеются другие библиотеки, biha будет добавлена в конец списка.

  • Утилита bihactl создаёт следующие файлы:

  • Создаётся база данных biha_db, расширение biha и ряд ролей, специфичных для BiHA. За дополнительной информацией обратитесь к Роли.

  • Создаются слоты репликации с именами формата biha_node_id. Слоты управляются автоматически, изменять или удалять их вручную не нужно.

  • В файле postgresql.biha.conf утилита bihactl устанавливает следующие параметры конфигурации Postgres Pro:

    • hot_standbyon (значение по умолчанию). Этот параметр не рекомендуется изменять.

    • wal_levelreplica (значение по умолчанию). Если уже было задано значение logical, BiHA будет использовать имеющееся значение. Этот параметр не рекомендуется изменять.

    • max_wal_senders устанавливается с учётом числа процессов-передатчиков WAL, необходимых для корректной работы BiHA, которое зависит от кворума, заданного в параметре biha.nquorum. Если значение nquorum равно 3 или меньше, значение max_wal_senders будет равно 10. В иных случаях значение рассчитывается по следующей формуле: кворум_BiHA * 2 + 3. Имейте это в виду при изменении значения параметра max_wal_senders. За подробной информацией об уменьшении значения max_wal_senders и некоторых других параметров конфигурации Postgres Pro обратитесь к Подразделу 27.1.1.1.

    • max_replication_slots — значение равно max_wal_senders + 1. Минимальное значение — 11. Этот параметр не рекомендуется изменять. Учитывайте эту информацию при изменении значения параметра max_replication_slots.

    • max_slot_wal_keep_size5GB. Если значение уже было задано, BiHA будет использовать имеющееся значение. При необходимости значение можно изменить.

      В отличие от кластера стандартной конструкции ведущий-ведомый, BiHA-кластер хранит файлы WAL на всех узлах, чтобы отстающий узел мог нагнать остальные узлы. Для этого каждый узел использует слоты репликации, определяет самый отстающий узел и сохраняет столько файлов WAL, сколько может потребоваться для отстающего узла.

      При настройке BiHA-кластера убедитесь, что вы выбрали оптимальное значение для этого параметра во избежание следующих проблем:

      • Если количество необходимых файлов WAL превышает значение max_slot_wal_keep_size, старые файлы WAL будут удалены. В результате отстающий узел не получит необходимые данные, изменит своё состояние на NODE_ERROR и остановит репликацию данных.

      • Если значение параметра max_slot_wal_keep_size равно -1 (что означает, что файлы WAL никогда не удаляются) или превышает доступное дисковое пространство, это может привести к переполнению дискового хранилища.

      • Если значение параметра max_slot_wal_keep_size слишком мало, заданного в нём пространства может оказаться недостаточно для хранения файлов WAL, необходимых, чтобы отстающий узел нагнал остальные узлы и продолжил работу.

    • wal_keep_size1GB. Если значение уже было задано, BiHA будет использовать имеющееся значение. Параметр конфигурации wal_keep_size помогает сохранять файлы WAL для возможного запуска pg_rewind. Можно изменять его значение в зависимости от нагрузки. Чем больше файлов WAL генерируется, тем выше должно быть значение wal_keep_size.

    • application_name задан в формате biha_node_идентификатор. Этот параметр не рекомендуется изменять.

    • listen_addresses*. Этот параметр не рекомендуется изменять.

    • port — устанавливается порт Postgres Pro по умолчанию. Если порт по умолчанию был изменён, BiHA будет использовать имеющееся значение. Этот параметр не рекомендуется изменять.

    • primary_conninfo, primary_slot_name, synchronous_standby_names изменяются и управляются только через BiHA.

      Когда расширение biha загружено и настроено, эти параметры нельзя изменить с помощью ALTER SYSTEM.

      Эти параметры хранятся в файле pg_biha/biha.conf, а также в разделяемой памяти процесса biha. Когда эти параметры изменяются, biha отправляет сигнал SIGHUP, чтобы проинформировать другие процессы об изменениях. Если в это время изменить какие-либо другие параметры и не перечитать конфигурацию, изменённые параметры могут быть перечитаны неожиданно.

      Postgres Pro ведёт себя вышеописанным образом, только когда расширение biha загружено и настроено, то есть когда библиотека указана в переменной shared_preload_libraries и установлены необходимые параметры biha.*. В других случаях Postgres Pro работает, как обычно.

  • Во время работы BiHA создаёт следующие служебные файлы в каталоге данных:

    • standby.signal — используется для запуска узлов в режиме резервного сервера. Файл необходим для того, чтобы сделать расширение biha доступным только для чтения при запуске Postgres Pro. Файл удаляется с лидера, когда лидер переходит в состояние LEADER_RW.

    • biha.state и biha.conf — файлы в каталоге pg_biha, необходимые для сохранения внутреннего состояния и конфигурации расширения biha.

27.1.1.1. Уменьшение значений параметров Postgres Pro #

В BiHA-кластере успешно уменьшить значения некоторых параметров конфигурации Postgres Pro возможно только с помощью приведённой ниже инструкции.

Используйте эту инструкцию для уменьшения значений следующих параметров:

Предупреждение

Изменяйте эти параметры конфигурации с осторожностью и убедитесь, что они имеют одинаковые значения на всех узлах BiHA-кластера. В противном случае изменение лидера может привести к непредвиденному поведению кластера.

Уменьшить значения вышеупомянутых параметров конфигурации кластера можно следующим образом:

  1. На лидере уменьшите значение необходимого параметра конфигурации.

  2. (Необязательно) Чтобы избежать выборов, увеличьте значение параметра biha.nquorum до общего числа узлов в кластере с помощью функции biha.set_nquorum.

  3. Остановите и запустите узел-лидер с помощью pg_ctl.

    Во время запуска лидер проверяет, что другие узлы работоспособны и продолжают считать его лидером. Если все узлы работают корректно, лидер применяет изменённые значения и успешно запускается. В противном случае лидер завершает работу и выводит в журнал соответствующее сообщение.

  4. Убедитесь, что все узлы получили информацию об изменении параметра конфигурации на лидере.

    Для этого можно использовать утилиту pg_controldata или выдержать паузу после перезапуска лидера, чтобы у других узлов было достаточно времени для получения обновлений.

  5. На других узлах уменьшите значение параметра конфигурации таким же образом, как и на лидере.

  6. Остановите и запустите узлы с помощью pg_ctl.

27.1.2. Варианты конфигурации кластера #

Существует несколько вариантов конфигурации кластера.

  • Три и более узлов, один из которых является лидером, а остальные — последователями.

    Ниже представлены возможные сценарии при отказе лидера или сбое сетевого подключения:

    • При отказе текущего лидера новый лидер избирается автоматически. Чтобы стать лидером, последователь должен получить максимальное количество голосов. Количество голосов должно быть больше или равно значению, заданному в параметре biha.nquorum.

    • При сбоях сетевого соединения внутри кластера BiHA кластер может разделиться на несколько групп узлов. В этом случае новый лидер избирается во всех группах, в которых количество узлов больше или равно значению biha.nquorum. После восстановления соединения лидер кластера выбирается между старым и новоизбранным лидером в зависимости от значения term. Узел с наибольшим значением term становится новым лидером. Рекомендуется установить значение biha.minnodes равным значению biha.nquorum.

  • Кластер из двух узлов, состоящий из лидера и последователя.

    Примечание

    Не рекомендуется использовать кластер из двух узлов, поскольку такая конфигурация может вызвать проблемы разделения кластера. Чтобы их избежать, добавьте узел-рефери.

    Ниже представлены возможные сценарии при отказе лидера или сбоях сети:

    • При отказе лидера узел-последователь автоматически становится новым лидером, если для параметра конфигурации biha.nquorum установлено значение 1.

    • Если между лидером и последователем происходят сетевые сбои, и для обоих параметров конфигурации biha.nquorum и biha.minnodes установлено значение 1, кластер может разделиться на двух лидеров, доступных для чтения и записи. Подобных проблем позволяет избежать узел-рефери.

  • Конфигурация с одним узлом-лидером. Этот вариант возможно использовать, пока не будут настроены последователи. Логично, что узел нельзя заменить при сбое ввиду отсутствия последователей, которые могут стать лидером.

  • Кластер с тремя узлами, состоящий из лидера, последователя и рефери. Узел-рефери используется для голосования при выборе нового лидера, но сам не может стать лидером. При возникновении сбоев кластер с рефери ведёт себя как кластер с тремя узлами (лидером и двумя последователями). Чтобы подробнее узнать о рефери, обратитесь к Узел-рефери в BiHA-кластере.

Примечание

  • Вы можете вручную назначить лидера с помощью функции biha.set_leader.

  • Рекомендуется установить для параметра biha.nquorum значение, большее или равное половине числа узлов в кластере.

  • При добавлении или удалении узлов из кластера всегда проверяйте значение biha.nquorum, учитывая наибольшее количество узлов, но не меньше, чем установлено в nquorum.

27.1.3. Выборы #

Выборы — это процесс определения лидера, который проводят последователи при отказе текущего лидера. В результате выборов лидером кластера становится последователь с наибольшим числом записей в WAL. Чтобы узел мог быть избран лидером, для параметров biha.can_be_leader и biha.can_vote этого узла должно быть установлено значение true.

Выборы проводятся с учётом кворума кластера, то есть минимального количества узлов, участвующих в голосовании. Значение кворума задаётся в параметре biha.nquorum при инициализации кластера командой bihactl init. Узлы, для которых в параметре biha.can_vote установлено значение false, исключаются из голосования и игнорируются в nquorum. Узлы в состоянии NODE_ERROR не могут голосовать.

Чтобы начались выборы, последователи должны не получить максимальное количество сообщений о контроле состояния, заданное функцией biha.set_heartbeat_max_lost. На этом этапе один из последователей выдвигает себя в качестве кандидата в лидеры (CANDIDATE), и начинаются выборы. Если в этом случае лидер не получает заданное количество сообщений о контроле состояния от последователя, состояние последователя меняется на UNKNOWN для лидера. В синхронном кластере можно задать приоритет узлов с помощью параметра biha.node_priority. Если в кластере только два узла и вы хотите избежать возможных проблем разделения кластера во время выборов, создайте узел-рефери, который участвует в голосовании так же, как последователи. За подробностями обратитесь к Узел-рефери в BiHA-кластере.

Например, в случае отказа одного узла-последователя в кластере из трёх узлов, где значение nquorum=2, узел-лидер продолжит работать. При отказе лидера в таком кластере два оставшихся последователя начнут выборы. После избрания нового лидера значение поколения кластера term увеличивается на единицу для всех узлов, то есть для нового лидера и оставшихся последователей term=2, а для старого лидера останется равным term=1. Когда старый лидер возвращается в кластер, происходит его понижение, то есть старый лидер становится последователем.

После избрания нового лидера последователи начинают получать файлы WAL уже от него. Обратите внимание, что при выборе нового лидера старый лидер понижается и становится недоступным для пишущих транзакций, чтобы избежать проблем разделения кластера (split brain). Вы можете вручную повысить старого лидера, используя функцию biha.set_leader. Механизмы кворума и поколения реализованы в BiHA на базе алгоритма консенсуса Raft.

27.1.4. Узел-рефери в BiHA-кластере #

В отказоустойчивом кластере можно создать узел-рефери, который участвует в выборах и помогает избежать потенциальной проблемы разделения кластера (split brain), состоящего только из лидера и последователя. В этом случае после создания рефери установите значение 2 для обоих параметров конфигурации biha.nquorum и biha.minnodes.

Для рефери требуется намного меньше дискового пространства, ресурсов процессора и памяти, чем для обычных узлов BiHA. За подробной информацией обратитесь к разделу Минимальные аппаратные требования для рефери.

По умолчанию на рефери отсутствует база данных postgres и пользовательские данные. За подробной информацией обратитесь к разделу База данных postgres на рефери.

Расширение biha поддерживает следующие режимы работы рефери:

  • Режим referee. В этом режиме узел принимает участие только в выборах лидера, но не в репликации данных. Кроме того, для рефери не создаются слоты репликации ни на лидере, ни на последователях.

  • Режим referee_with_wal. В этом режиме узел участвует не только в выборах лидера таким же образом, как и в режиме referee, но и в репликации данных, и получает весь WAL с узла-лидера. Если на момент начала выборов больше всего записей WAL среди узлов кластера накопится на узле-рефери, то есть у рефери будет наибольший LSN, узел-последователь будет пытаться получить недостающие файлы WAL с рефери. Этот процесс важен для того, чтобы узел-рефери не перешел в состояние NODE_ERROR, что возможно при расхождении WAL. Для referee_with_wal, apply lag равен NULL и apply ptr невозможно изменить, так как рефери не применяет данные пользователя.

Вне зависимости от установленного режима работы узла-рефери, он отправляет и получает сообщения о контроле состояния по каналу управления, в том числе с использованием SSL, участвует в выборах так же, как и узлы-последователи, поддерживает функции мониторинга кластера и должен учитываться, когда задаётся значение параметра biha.minnodes. Обратите внимание, что рефери — это конечное состояние узла: его нельзя сделать лидером при помощи функции biha.set_leader, и он не может стать узлом-последователем. Если по какой-либо причине последователь «не видит» лидера, но его видит рефери, рефери не позволит последователю стать лидером. Если лидер с более высоким значением поколения term подключится к рефери, рефери понизит статус лидера с более низким значением term до последователя.

27.1.4.1. Минимальные аппаратные требования для рефери #

В системах Linux для минимальной конфигурации узла-рефери в режиме referee требуется 1 ядро ЦП и 1 ГБ ОЗУ. Этого достаточно для участия в выборах.

Если рефери используется в режиме referee_with_wal, при котором рефери участвует в репликации данных и получает от лидера WAL в полном объёме, ресурсы для рефери необходимо выделять с учётом нагрузки на кластер.

Для операционных систем, отличных от Linux, необходимо выделять ресурсы в соответствии с минимальными требованиями используемой операционной системы.

Примечание

Так как рефери создаётся через частичное копирование лидера, он наследует и параметры конфигурации лидера. Чтобы избежать избыточного потребления ресурсов, перед первым запуском рефери убедитесь, что его параметры конфигурации соответствуют реальным аппаратным ресурсам сервера, на котором запущен рефери. Например, установите для параметра shared_buffers значение по умолчанию 128 МБ.

27.1.4.2. База данных postgres на рефери #

При добавлении рефери, утилита pg_basebackup создаёт частичную резервную копию лидера. Это значит, что, по умолчанию, на рефери с лидера копируются только база данных biha_db и системные таблицы. База данных postgres и пользовательские данные не копируются. Это сделано намеренно для уменьшения потребления ресурсов.

Однако некоторые утилиты и системы мониторинга используют базу данных postgres для подключения к узлам. Если необходимо, чтобы база данных postgres присутствовала на рефери, вы можете указать параметр --referee-with-postgres-db при добавлении узла в режиме referee или referee_with_wal. Этот параметр копирует на рефери базу данных postgres со всеми объектами. Для рефери в режиме referee_with_wal также применяются записи WAL, относящиеся к базе данных postgres. Это значит, что все новые объекты, созданные в базе данных postgres, будут также созданы на рефери в режиме referee_with_wal.

Примечание

Обратите внимание, что вышесказанное относится к базе данных postgres, создаваемой при инициализации экземпляра. Если удалить базу данных postgres на лидере, она также будет удалена и на рефери без возможности восстановления.

27.1. Architecture #

With built-in high-availability capabilities, Postgres Pro allows creating a cluster with one leader node and several follower nodes. The leader is the primary server of the BiHA cluster, while followers are its replicas.

The bihactl utility is used to initialize the cluster and create the leader, add followers, convert existing cluster nodes into the leader or the follower in the BiHA cluster as well as check the cluster node status. The leader is available for read and write transactions, while followers are read-only and replicate data from the leader in the synchronous or asynchronous mode.

Physical streaming replication implemented in BiHA ensures high availability by providing protection against server failures and data storage system failures. During physical replication, WAL files of the leader node are sent, synchronously of asynchronously, to the follower node and applied there. In case of synchronous replication, with each commit a user waits for the confirmation from the follower that the transaction is committed. The follower in the BiHA cluster can be used to:

  • Perform read transactions in the database.

  • Prepare reports.

  • Create in-memory tables open for write transactions.

  • Prepare a follower node backup.

  • Restore bad blocks of data on the leader node by receiving them from the follower node.

  • Check corrupt records in WAL files.

Physical streaming replication implemented in BiHA provides protection against several types of failures:

  • Leader node failure. In this case, a follower node is promoted and becomes the new leader of the cluster. The promotion can be done both manually using the biha.set_leader function or automatically by means of elections.

  • Follower node failure. If a follower node uses asynchronous replication, the failure by no means affects the leader node. If a follower node uses synchronous replication, this failure causes the transaction on the leader node to stop. This happens because the leader stops receiving transaction confirmations from the follower and the transaction fails to end. For details on how to set up synchronous replication in the BiHA cluster, see Replication Configuration.

  • Network failure between the leader node and follower nodes. In this case, the leader node cannot send and follower nodes cannot receive any data. Note that you cannot allow write transactions on follower nodes if users are connected to the leader node. Any changes made on follower nodes will not be restored on the leader node. To avoid this, configure your network with redundant channels. It is best to provide each follower with its own communication channel to avoid single point of failure issues.

In case of an emergency, such as operating system or hardware failure, you can reinstall Postgres Pro and remove the biha extension from shared_preload_libraries to go back to work as soon as possible.

27.1.1. Postgres Pro Configuration #

For proper operation, BiHA sets some Postgres Pro configuration parameters and creates a number of auxiliary objects:

  • The bihactl utility adds biha to the shared_preload_libraries variable of the postgresql.conf file and, if applicable, of the postgresql.auto.conf file:

    shared_preload_libraries = 'biha'
    

    This parameter is required for operation of the BiHA cluster. If shared_preload_libraries already contains other preloaded libraries, biha is added to the end of the list.

  • The bihactl utility creates the following files:

  • The biha_db database, the biha extension, and a number of BiHA-specific roles are created. For more information, see Roles.

  • Replication slots with names set in the biha_node_id format are created. These slots are managed automatically without the need to modify or delete them manually.

  • In the postgresql.biha.conf file, bihactl sets the following Postgres Pro configuration parameters:

    • hot_standby is set to on (the default). It is not recommended to modify this parameter.

    • wal_level is set to replica (the default). If the value has already been set to logical, BiHA uses the existing value. It is not recommended to modify this parameter.

    • max_wal_senders is set based on the number of WAL senders required for proper operation of BiHA that depends on the quorum set in biha.nquorum. If the nquorum value is 3 or less, the max_wal_senders value is 10. Otherwise, the value is calculated based on the following formula: BiHA_quorum * 2 + 3. Consider this when modifying the max_wal_senders value. For more information about decreasing max_wal_senders and some other Postgres Pro configuration parameters, see Section 27.1.1.1.

    • max_replication_slots is max_wal_senders + 1. The minimum value is 11. Consider this when modifying the max_replication_slots value.

    • max_slot_wal_keep_size is set to 5GB. If the value has already been set, BiHA uses the existing value. You can modify the value if required.

      Unlike standard primary-standby configuration, the BiHA cluster stores WAL files on all nodes to ensure that a lagging node can catch up. To achieve this, each node uses replication slots, identifies the node that is lagging the most, and retains as many WAL files as the lagging node might require.

      When setting up the BiHA cluster, ensure that you select the optimal value for this parameter to avoid the following issues:

      • If the number of required WAL files is higher than the max_slot_wal_keep_size value, the old WAL files are deleted. As a result, the lagging node cannot receive the required data, changes its state to NODE_ERROR, and stops data replication.

      • If the max_slot_wal_keep_size value is set to -1 (which means that WAL files are never deleted) or if it exceeds the available disk size, this may lead to disk storage overflow.

      • If the max_slot_wal_keep_size value is too small, there may not be enough space to keep WAL files required for the lagging node to catch up and continue operation.

    • wal_keep_size is set to 1GB. If the value has already been set, BiHA uses the existing value. The wal_keep_size configuration parameter helps to keep WAL files for a potential run of pg_rewind. You can modify the value depending on the workload. The more WAL files are generated, the higher the wal_keep_size value must be set.

    • application_name is set in the biha_node_id format. It is not recommended to modify this parameter.

    • listen_addresses is set to *. It is not recommended to modify this parameter.

    • port is set to the default Postgres Pro value. If the default port has been changed, BiHA uses the existing value. It is not recommended to modify this parameter.

    • primary_conninfo, primary_slot_name, synchronous_standby_names are modified and managed by BiHA only.

      When biha is loaded and configured, you cannot modify these parameters using ALTER SYSTEM.

      These parameters are stored in the pg_biha/biha.conf file, as well as in the shared memory of the biha process. When these parameters are modified, biha sends the SIGHUP signal for other processes to be informed about the changes. If you modify any other parameters during this change and do not send a signal to reread the configuration, the parameters that you have changed may be unexpectedly reread.

      Postgres Pro behaves as described above only when biha is loaded and configured, i.e. when the extension is present in the shared_preload_libraries variable and the required biha.* parameters are configured. Otherwise, Postgres Pro operates normally.

  • During operation, BiHA creates the following service files in the database directory:

    • standby.signal is used to start nodes in standby mode. It is required to make biha read-only at the start of Postgres Pro. This file is deleted from the leader node when its state changes to LEADER_RW.

    • biha.state and biha.conf are files in the pg_biha directory required to save the internal state and configuration of biha.

27.1.1.1. Decreasing Postgres Pro Parameter Values #

In a BiHA cluster, some Postgres Pro configuration parameter values can only be successfully decreased using the procedure described in this section.

Use this procedure if you need to decrease any of the following parameters:

Warning

Be careful when modifying these configuration parameters and ensure their values are the same on all BiHA cluster nodes. Otherwise, the leader change may lead to unexpected cluster behavior.

You can decrease the above mentioned configuration parameters as follows:

  1. On the leader, decrease the value of the required configuration parameter.

  2. (Optional) To avoid elections, increase the biha.nquorum value to the total number of cluster nodes using the biha.set_nquorum function.

  3. Stop and start the leader using pg_ctl.

    During startup, the leader verifies other nodes are operational and continue recognizing its leader role. If all nodes operate correctly, the leader applies the modified value and starts successfully. Otherwise, the leader shuts down and provides the corresponding log message.

  4. Ensure that all nodes receive information that the configuration parameter has been modified on the leader.

    You can use the pg_controldata utility or, alternatively, make a pause after the leader restarts so that other nodes could have enough time to receive the updates.

  5. On other nodes, decrease the configuration parameter to the value you have just set on the leader.

  6. Stop and start the nodes using pg_ctl.

27.1.2. Variants of Cluster Configuration #

There are several variants of the cluster configuration.

  • Three and more nodes where one node is the leader and the rest are the followers.

    Below are possible scenarios for the cases of the leader failure or network connection interruption:

    • When the current leader is down, the new leader is elected automatically. To become the leader, a follower must have the highest number of votes. The number of votes must be higher or equal to the value configured in biha.nquorum.

    • In case of network connection interruptions inside the BiHA cluster, the cluster may split into several groups of nodes. In this case, the new leader node is elected in all groups, where the number of nodes is higher or equal to the biha.nquorum value. After the connection is restored, the new leader will be chosen between the old one and the newly elected one depending on the term value. The node with the highest term becomes the new leader. It is recommended to set the biha.minnodes value equal to the biha.nquorum value.

  • Two-node cluster consisting of the leader and the follower.

    Note

    Using two-node clusters is not recommended as such configurations can cause split-brain issues. To avoid such issues, you can add a referee node.

    Below are possible scenarios for the leader or network failures:

    • When the leader is down, the follower node becomes the new leader automatically if the biha.nquorum configuration parameter is set to 1.

    • When network interruptions occur between the leader and the follower, and both the biha.nquorum and biha.minnodes configuration parameters are set to 1, the cluster may split into two leaders available for reads and writes. The referee node helps avoiding such issues.

  • Single-node configuration consisting of the leader only. A possible variant that can be used to wait until follower nodes are configured. Logically, the node cannot be replaced once down, since there are no follower nodes that can become the leader node.

  • Three-node cluster consisting of the leader, the follower, and the referee. The referee is a node used for voting in elections of the new leader, but it cannot become the leader. In case of faults, the cluster with the referee behaves the same way as the three-node cluster (the leader and two followers). To learn more about the referee, see The Referee Node in the BiHA Cluster.

Note

  • You can set the leader manually with the biha.set_leader function.

  • The recommended value of biha.nquorum is higher or equal to the half of the cluster nodes.

  • When you add or remove nodes from your cluster, always revise the biha.nquorum value considering the highest number of nodes, but not less than set in nquorum.

27.1.3. Elections #

Elections are a process conducted by the follower nodes to determine a new leader node when the current leader is down. As a result of the elections, the follower node with the most records in the WAL becomes the cluster leader. To be elected, a node must have the biha.can_be_leader and biha.can_vote parameters set to true.

Elections are held based on the cluster quorum, which is the minimum number of nodes that participate in the leader election. The quorum value is set in the biha.nquorum parameter when initializing the cluster with the bihactl init command. Nodes with the biha.can_vote parameter set to false are excluded from voting and are ignored by nquorum. Nodes in the NODE_ERROR state are unable to vote.

For the elections to begin, the followers must miss the maximum number of heartbeats from the leader set by the biha.set_heartbeat_max_lost function. At this point one of the followers proposes itself as a leader CANDIDATE, and elections begin. If the leader does not receive the set number of heartbeats from the follower in this case, the follower state changes to UNKNOWN for the leader. In a synchronous cluster, you can use the biha.node_priority parameter to prioritize the nodes. If your cluster has only two nodes and you want to avoid potential split-brain issues in case of elections, you can set up a referee node that participates in the elections in the same way as followers. To learn more, see The Referee Node in the BiHA Cluster.

For example, if you have a cluster with three nodes where nquorum=2 and one follower node is down, the cluster leader will continue to operate. If the leader is down in such a cluster, two remaining followers start elections. After the new leader node is elected, the node generation specified in the term is incremented for all cluster nodes. More specifically, the new leader and the remaining followers have term=2, while for the old leader the value is left as term=1. Therefore, when the old leader is back in the cluster, it goes through demotion, i.e. turns into a follower.

After the new leader is set, followers of the cluster start receiving WAL files from this new cluster leader. Note that once the new leader is elected, the old leader is demoted and is not available for write transactions to avoid split-brain issues. You can promote the old leader manually using the biha.set_leader function. Both the cluster quorum and the term concepts are implemented in BiHA based on the Raft consensus algorithm.

27.1.4. The Referee Node in the BiHA Cluster #

The biha extension allows you to set up the referee node that participates in elections and helps to avoid potential split-brain issues if your cluster has only two nodes, i.e. the leader and one follower. In this case, use the referee node and set both biha.nquorum and biha.minnodes configuration parameters to 2.

The referee node requires much less disk space, CPU, and RAM than regular BiHA nodes. For more information, refer to Minimum Hardware Requirements for the Referee.

By default, the postgres database and user data are not present on the referee node. For more information, refer to The postgres Database on the Referee.

The biha extension provides the following referee operation modes:

  • The referee mode. In this mode, the node only takes part in elections of the leader and does not participate in data replication, and no replication slots are created on the leader and follower nodes for the referee.

  • The referee_with_wal mode. In this case, the node participates both in the leader elections, in the same way as in the referee mode, and data replication and receives the entire WAL from the leader node. If the referee node has the most WAL records in the cluster when the elections begin, i.e. has the greatest LSN, the follower node tries to get missing WAL files from the referee. This process is also important for the referee node to avoid entering the NODE_ERROR state, which may be the case if WALs diverge. For the referee_with_wal, apply lag is NULL and apply ptr cannot be monitored, as the referee does not apply user data.

Regardless of the mode set for the referee, it sends and receives heartbeats over the control channel, including using SSL, participates in the elections in the same way as follower nodes, supports cluster monitoring functions, and must be taken into account when setting the biha.minnodes configuration parameter. Note that the referee is the final state of the node and it cannot be switched to the leader node using the biha.set_leader function, nor can it become the follower node. If for some reason the follower does not see the leader but the referee does, the referee does not allow the follower to become the leader. If the leader node with greater term connects to the referee node, the referee demotes the leader with lower term and makes it the follower.

27.1.4.1. Minimum Hardware Requirements for the Referee #

On Linux systems, the minimum configuration of the referee node in the referee mode requires 1 CPU and 1 GB RAM, which is enough for participating in elections.

If you use the referee in the referee_with_wal mode, where the referee participates in data replication and receives the entire WAL from the leader, you must allocate resources for the referee considering workloads of your cluster.

For operating systems other than Linux, you must allocate resources according to the minimum requirements for your specific operating system.

Note

Note that the referee is created via partial copy of the leader and, as a result, inherits its configuration parameters. To avoid unnecessary resource consumption, before you start the referee for the first time, ensure its configuration parameters are aligned with the actual hardware resources of the server the referee is running on. For example, set shared_buffers to the default 128 MB.

27.1.4.2. The postgres Database on the Referee #

When adding the referee node, the pg_basebackup utility makes a partial backup of the leader. It means that, by default, only the biha_db database and system tables are copied to the referee node from the leader, while the postgres database and user data are not copied. It was designed intentionally to decrease resource consumption.

However, some utilities and monitoring systems connect to nodes via the postgres database. If you need the postgres database to be present on the referee node, you can specify the --referee-with-postgres-db option when adding a node in referee or referee_with_wal modes. This option copies the postgres database with all the objects to the referee node. For referee_with_wal, WAL records related to the postgres database are also applied, meaning that all new objects created in the postgres database are also created on the referee in the referee_with_wal mode.

Note

Note that this refers to the postgres database created during instance initialization. If you delete the postgres database from the leader, it is also deleted on the referee, and you cannot recreate it.

FAQ