Skip to content

This is the multi-page printable view of this section. .

Return to the regular view of this page.

Patroni 4.1.5 Documentation

Overview of Patroni high-availability documentation for PostgreSQL.

Source: https://patroni.readthedocs.io/en/latest/index.html

Warning

Running Patroni on memory-restricted systems with Python 3.11+

Unexpected behavior can occur with Python 3.11 or newer on systems with strict memory limits. For example, this includes vm.overcommit_memory=2, which is recommended for PostgreSQL. You may observe these symptoms:

  • Patroni appears healthy
  • PostgreSQL continues to run
  • Patroni REST API becomes unresponsive
  • The operating system reports that Patroni is listening on the REST API port
  • Patroni logs look normal; however, following messages may appear once: Exception ignored in thread started by: <object repr() failed>, MemoryError
  • Kernel logs may contain messages such as not enough memory for the allocation

A bug in Python 3.11+ causes this behavior. Under strict memory conditions, a new thread may hang indefinitely if free memory is insufficient.

Recent Patroni releases (4.1.1+, 4.0.8+) start all required threads early, before the system has memory pressure. This reduces the impact of the issue.

Additional recommendations (Linux, glibc)

When you use vm.overcommit_memory=2 (recommended for PostgreSQL), we also recommend these environment variables before you start Patroni:

  • MALLOC_ARENA_MAX=1 - reduces the amount of virtual memory allocated by glibc for multi-threaded applications
  • PG_MALLOC_ARENA_MAX= - resets the value of MALLOC_ARENA_MAX for PostgreSQL processes started by Patroni.

In addition, you may tune the following Patroni configuration parameters:

  • thread_stack_size - Stack size for threads that Patroni starts. A lower value reduces Patroni memory usage. The default is 512kB. Increase thread_stack_size if Patroni has stack-related crashes. Otherwise, the default is sufficient.
  • thread_pool_size - Thread pool size for asynchronous tasks and REST API communication with other members during leader races or failsafe checks. The default is 5, which is sufficient for three-node clusters.
  • restapi.thread_pool_size - Thread pool size for REST API requests. The default is 5, which allows up to five parallel requests. Requests with SQL queries effectively run in sequence because they use one database connection. A higher value typically gives no benefit.

Patroni is a Python template for high availability (HA) PostgreSQL solutions. It supports distributed configuration stores such as ZooKeeper, etcd, Consul, and Kubernetes. Database engineers, DBAs, DevOps engineers, and SREs can use it to deploy HA PostgreSQL quickly in datacenters or other environments.

Patroni is a template. Its replication system needs configuration for your requirements and has limitations that you must consider. PostgreSQL supports many high-availability approaches. See the PostgreSQL Documentation for a list.

Currently supported PostgreSQL versions: 9.3 to 18.

Note to Citus users: Patroni 3.0 and later integrate with the Citus database extension to Postgres. See the Citus support page for Patroni high availability with a Citus distributed cluster.

Note to Kubernetes users: Patroni can run natively on Kubernetes. See the Kubernetes chapter.

image

1 - Introduction

Patroni introduction, quick start, and core high-availability concepts.

Source: https://patroni.readthedocs.io/en/latest/README.html

Patroni is a Python template for high availability (HA) PostgreSQL solutions. It started as a fork of Governor, a Compose project, and adds many features.

For additional background info, see:


Development Status

Patroni is in active development and accepts contributions. See Contributing for details.

See release information for new releases.


Technical Requirements/Installation

See the installation guide to install and upgrade Patroni on different platforms.


Planning the Number of PostgreSQL Nodes

Patroni/PostgreSQL nodes are independent of DCS nodes, except when Patroni implements RAFT itself. Thus, there is no minimum node count for Patroni/PostgreSQL. A cluster can have one primary and one standby. You can add more standby nodes later.

2-node clusters (primary + standby) are common and provide automatic failover with high availability. During failover, the cluster temporarily has no redundancy until the failed node rejoins.

DCS requirements: Your DCS (etcd, ZooKeeper, Consul) must have 3 or 5 nodes for consensus and fault tolerance. One DCS cluster can store data for hundreds or thousands of Patroni clusters. Use different namespace/scope combinations for these clusters.


Running and Configuring

This section assumes you cloned the Patroni repository from https://github.com/patroni/patroni. You need the example configuration files postgres0.yml and postgres1.yml. If you installed Patroni with pip, get these files from the git repository. Then replace ./patroni.py below with the patroni command.

To start, run these commands in separate terminals:

> etcd --data-dir=data/etcd --enable-v2=true
> ./patroni.py postgres0.yml
> ./patroni.py postgres1.yml

These commands start a high-availability cluster. Test different YAML settings to see how they change cluster behavior. Stop some components to test how the system responds.

Add more postgres*.yml files to create an even larger cluster.

Patroni provides an HAProxy configuration. It gives your application one endpoint to connect to the cluster leader. To configure it, run:

> haproxy -f haproxy.cfg

> psql --host 127.0.0.1 --port 5000 postgres

YAML Configuration

See YAML settings for details about etcd, consul, and ZooKeeper settings. See postgres0.yml for an example.


Environment Configuration

See environment settings to configure or override settings with environment variables.


Replication Choices

Patroni uses Postgres streaming replication, which is asynchronous by default. Set maximum_lag_on_failover to prevent failover when a replica is more than the specified number of bytes behind the leader. Adjust this setting for your business requirements. You can also use synchronous replication for stronger durability guarantees. See replication modes documentation for details.


Applications Should Not Use Superusers

Always use a non-superuser for application connections. Patroni needs database access to operate correctly. An application that uses a superuser can consume all connections, including those reserved by superuser_reserved_connections. If no connections remain, Patroni cannot access the primary and can behave incorrectly.


Testing Your HA Solution

HA testing takes time and involves many variables, especially for a cross-platform application. A trained system administrator or consultant must do this work. These documents do not cover the process in detail.

Test these parts of your infrastructure:

  • Network (the network in front of your system as well as the NICs physicalorvirtualphysical or virtualthemselves)
  • Disk IO
  • file limits (nofile in Linux)
  • RAM. Even if you have oomkiller turned off, the unavailability of RAM could cause issues.
  • CPU
  • Virtualization Contention (overcommitting the hypervisor)
  • Any cgroup limitation (likely to be related to the above)
  • kill -9 of any postgres process (except postmaster!). This is a decent simulation of a segfault.

Do not run kill -9 on a postmaster process. This does not simulate a real-world failure. If an attacker can run kill -9, an HA process cannot resolve the security problem. The attacker can kill the process again or cause other damage.

2 - Installation

Installation and upgrade instructions for Patroni across supported platforms.

Source: https://patroni.readthedocs.io/en/latest/installation.html


Pre-requirements for Mac OS

On a Mac, install the requirements:

brew install postgresql etcd haproxy libyaml python


Psycopg

Since psycopg2-2.8, the binary package is not installed by default. A source installation requires a C compiler and Postgres and Python development packages. Python dependencies cannot express psycopg2 OR psycopg2-binary. Select an installation method:

  1. Use the package manager from your distro
sudo apt-get install python3-psycopg2  # install psycopg2 module on Debian/Ubuntu
sudo yum install python3-psycopg2      # install psycopg2 on RedHat/Fedora/CentOS
  1. Specify one of psycopg, psycopg2, or psycopg2-binary in the list of dependencies when installing Patroni with pip.


General installation for pip

Patroni can be installed with pip:

pip install patroni[dependencies]

Leave dependencies empty, or specify one or more of these dependencies:

etcd or etcd3
python-etcd module to use Etcd as the Distributed Configuration Store (DCS)

consul
py-consul module to use Consul as the DCS

zookeeper
kazoo module to use Zookeeper as the DCS

exhibitor
kazoo module to use Exhibitor as the DCS (same dependencies as Zookeeper)

kubernetes
kubernetes module to use Kubernetes as the DCS

raft
pysyncobj module to use the Python Raft implementation as the DCS

aws
boto3 to use AWS callbacks

jsonlogger
python-json-logger module for JSON logging

systemd
systemd-python for sd_notify integration

all
all of the above (except psycopg family)

psycopg3
psycopg\[binary\]\>=3.0.0 module

psycopg2
psycopg2\>=2.5.4 module

psycopg2-binary
psycopg2-binary module

For example, install Patroni with psycopg3, Etcd DCS dependencies, and AWS callbacks:

pip install patroni[psycopg3,etcd3,aws]

Install external tools, such as WAL-E, separately if your replica creation or custom bootstrap scripts call them.


Package installation on Linux

The Postgres community may provide Patroni packages for these operating systems:

  • RHEL, RockyLinux, AlmaLinux;
  • Debian and Ubuntu;
  • SUSE Enterprise Linux.

Packages may also provide direct dependencies, such as Python modules absent from the operating system repositories.

For more information see the PGDG repository documentation.

On RedHat Enterprise Linux derivatives, you may also need EPEL packages. See the EPEL repository documentation.

After you configure the PGDG repository for your operating system, install Patroni.

Note

The Postgres community maintains these packages, rather than the Patroni developers. For support, first contact Postgres slack.

Installing on Debian derivatives

After you configure the PGDG repository, install Patroni with apt:

apt-get install patroni

Installing on RedHat derivatives

On RHEL 9 and derivatives, first configure the PGDG repository. Then install Patroni with an etcd DCS:

dnf install patroni patroni-etcd

If your RedHat derivative does not provide etcd packages, install them from PGDG. On each DCS node, run:

dnf install 'dnf-command(config-manager)'
dnf config-manager --enable pgdg-rhel9-extras
dnf install etcd

For RHEL 8, replace the version with 8 to use pgdg-rhel8-extras. RockyLinux, AlmaLinux, Oracle Linux, and other derivatives also use the pgdg-rhelN-extras repository name.

Installing on SUSE Enterprise Linux

Some dependencies may require SUSE PackageHub repositories. See the SUSE PackageHub documentation.

On SLES 15, configure the PGDG repository. Then install Patroni:

zypper install patroni patroni-etcd

With the SUSE PackageHub repo enabled you can also install etcd:

SUSEConnect -p PackageHub/15.5/x86_64
zypper install etcd

Upgrading

To upgrade Patroni, update the software and restart the Patroni daemon on each cluster node.

A Patroni daemon restart also restarts the Postgres database. This can cause primary failover. We recommend maintenance mode until all Patroni daemon restarts finish.

On one Patroni node, put the cluster in maintenance mode:

patronictl pause --wait

Then on each node in the cluster, perform the package upgrade required for your OS:

apt-get update && apt-get install patroni patroni-etcd

Restart the patroni daemon process on each node:

systemctl restart patroni

Resume Patroni monitoring and leave maintenance mode:

patronictl resume --wait

The cluster now operates fully with the new Patroni version.

3 - Patroni configuration

Patroni configuration model, precedence rules, and validation tooling.

Source: https://patroni.readthedocs.io/en/latest/patroni_configuration.html

There are 3 types of Patroni configuration:

  • Global dynamic configuration.
    These options are stored in the DCS (Distributed Configuration Store) and apply to all nodes. Change them at any time with patronictl_edit_config or the REST API. Changes outside startup configuration apply asynchronously on each node’s next wake-up cycle, followed by a reload. Changed PostgreSQL parameters with postmaster context require a restart. Patroni sets pending_restart in members.data JSON for these nodes. Node status also shows "restart_pending": true.

  • Local configuration file (patroni.yml).
    Local options override dynamic configuration. To reload patroni.yml without restarting Patroni, send SIGHUP, send POST /reload, or run patronictl_reload. Local configuration can be one YAML file or a directory. Patroni loads all YAML files in a directory in sorted order. If several files define a key, the last file takes precedence.

  • Environment configuration.
    Environment variables can set or override some local parameters. Use them in dynamic environments where some values are unknown in advance. For example, the external IP address may be unknown inside docker.


Important rules

PostgreSQL parameters controlled by Patroni

These PostgreSQL parameters must have the same values on the primary and replicas. Local configuration and environment values have no effect. Set them through shared DCS configuration. The list shows their defaults and minimum values:

  • max_connections: default value 100, minimal value 25
  • max_locks_per_transaction: default value 64, minimal value 32
  • max_worker_processes: default value 8, minimal value 2
  • max_prepared_transactions: default value 0, minimal value 0
  • wal_level: default value hot_standby, accepted values: hot_standby, replica, logical
  • track_commit_timestamp: default value off

PostgreSQL permits different primary and replica values for the parameters below. However, a replica can become primary at any time. Different values are therefore unsuitable, and Patroni permits changes only through dynamic configuration.

  • max_wal_senders: default value 10, minimal value 3
  • max_replication_slots: default value 10, minimal value 4
  • wal_keep_segments: default value 8, minimal value 1
  • wal_keep_size: default value 128MB, minimal value 16MB
  • wal_log_hints: on

Patroni validates these values for correctness or a required minimum.

There are some other Postgres parameters controlled by Patroni:

  • listen_addresses - is set either from postgresql.listen or from PATRONI_POSTGRESQL_LISTEN environment variable
  • port - is set either from postgresql.listen or from PATRONI_POSTGRESQL_LISTEN environment variable
  • cluster_name - is set either from scope or from PATRONI_SCOPE environment variable
  • hot_standby: on

Patroni writes the parameters above to postgresql.conf. Except for wal_keep_segments and wal_keep_size, it also passes them as postgres arguments. These arguments take precedence over all other settings, including ALTER SYSTEM.

Parameters such as postgresql.listen and postgresql.data_dir can only be set locally. Use the configuration file or environment variables. Local configuration overrides dynamic configuration in most cases.

When applying the local or dynamic configuration options, the following actions are taken:

  • The node checks for postgresql.base.conf and custom_conf.
  • If custom_conf is set, its file supplies the base configuration. Patroni ignores postgresql.base.conf and postgresql.conf as base files.
  • Otherwise, an existing postgresql.base.conf supplies the base configuration. It contains the renamed original configuration.
  • If neither exists, Patroni renames the original postgresql.conf to postgresql.base.conf and uses it as the base.
  • Patroni writes dynamic options to postgresql.conf, subject to the exceptions above. It adds an include for postgresql.base.conf or the custom_conf file. New options can then apply without rereading the file to check for the include.
  • Command-line arguments override parameters essential for Patroni cluster management.
  • If a changed value requires restart according to pg_settings context, Patroni sets pending_restart on the node. Any restart resets this flag.

The parameters would be applied in the following order (run-time are given the highest priority):

  1. load parameters from file postgresql.base.conf (or from a custom_conf file, if set)
  2. load parameters from file postgresql.conf
  3. load parameters from file postgresql.auto.conf
  4. run-time parameter using -o --name=value

This order supports shared node configuration (2) and node-specific ALTER SYSTEM settings (3). It enforces essential Patroni parameters (4). It also permits external tools to manage the base configuration directly (1).

PostgreSQL parameters that touch shared memory

PostgreSQL has some parameters that determine the size of the shared memory used by them:

  • max_connections
  • max_prepared_transactions
  • max_locks_per_transaction
  • max_wal_senders
  • max_worker_processes

Changes require a PostgreSQL restart. Standby shared memory structures must not be smaller than the corresponding primary structures.

Change these values through dynamic configuration, as Patroni requires. The usual sequence is:

  1. Applying changes through patronictl_edit_config (or via REST API /config endpoint)
  2. Restarting nodes through patronictl_restart (or via REST API /restart endpoint)

Note: Restart PostgreSQL through patronictl_restart or the REST API /restart endpoint. Restarting the Patroni daemon with systemctl restart patroni can trigger failover if the node is primary.

These shared memory settings require a specific restart order:

  • If you want to increase the value of any of those settings:

    1. Restart all standbys first
    2. Restart the primary after that
  • If you want to decrease the value of any of those settings:

    1. Restart the primary first
    2. Restart all standbys after that

Note: If you restart all nodes together after a decrease, Patroni restarts standbys with the original value. You must restart them again later. This prevents an endless crash loop: PostgreSQL exits with FATAL if a value is below that recorded in standby pg_controldata. A standby value can decrease only after its pg_controldata reflects the primary change.

More information about that can be found at PostgreSQL Administrator’s Overview.

Patroni configuration parameters

Also the following Patroni configuration options can be changed only dynamically:

  • ttl: 30
  • loop_wait: 10
  • retry_timeout: 10
  • maximum_lag_on_failover: 1048576
  • max_timelines_history: 0
  • check_timeline: false
  • postgresql.use_slots: true

After a change, Patroni reads the relevant DCS configuration section and updates its runtime values.

After each configuration change, Patroni writes DCS options to patroni.dynamic.json in the Postgres data directory. Only the leader can restore these options from disk. It can do so only when DCS options are absent or invalid.


Configuration generation and validation

The patroni executable can generate and validate local configuration. Use it to:

  • Create a sample local Patroni configuration;
  • Create a Patroni configuration file for the locally running PostgreSQL instance (e.g. as a preparation step for the Patroni integration);
  • Validate a given Patroni configuration file.

Sample Patroni configuration

patroni --generate-sample-config [configfile]

Description

Generate a sample Patroni configuration in yaml format. Values come from Environment configuration. For unset parameters, use Patroni defaults or #FIXME for values that the user must supply.

Some default values are defined based on the local setup:

  • postgresql.listen: the IP address returned by gethostname call for the current machine’s hostname and the standard 5432 port.
  • postgresql.connect_address: the IP address returned by gethostname call for the current machine’s hostname and the standard 5432 port.
  • postgresql.authentication.rewind: is only defined if the PostgreSQL version can be defined from the binary and the version is 11 or later.
  • restapi.listen: IP address returned by gethostname call for the current machine’s hostname and the standard 8008 port.
  • restapi.connect_address: IP address returned by gethostname call for the current machine’s hostname and the standard 8008 port.

Parameters

configfile - full path to the configuration file used to store the result. If not provided, the result is sent to stdout.

Patroni configuration for a running instance

patroni --generate-config [--dsn DSN] [configfile]

Description

Generate a yaml configuration for the local running PostgreSQL instance. Connection settings use the supplied DSN first, then PostgreSQL environment variables. If no password is supplied, enter it at the prompt.

All non-internal GUCs from the source instance supply these Patroni parameters. This includes GUCs set through files, postmaster command-line arguments, or environment variables:

  • scope: cluster_name GUC value;
  • postgresql.listen: listen_addresses and port GUC values;
  • postgresql.datadir: data_directory GUC value;
  • postgresql.parameters: archive_command, restore_command, archive_cleanup_command, recovery_end_command, ssl_passphrase_command, hba_file, ident_file, config_file GUC values;
  • bootstrap.dcs: all other gathered PostgreSQL GUCs.

If Postgres GUCs do not supply scope, postgresql.listen, or postgresql.datadir, Patroni uses the corresponding Environment configuration value.

Other rules applied for the values definition:

  • name: PATRONI_NAME environment variable value if set, otherwise the current machine’s hostname.
  • postgresql.bin_dir: path to the Postgres binaries gathered from the running instance.
  • postgresql.connect_address: the IP address returned by gethostname call for the current machine’s hostname and the port used for the instance connection or the port GUC value.
  • postgresql.authentication.superuser: the configuration used for the instance connection;
  • postgresql.pg_hba: the lines gathered from the source instance’s hba_file.
  • postgresql.pg_ident: the lines gathered from the source instance’s ident_file.
  • restapi.listen: IP address returned by gethostname call for the current machine’s hostname and the standard 8008 port.
  • restapi.connect_address: IP address returned by gethostname call for the current machine’s hostname and the standard 8008 port.

The generated file also includes other parameters from Environment configuration.

Parameters

configfile
Full path to the configuration file used to store the result. If not provided, result is sent to stdout.

dsn
Optional DSN string for the local PostgreSQL instance to get GUC values from.

Validate Patroni configuration

patroni --validate-config [configfile] [--ignore-listen-port | -i]

Description

Validate the Patroni configuration and print failed checks.

Parameters

configfile
Full path to the file to check. If absent or nonexistent, read PATRONI_CONFIG_VARIABLE. If that variable is unset, use Patroni environment variables.

--ignore-listen-port | -i
Optional flag to ignore bind failures for occupied listen ports during configfile validation.

--print | -p
Optional flag to print local configuration, including environment overrides, after successful validation.

3.1 - Dynamic Configuration Settings

Dynamic configuration settings stored in DCS and applied cluster-wide.

Source: https://patroni.readthedocs.io/en/latest/dynamic_configuration.html

Dynamic configuration is stored in the DCS (Distributed Configuration Store) and applied on all cluster nodes.

Change dynamic configuration with patronictl_edit_config or the Patroni REST API.

  • loop_wait: the number of seconds the loop will sleep. Default value: 10, minimum possible value: 1
  • ttl: leader lock TTL, in seconds. This is the interval before automatic failover can start. Default: 30. Minimum: 20.
  • retry_timeout: timeout for DCS and PostgreSQL operation retries (in seconds). DCS or network issues shorter than this will not cause Patroni to demote the leader. Default value: 10, minimum possible value: 3
Warning

when changing values of loop_wait, retry_timeout, or ttl you have to follow the rule:

loop_wait + 2 * retry_timeout <= ttl
  • maximum_lag_on_failover: the maximum bytes a follower may lag to be able to participate in leader election.
  • primary_race_backoff: delays standby leader races by primary_race_backoff seconds while WAL replication from the primary advances. This reduces unnecessary failovers when Patroni is briefly unresponsive. Default: 0 (disabled).
  • maximum_lag_on_syncnode: maximum synchronous replica lag in bytes before replacement by a healthy asynchronous replica. With multiple replicas, Patroni uses the maximum replica LSN. Otherwise, it uses the leader’s current WAL LSN. Default: -1. Values of 0 or less disable replacement. Use a sufficiently high value to avoid frequent replacements during high transaction volume.
  • max_timelines_history: maximum number of timeline history items kept in DCS. Default value: 0. When set to 0, it keeps the full history in DCS.
  • primary_start_timeout: seconds allowed for primary recovery before failover. Default: 300. A value of 0 permits immediate failover after crash detection. Asynchronous failover can lose transactions. Worst-case failover time is loop_wait + primary_start_timeout + loop_wait, or only loop_wait when primary_start_timeout is zero. Select the value for your durability and availability requirements.
  • primary_stop_timeout: seconds Patroni can wait for Postgres shutdown when synchronous_mode is enabled. With synchronous_mode enabled and a value > 0, Patroni sends SIGKILL to postmaster if shutdown exceeds this interval. Select the value for your durability and availability requirements. Unset values or values <= 0 disable this timeout.
  • synchronous_mode: synchronous replication mode: off, on, or quorum. The leader manages synchronous_standby_names. Only the last known leader or synchronous replicas can enter a leader race. This protects successful commits during failover but can block writes when Patroni cannot guarantee durability. See replication modes documentation.
  • synchronous_mode_strict: keeps synchronous replication enabled when no synchronous replica is available, blocking client writes. Without an eligible streaming replica, Patroni uses the last synchronous nodes from /sync for synchronous_standby_names. If no prior state exists, it uses __patroni_strict_sync_replica_placeholder__. Do not use that reserved value for the node name in patroni.yaml. See replication modes documentation.
  • synchronous_node_count: required synchronous standby count when synchronous_mode is enabled. Patroni updates the DCS and PostgreSQL synchronous_standby_names as members join or leave. It reduces the count if it exceeds the number of eligible nodes. Default: 1.
  • failsafe_mode: Enables DCS Failsafe Mode. Defaults to false.
  • postgresql:
    • use_pg_rewind: enables pg_rewind. Default: false. For correct operation, pg_rewind requires data page checksums and/or wal_log_hints set to on. Enable checksums with the --data-checksums option for initdb.
    • use_slots: whether or not to use replication slots. Defaults to true on PostgreSQL 9.4+.
    • recovery_conf: extra recovery.conf settings for replicas. PostgreSQL 12 no longer uses recovery.conf. You can still use this section because Patroni handles the version difference.
    • parameters: configuration parameters (GUCs) for Postgres in format {max_connections: 100, wal_level: "replica", max_wal_senders: 10, wal_log_hints: "on"}. Many of these are required for replication to work.
    • parameters_primary: (optional) role-specific parameter overrides for primary. These values are merged with and override the base parameters.
    • parameters_replica: (optional) role-specific parameter overrides for replica. These values are merged with and override the base parameters.
    • parameters_standby_leader: (optional) role-specific parameter overrides for standby_leader. These values are merged with and override the base parameters.
    • pg_hba: list of lines that Patroni will use to generate pg_hba.conf. Patroni ignores this parameter if hba_file PostgreSQL parameter is set to a non-default value.
      • - host all all 0.0.0.0/0 md5
      • - host replication replicator 127.0.0.1/32 md5: A line like this is required for replication.
    • pg_hba_primary: (optional) role-specific pg_hba entries for primary. These completely replace pg_hba (no merging). If not defined, pg_hba is used.
    • pg_hba_replica: (optional) role-specific pg_hba entries for replica. These completely replace pg_hba (no merging). If not defined, pg_hba is used.
    • pg_hba_standby_leader: (optional) role-specific pg_hba entries for standby_leader. These completely replace pg_hba (no merging). If not defined, pg_hba is used.
    • pg_ident: list of lines that Patroni will use to generate pg_ident.conf. Patroni ignores this parameter if ident_file PostgreSQL parameter is set to a non-default value.
      • - mapname1 systemname1 pguser1
      • - mapname1 systemname2 pguser2
    • pg_ident_primary: (optional) role-specific pg_ident entries for primary. These completely replace pg_ident (no merging). If not defined, pg_ident is used.
    • pg_ident_replica: (optional) role-specific pg_ident entries for replica. These completely replace pg_ident (no merging). If not defined, pg_ident is used.
    • pg_ident_standby_leader: (optional) role-specific pg_ident entries for standby_leader. These completely replace pg_ident (no merging). If not defined, pg_ident is used.
  • standby_cluster: if this section is defined, we want to bootstrap a standby cluster.
    • host: an address of remote node
    • port: a port of remote node
    • primary_slot_name: replication slot on the remote node. Optional. The default comes from the instance name; see slot_name_from_member_name.
    • create_replica_methods: ordered methods to bootstrap the standby leader from the remote primary. This list can differ from postgresql_settings.
    • restore_command: command to restore remote primary WAL records to standby cluster nodes. It can differ from postgresql_settings.
    • archive_cleanup_command: cleanup command for standby leader
    • recovery_min_apply_delay: how long to wait before actually apply WAL records on a standby leader
  • member_slots_ttl: physical slot retention after replicas shut down. Default: 30min. A value of 0 restores immediate removal when the member key expires from the DCS. Requires PostgreSQL 11 or later.
  • slots: permanent replication slots, retained through switchover and failover. Patroni creates missing slots. On PostgreSQL 11 and later, it creates physical slots on all nodes and advances them every loop_wait seconds. Earlier versions maintain permanent physical slots only on the primary. Logical slots are copied from the primary to a standby with restart. Their positions then advance every loop_wait seconds if necessary. Patroni copies logical slot files through libpq with rewind or superuser credentials; see postgresql.authentication. A replica slot can lag behind the old primary. Applications must handle repeated messages after failover, for example by tracking confirmed_flush_lsn. Permanent slots require postgresql.use_slots set to true. Permanent logical slots automatically enable hot_standby_feedback. Logical slot failover is unsafe on PostgreSQL 9.6 and older, and PostgreSQL 10 lacks required functions. This feature requires PostgreSQL 11+.
    • my_slot_name: permanent slot name. Patroni does not create a slot on the node with the same name. A permanent physical slot named after a member remains even when that member becomes unresponsive. Normally, Patroni would remove it. This preserves member slots during temporary failures or migration to Patroni; see Convert a Standalone to a Patroni Cluster. Remove these matching names from DCS configuration when the slots are no longer required. Otherwise, they affect normal Patroni operation.
      • type: physical or logical. Logical slots also require database and plugin. Physical slots optionally accept cluster_type.
      • database: the database name where logical slots should be created.
      • plugin: the plugin name for the logical slot.
      • cluster_type: create the slot only on this cluster type: primary or standby. On other types, Patroni skips creation or drops an existing slot.
  • ignore_slots: sets of slot properties that Patroni must ignore. Use this for slots managed outside Patroni. Any matching subset of properties causes a slot to be ignored.
    • name: the name of the replication slot.
    • type: slot type. Can be physical or logical. If the slot is logical, you may additionally define database and/or plugin.
    • database: the database name (when matching a logical slot).
    • plugin: the logical decoding plugin (when matching a logical slot).

Note: slots is a hashmap while ignore_slots is an array. For example:

slots:
  permanent_logical_slot_name:
    type: logical
    database: my_db
    plugin: test_decoding
  permanent_physical_slot_name:
    type: physical
  ...
ignore_slots:
  - name: ignored_logical_slot_name
    type: logical
    database: my_db
    plugin: test_decoding
  - name: ignored_physical_slot_name
    type: physical
  ...

Note: On PostgreSQL v11 or later, Patroni maintains physical slots on all nodes eligible to become leader. Replicas therefore retain WAL segments that other nodes may need. After an absent node’s DCS member key expires, Patroni drops its slot after member_slots_ttl, which defaults to 30min. Adjust retention for your requirements.

For a fixed topology with stable node names, you can configure permanent physical slots named after the nodes. This prevents slot removal and WAL recycling while a replica is temporarily down:

slots:
  node_name1:
    type: physical
  node_name2:
    type: physical
  node_name3:
    type: physical
  ...
Warning

Permanent slots synchronize only from primary/standby_leader to replicas. Applications must therefore use them only on the leader. Using them on replicas causes indefinite pg_wal growth on all other nodes. Physical slots named after Patroni members are an exception. Patroni creates and synchronizes these slots across all nodes for member replication.

Warning

The nostream tag disables permanent logical slot copying and synchronization on a standby and all its cascading replicas.

3.2 - YAML Configuration Settings

Complete reference for Patroni YAML configuration options and sections.

Source: https://patroni.readthedocs.io/en/latest/yaml_configuration.html


Global/Universal

  • thread_pool_size: thread pool size for asynchronous tasks and REST API communication with other members during leader races or failsafe checks. Minimum: 5. Default: 5.
  • thread_stack_size: stack size for Patroni threads. Use a multiple of 64kB. Minimum: 64kB. Patroni default: 512kB.
  • name: the name of the host. Must be unique for the cluster. The value __patroni_strict_sync_replica_placeholder__ is reserved for internal use by Patroni and cannot be used as a node name.
  • namespace: path within the configuration store where Patroni will keep information about the cluster. Default value: “/service”
  • scope: cluster name


Log

  • type: sets the format of logs. Can be either plain or json. To use json format, you must have the jsonlogger installed. The default value is plain.
  • level: sets the general logging level. Default value is INFO (see the docs for Python logging)
  • traceback_level: sets the level where tracebacks will be visible. Default value is ERROR. Set it to DEBUG if you want to see tracebacks only if you enable log.level=DEBUG.
  • format: log format. For plain logs, use a string. For json, use a string or a list of LogRecord attributes. In lists, use field names without %( and ). To rename a field, use a dictionary with the original field as key and the output name as value. Default: %(asctime)s %(levelname)s: %(message)s.
  • dateformat: sets the datetime formatting string. (see the formatTime() documentation)
  • static_fields: add additional fields to the log. This option is only available when the log type is set to json.
  • max_queue_size: maximum internal log queue size. Patroni writes records to an in-memory queue. A separate thread reads them and writes to stderr or a file. The default 1000 records retain approximately 1h20m of logs.
  • dir: application log directory. It must exist and be writable by the Patroni user. By default, Patroni retains four 25MB files. Adjust retention with file_num and file_size.
  • mode: Permissions for log files (for example, 0644). If not specified, permissions will be set based on the current umask value.
  • file_num: The number of application logs to retain.
  • file_size: Size of patroni.log file (in bytes) that triggers a log rolling.
  • loggers: This section allows redefining logging level per python module
    • patroni.postmaster: WARNING
    • urllib3: DEBUG
  • deduplicate_heartbeat_logs: suppresses consecutive identical heartbeat messages when true. Default: false.
Warning

HA loop timing helps diagnose failovers caused by exhausted resources and similar problems. With deduplicate_heartbeat_logs set to true, loop execution produces no log unless the leader changes. These diagnostics are then unavailable in the logs.

For JSON logging, use this example:

log:
   type: json
   format:
      - message
      - module
      - asctime: '@timestamp'
      - levelname: level
   static_fields:
      app: patroni


Bootstrap configuration

Note

After initial cluster bootstrap, Patroni stores settings in the DCS. Later changes to YAML bootstrap.dcs have no effect. Use patronictl_edit_config or the REST API to change them.

  • bootstrap:
    • dcs: global dynamic cluster configuration. Put parameters from Dynamic Configuration settings under bootstrap.dcs. After bootstrap, Patroni writes this section to /<namespace>/<scope>/config in the configuration store.

    • method: custom script to use for bootstrapping this cluster.

      See custom bootstrap methods. Set method to initdb, or omit it, to use the default initdb command.

    • initdb: (optional) list options to be passed on to initdb.

      • - data-checksums: Must be enabled when pg_rewind is needed on 9.3.
      • - encoding: UTF8: default encoding for new databases.
      • - locale: UTF8: default locale for new databases.
    • post_bootstrap or post_init: script to run after cluster initialization. It receives a connection URL with the cluster superuser name. PGPASSFILE points to the pgpass file.


Citus

Enable Citus integration. Patroni then registers workers on the coordinator. See Citus support.

  • group: the Citus group id, integer. Use 0 for coordinator and 1, 2, etc… for workers
  • database: database for the citus extension. Use the same database on the coordinator and all workers. Currently, only one database is supported.


Consul

Most of the parameters are optional, but you have to specify one of the host or url

  • host: the host:port for the Consul local agent.
  • url: url for the Consul local agent, in format: http(s)://host:port.
  • port: (optional) Consul port.
  • scheme: (optional) http or https, defaults to http.
  • token: (optional) ACL token.
  • verify: (optional) whether to verify the SSL certificate for HTTPS requests.
  • cacert: (optional) The ca certificate. If present it will enable validation.
  • cert: (optional) file with the client certificate.
  • key: (optional) file with the client key. Can be empty if the key is part of cert.
  • dc: (optional) Datacenter to communicate with. By default the datacenter of the host is used.
  • consistency: (optional) Select consul consistency mode. Possible values are default, consistent, or stale (more details in consul API reference)
  • checks: (optional) list of Consul health checks used for the session. By default an empty list is used.
  • register_service: (optional) registers a service named by scope. Its role tag is master, primary, replica, or standby-leader. Default: false.
  • service_tags: (optional) additional static tags to add to the Consul service apart from the role (primary/replica/standby-leader). By default an empty list is used.
  • service_check_interval: (optional) how often to perform health check against registered url. Defaults to ‘5s’.
  • service_check_tls_server_name: (optional) override SNI host when connecting via TLS, see also consul agent check API reference.

The token needs to have the following ACL permissions:

service_prefix "${scope}" {
    policy = "write"
}
key_prefix "${namespace}/${scope}" {
    policy = "write"
}
session_prefix "" {
    policy = "write"
}

Etcd

Most of the parameters are optional, but you have to specify one of the host, hosts, url, proxy or srv

  • host: the host:port for the etcd endpoint.
  • hosts: list of etcd endpoint in format host1:port1,host2:port2,etc… Could be a comma separated string or an actual yaml list.
  • use_proxies: if true, treats hosts as proxies. Patroni does not discover etcd topology.
  • url: url for the etcd.
  • proxy: proxy url for the etcd. If you are connecting to the etcd using proxy, use this parameter instead of url.
  • srv: domain for SRV-based cluster discovery. Patroni queries these services in order until one succeeds: _etcd-client-ssl, _etcd-client, _etcd-ssl, _etcd, _etcd-server-ssl, _etcd-server. For _etcd-server-ssl or _etcd-server, it queries available members through the ETCD peer protocol. Otherwise, it uses hosts from the SRV records.
  • srv_suffix: suffix for discovery SRV names. Requires srv. Use it to distinguish etcd clusters in one domain. For example, srv_suffix: foo and srv: example.org produce _etcd-client-ssl-foo._tcp.example.com. Patroni applies this suffix to each possible ETCD SRV service name.
  • protocol: (optional) http or https, if not specified http is used. If the url or proxy is specified - will take protocol from them.
  • username: (optional) username for etcd authentication.
  • password: (optional) password for etcd authentication.
  • cacert: (optional) The ca certificate. If present it will enable validation.
  • cert: (optional) file with the client certificate.
  • key: (optional) file with the client key. Can be empty if the key is part of cert.

Etcdv3

To use Etcd protocol version 3, configure the etcd3 section. Its parameters are the same as etcd.

Warning

Protocol versions 2 and 3 cannot see each other’s keys. Changing Patroni configuration alone cannot migrate etcd to etcd3. Patroni uses the Etcd gRPC-gateway proxy for the V3 API. This prevents TLS common name authentication.


ZooKeeper

  • hosts: List of ZooKeeper cluster members in format: ′host1:port1′,′host2:port2′,′etc...′'host1:port1', 'host2:port2', 'etc...'.
  • use_ssl: (optional) Whether SSL is used or not. Defaults to false. If set to false, all SSL specific parameters are ignored.
  • cacert: (optional) The CA certificate. If present it will enable validation.
  • cert: (optional) File with the client certificate.
  • key: (optional) File with the client key.
  • key_password: (optional) The client key password.
  • verify: (optional) Whether to verify certificate or not. Defaults to true.
  • set_acls: (optional) default ACL that Kazoo applies to each new ZNode. Use x509 (default) or another supported ZooKeeper scheme, such as digest. Supply a dictionary: each key is the full principal, optionally prefixed with its scheme. Each value lists one or more permissions: CREATE, READ, WRITE, DELETE, ADMIN, or ALL. Example: set_acls: {CN=principal1: [CREATE, READ], digest:principal2:+pjROuBuuwNNSujKyH8dGcEnFPQ=: [ALL]}.
  • auth_data: (optional) connection authentication dictionary. Use scheme as the key and credential as the value. Default: empty dictionary.
Note

It is required to install kazoo>=2.6.0 to support SSL.


Exhibitor

  • hosts: initial list of Exhibitor (ZooKeeper) nodes in format: ‘host1,host2,etc…’. This list updates automatically whenever the Exhibitor (ZooKeeper) cluster topology changes.
  • poll_interval: how often the list of ZooKeeper and Exhibitor nodes should be updated from Exhibitor.
  • port: Exhibitor port.


Kubernetes

  • bypass_api_service: (optional) normally, Patroni contacts the kubernetes service at KUBERNETES_SERVICE_HOST. With bypass_api_service set to true, it discovers the API nodes behind the service and contacts them directly.
  • namespace: (optional) Kubernetes namespace where Patroni pod is running. Default value is default.
  • labels: labels in {label1: value1, label2: value2} format. Patroni uses them to find cluster Pods and Endpoints or ConfigMaps. It also adds them to each Endpoint or ConfigMap it creates.
  • scope_label: (optional) name of the label containing cluster name. Default value is cluster-name.
  • bootstrap_labels: (optional) labels in {label1: value1, label2: value2} format. Patroni assigns them to pods in these states: initializing new cluster, running custom bootstrap script, starting after custom bootstrap, or creating replica.
  • role_label: (optional) name of the label containing role (primary, replica, or other custom value). Patroni will set this label on the pod it runs in. Default value is role.
  • leader_label_value: (optional) value of the pod label when Postgres role is primary. Default value is primary.
  • follower_label_value: (optional) value of the pod label when Postgres role is replica. Default value is replica.
  • standby_leader_label_value: (optional) value of the pod label when Postgres role is standby_leader. Default value is primary.
  • tmp_role_label: (optional) name of the temporary label containing role (primary or replica). Value of this label will always use the default of corresponding role. Set only when necessary.
  • use_endpoints: (optional) if set to true, Patroni will use Endpoints instead of ConfigMaps to run leader elections and keep cluster state.
  • pod_ip: (optional) Patroni pod IP address. Required when use_endpoints is enabled. On promotion, Patroni uses this value to populate leader endpoint subsets.
  • ports: (optional) named Service ports require identical Endpoint port names. Otherwise, the service cannot work. For {Kind: Service, spec: {ports: [{name: postgresql, port: 5432, targetPort: 5432}]}}, set kubernetes.ports: [{"name": "postgresql", "port": 5432}]. Patroni uses this value to update leader Endpoint subsets. Applies only with kubernetes.use_endpoints.
  • cacert: (optional) CA_BUNDLE file with trusted CA certificates for Kubernetes API SSL verification. Defaults to the ServiceAccount secret value.
  • retriable_http_codes: (optional) Kubernetes API status codes to retry. By default, Patroni retries 500, 503, and 504, and responses with a retry-after HTTP header.


Raft (deprecated)

  • self_addr: ip:port to listen on for Raft connections. The self_addr must be accessible from other nodes of the cluster. If not set, the node will not participate in consensus.

  • bind_addr: (optional) ip:port to listen on for Raft connections. If not specified the self_addr will be used.

  • partner_addrs: list of other Patroni nodes in the cluster in format:

    ′ip1:port′,′ip2:port′,′etc...′'ip1:port', 'ip2:port', 'etc...'
  • data_dir: directory where to store Raft log and snapshot. If not specified the current working directory is used.

  • password: (optional) Encrypt Raft traffic with a specified password, requires cryptography python module.

  • min_timeout: (optional) minimum election timeout in seconds for the underlying pysyncobj Raft implementation. Must be greater than 3 * append_entries_period. Default: 0.4.

  • max_timeout: (optional) maximum election timeout in seconds for the underlying pysyncobj Raft implementation. Must be greater than min_timeout. Default: 1.4.

  • connection_timeout: (optional) time in seconds after which a connection with no data received is considered dead. Must be greater than or equal to max_timeout. Default: 3.5.

  • append_entries_period: (optional) interval in seconds for sending heartbeat (append_entries) commands. Must be less than one-third of min_timeout. Default: 0.1.

  • connection_retry_time: (optional) interval in seconds between reconnection attempts to offline nodes. Default: 5.0.

  • leader_fallback_timeout: (optional) time in seconds after which a leader with no response from the majority falls back to follower state. Must be greater than append_entries_period. Default: 30.0.

Note

Adjust these timeouts for high-latency networks where pysyncobj defaults are too short. Required constraints: min_timeout > 3 * append_entries_period, max_timeout > min_timeout, connection_timeout >= max_timeout, and leader_fallback_timeout > append_entries_period. Patroni validates them at startup and refuses to start if they fail. Changes require a restart.

[!WARNING] These settings only extend pysyncobj election and connection timeouts. Each Raft command, including leader lock refresh and cluster-state writes, must still finish within retry_timeout (default 10). With round-trip latency above approximately a few seconds, a command can exceed this limit even if connection_timeout exceeds the RTT. The DCS then appears unreachable, and the primary may demote. Also increase retry_timeout and ttl on these links. Keep loop_wait + 2 * retry_timeout <= ttl.

Short FAQ about Raft implementation

  • Q: How to list all the nodes providing consensus?

    A: syncobj_admin -conn host:port -status where the host:port is the address of one of the cluster nodes

  • Q: Node that was a part of consensus and has gone and I can’t reuse the same IP for other node. How to remove this node from the consensus?

    A: syncobj_admin -conn host:port -remove host2:port2 where the host2:port2 is the address of the node you want to remove from consensus.

  • Q: Where to get the syncobj_admin utility?

    A: It is installed together with pysyncobj module (python RAFT implementation), which is Patroni dependency.

  • Q: it is possible to run Patroni node without adding in to the consensus?

    A: Yes, just comment out or remove raft.self_addr from Patroni configuration.

  • Q: It is possible to run Patroni and PostgreSQL only on two nodes?

    A: Yes, on the third node you can run patroni_raft_controller (without Patroni and PostgreSQL). In such a setup, one can temporarily lose one node without affecting the primary.


PostgreSQL

  • postgresql:
    • authentication:

      • superuser:
        • username: name for the superuser, set during initialization (initdb) and later used by Patroni to connect to the postgres.
        • password: password for the superuser, set during initialization (initdb).
        • sslmode: (optional) maps to sslmode. Specifies the TLS negotiation mode. See the PostgreSQL documentation for each mode. Default: prefer.
        • sslkey: (optional) maps to sslkey. Path to the secret key for the client certificate.
        • sslpassword: (optional) maps to sslpassword. Password for the secret key in sslkey.
        • sslcert: (optional) maps to sslcert. Path to the client certificate.
        • sslrootcert: (optional) maps to sslrootcert. File containing one or more trusted CA certificates. The client uses them to verify the server certificate.
        • sslcrl: (optional) maps to sslcrl. Certificate revocation list file. The client rejects servers whose certificates appear in the list.
        • sslcrldir: (optional) maps to sslcrldir. Directory containing certificate revocation list files. The client rejects servers whose certificates appear in these lists.
        • sslnegotiation: (optional) maps to sslnegotiation. Controls server SSL negotiation when SSL is used.
        • gssencmode: (optional) maps to gssencmode. Controls whether to negotiate secure GSS TCP/IP and its priority.
        • channel_binding: (optional) maps to channel_binding. Controls client channel binding.
      • replication:
        • username: replication username; the user will be created during initialization. Replicas will use this user to access the replication source via streaming replication
        • password: replication password; the user will be created during initialization.
        • sslmode: (optional) maps to sslmode. Specifies the TLS negotiation mode. See the PostgreSQL documentation for each mode. Default: prefer.
        • sslkey: (optional) maps to sslkey. Path to the secret key for the client certificate.
        • sslpassword: (optional) maps to sslpassword. Password for the secret key in sslkey.
        • sslcert: (optional) maps to sslcert. Path to the client certificate.
        • sslrootcert: (optional) maps to sslrootcert. File containing one or more trusted CA certificates. The client uses them to verify the server certificate.
        • sslcrl: (optional) maps to sslcrl. Certificate revocation list file. The client rejects servers whose certificates appear in the list.
        • sslcrldir: (optional) maps to sslcrldir. Directory containing certificate revocation list files. The client rejects servers whose certificates appear in these lists.
        • sslnegotiation: (optional) maps to sslnegotiation. Controls server SSL negotiation when SSL is used.
        • gssencmode: (optional) maps to gssencmode. Controls whether to negotiate secure GSS TCP/IP and its priority.
        • channel_binding: (optional) maps to channel_binding. Controls client channel binding.
      • rewind:
        • username: (optional) name for the user for pg_rewind; the user will be created during initialization of postgres 11+ and all necessary permissions will be granted.
        • password: (optional) password for the user for pg_rewind; the user will be created during initialization.
        • sslmode: (optional) maps to sslmode. Specifies the TLS negotiation mode. See the PostgreSQL documentation for each mode. Default: prefer.
        • sslkey: (optional) maps to sslkey. Path to the secret key for the client certificate.
        • sslpassword: (optional) maps to sslpassword. Password for the secret key in sslkey.
        • sslcert: (optional) maps to sslcert. Path to the client certificate.
        • sslrootcert: (optional) maps to sslrootcert. File containing one or more trusted CA certificates. The client uses them to verify the server certificate.
        • sslcrl: (optional) maps to sslcrl. Certificate revocation list file. The client rejects servers whose certificates appear in the list.
        • sslcrldir: (optional) maps to sslcrldir. Directory containing certificate revocation list files. The client rejects servers whose certificates appear in these lists.
        • sslnegotiation: (optional) maps to sslnegotiation. Controls server SSL negotiation when SSL is used.
        • gssencmode: (optional) maps to gssencmode. Controls whether to negotiate secure GSS TCP/IP and its priority.
        • channel_binding: (optional) maps to channel_binding. Controls client channel binding.
    • callbacks: callback scripts to run on certain actions. Patroni will pass the action, role and cluster name. (See scripts/aws.py as an example of how to write them.)

      • on_reload: run this script when configuration reload is triggered.
      • on_restart: run this script when the postgres restarts (without changing role).
      • on_role_change: run this script when the postgres is being promoted or demoted.
      • on_start: run this script when the postgres starts.
      • on_stop: run this script when the postgres stops.
    • connect_address: IP address + port through which Postgres is accessible from other nodes and applications.

    • proxy_address: address and port of the connection pool beside Postgres, such as pgbouncer. Patroni stores it as proxy_url in the DCS member key for service discovery.

    • create_replica_methods: ordered methods for creating replicas. The default is “basebackup”. Other methods refer to scripts, each with its own configuration section. See custom replica creation methods.

    • data_dir: The location of the Postgres data directory, either existing or to be initialized by Patroni.

    • config_dir: The location of the Postgres configuration directory, defaults to the data directory. Must be writable by Patroni.

    • bin_dir: (optional) Path to PostgreSQL binaries (pg_ctl, initdb, pg_controldata, pg_basebackup, postgres, pg_isready, pg_rewind). If not provided or is an empty string, PATH environment variable will be used to find the executables.

    • bin_name: (optional) Make it possible to override Postgres binary names, if you are using a custom Postgres distribution:

      • pg_ctl: (optional) Custom name for pg_ctl binary.
      • initdb: (optional) Custom name for initdb binary.
      • pgcontroldata: (optional) Custom name for pg_controldata binary.
      • pg_basebackup: (optional) Custom name for pg_basebackup binary.
      • postgres: (optional) Custom name for postgres binary.
      • pg_isready: (optional) Custom name for pg_isready binary.
      • pg_rewind: (optional) Custom name for pg_rewind binary.
    • listen: Postgres listen addresses and port. With streaming replication, other cluster nodes must be able to reach this address. Separate multiple addresses with commas and append the port after the last address: listen: 127.0.0.1,127.0.0.2:5432. Patroni uses the first address for local connections.

    • use_unix_socket: prefer Unix sockets for cluster connections. Default: false. If unix_socket_directories is set, use its first suitable value, or TCP if none is suitable. If absent from postgresql.parameters, assume the default socket directory and omit host from connection parameters.

    • use_unix_socket_repl: prefer Unix sockets for replication user connections. Default: false. If unix_socket_directories is set, use its first suitable value, or TCP if none is suitable. If absent from postgresql.parameters, assume the default socket directory and omit host from connection parameters.

    • pgpass: path to the .pgpass password file. Patroni creates this file before executing pg_basebackup, the post_init script and under some other circumstances. The location must be writable by Patroni.

    • recovery_conf: additional configuration settings written to recovery.conf when configuring follower.

    • custom_conf : optional custom postgresql.conf file to use instead of postgresql.base.conf. It must exist on all nodes and be readable by PostgreSQL. The actual postgresql.conf includes it from its location. Patroni neither monitors nor backs up this file. Patroni configuration can still override its settings; see dynamic configuration.

    • parameters: configuration parameters (GUCs) for Postgres in format {ssl: "on", ssl_cert_file: "cert_file"}.

    • parameters_primary: (optional) role-specific parameter overrides for primary. These values are merged with and override the base parameters.

    • parameters_replica: (optional) role-specific parameter overrides for replica. These values are merged with and override the base parameters.

    • parameters_standby_leader: (optional) role-specific parameter overrides for standby_leader. These values are merged with and override the base parameters.

    • pg_hba: list of lines that Patroni will use to generate pg_hba.conf. Patroni ignores this parameter if hba_file PostgreSQL parameter is set to a non-default value. Together with dynamic configuration this parameter simplifies management of pg_hba.conf.

      • - host all all 0.0.0.0/0 md5
      • - host replication replicator 127.0.0.1/32 md5: A line like this is required for replication.
    • pg_hba_primary: (optional) role-specific pg_hba entries for primary. These completely replace pg_hba (no merging). If not defined, pg_hba is used.

    • pg_hba_replica: (optional) role-specific pg_hba entries for replica. These completely replace pg_hba (no merging). If not defined, pg_hba is used.

    • pg_hba_standby_leader: (optional) role-specific pg_hba entries for standby_leader. These completely replace pg_hba (no merging). If not defined, pg_hba is used.

    • pg_ident: list of lines that Patroni will use to generate pg_ident.conf. Patroni ignores this parameter if ident_file PostgreSQL parameter is set to a non-default value. Together with dynamic configuration this parameter simplifies management of pg_ident.conf.

      • - mapname1 systemname1 pguser1
      • - mapname1 systemname2 pguser2
    • pg_ident_primary: (optional) role-specific pg_ident entries for primary. These completely replace pg_ident (no merging). If not defined, pg_ident is used.

    • pg_ident_replica: (optional) role-specific pg_ident entries for replica. These completely replace pg_ident (no merging). If not defined, pg_ident is used.

    • pg_ident_standby_leader: (optional) role-specific pg_ident entries for standby_leader. These completely replace pg_ident (no merging). If not defined, pg_ident is used.

    • pg_ctl_timeout: How long should pg_ctl wait when doing start, stop or restart. Default value is 60 seconds.

    • use_pg_rewind: try pg_rewind when the old leader rejoins as a replica. For correct operation, pg_rewind requires data page checksums and/or wal_log_hints set to on. Enable checksums with the --data-checksums option for initdb.

    • rewind: (optional) custom options to pass to the pg_rewind command. Can be specified as a list of strings and/or single key-value dictionaries. Not allowed options include: target-pgdata, source-pgdata, source-server, write-recovery-conf, dry-run, restore-target-wal, config-file, no-ensure-shutdown, version, and help. Example usage:

      postgresql:
        rewind:
          - debug
          - progress
          - sync-method: fsync
    • remove_data_directory_on_rewind_failure: If this option is enabled, Patroni will remove the PostgreSQL data directory and recreate the replica. Otherwise it will try to follow the new leader. Default value is false.

    • remove_data_directory_on_diverged_timelines: remove the data directory and recreate the replica if timelines diverge and the old primary cannot stream from the new primary. Use this when pg_rewind is unavailable. On PostgreSQL v10 and older, Patroni checks divergence by connecting to the “postgres” database with replication credentials. Permit this access in pg_hba.conf. Default: false.

    • replica_method: add a section for each create_replica_methods entry other than basebackup. Use the method name as the section name. At minimum, set “command” to the full script path. Patroni passes other parameters to the script as “parameter=value”.

    • pre_promote: fencing script run after leader lock acquisition and before replica promotion during failover. A non-zero exit prevents promotion and removes the DCS leader key.

    • before_stop: script run immediately before Postgres stops. It runs synchronously and blocks shutdown until completion. Shutdown then proceeds regardless of its exit code.


REST API

  • restapi:
    • thread_pool_size: size of thread pool used by Patroni to process REST API requests. Minimal value is 5, default value is 5.
    • connect_address: address or host name and port for the REST API. Every cluster member must reach it. Use a non-loopback address except for a local demonstration; “localhost” and “127.0.0.1” are unsuitable for other deployments. It supports HTTP health checks, user queries, and member checks during leader elections. These checks determine whether the leader runs or another node has a later WAL position. Patroni stores connect_address in the DCS member key so member names resolve to REST API addresses.
    • listen: address or host name and port for REST API health checks and communication between cluster members. HAProxy and other load balancers can use HTTP “OPTION” or “GET” checks.
    • authentication: (optional)
      • username: Basic-auth username to protect unsafe REST API endpoints.
      • password: Basic-auth password to protect unsafe REST API endpoints.
    • certfile: (optional): Specifies the file with the certificate in the PEM format. If the certfile is not specified or is left empty, the API server will work without SSL.
    • keyfile: (optional): Specifies the file with the secret key in the PEM format.
    • keyfile_password: (optional): Specifies a password for decrypting the keyfile.
    • cafile: (optional): Specifies the file with the CA_BUNDLE with certificates of trusted CAs to use while verifying client certs.
    • ciphers: (optional): Specifies the permitted cipher suites (e.g. “ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:!SSLv1:!SSLv2:!SSLv3:!TLSv1:!TLSv1.1”)
    • verify_client: (optional) client certificate verification mode: none (default), optional, or required. none disables verification. required requires certificates for all calls; successful signature verification authenticates the client. optional requires and checks certificates only for unsafe PUT, POST, PATCH, and DELETE requests.
    • allowlist: (optional) hosts permitted to call unsafe endpoints. Each entry can be a host name, IP address, or CIDR network. Default: allow all. With allowlist or allowlist_include_members set, all unlisted sources are rejected.
    • allowlist_include_members: (optional) if true, permits unsafe endpoint access from cluster members registered in the DCS. It uses each member’s api_url host name or IP address. The operating system may use a different address for outgoing connections.
    • http_extra_headers: (optional): HTTP headers let the REST API server pass additional information with an HTTP response.
    • https_extra_headers: (optional): HTTPS headers let the REST API server pass additional information with an HTTP response when TLS is enabled. This will also pass additional information set in http_extra_headers.
    • request_queue_size: (optional): Sets request queue size for TCP socket used by Patroni REST API. Once the queue is full, further requests get a “Connection denied” error. The default value is 5.
    • server_tokens: (optional): Configures the value of the Server HTTP header.
      • Minimal: The header will contain only the Patroni version, e.g. Patroni/4.0.0.
      • ProductOnly: The header will contain only the product name, e.g. Patroni.
      • Original (default): The header will expose the original behaviour and display the BaseHTTP and Python versions, e.g. BaseHTTP/0.6 Python/3.12.3.

Here is an example of both http_extra_headers and https_extra_headers:

restapi:
  listen: <listen>
  connect_address: <connect_address>
  authentication:
    username: <username>
    password: <password>
  http_extra_headers:
    'X-Frame-Options': 'SAMEORIGIN'
    'X-XSS-Protection': '1; mode=block'
    'X-Content-Type-Options': 'nosniff'
  cafile: <ca file>
  certfile: <cert>
  keyfile: <key>
  https_extra_headers:
    'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'

Warning

  • The restapi.connect_address must be accessible from all nodes of a given Patroni cluster. Internally Patroni is using it during the leader race to find nodes with minimal replication lag.
  • If you enabled client certificates validation (restapi.verify_client is set to required), you also must provide valid client certificates in the ctl.certfile, ctl.keyfile, ctl.keyfile_password. If not provided, Patroni will not work correctly.


CTL

  • ctl: (optional)
    • authentication:
      • username: Basic-auth username for accessing protected REST API endpoints. If not provided patronictl will use the value provided for REST API “username” parameter.
      • password: Basic-auth password for accessing protected REST API endpoints. If not provided patronictl will use the value provided for REST API “password” parameter.
    • insecure: Allow connections to REST API without verifying SSL certs.
    • cacert: CA_BUNDLE file or directory with trusted CAs for REST API SSL verification. If absent, patronictl uses the REST API “cafile” value.
    • certfile: Specifies the file with the client certificate in the PEM format.
    • keyfile: Specifies the file with the client secret key in the PEM format.
    • keyfile_password: Specifies a password for decrypting the client keyfile.

Watchdog

  • mode: off, automatic, or required. off disables the watchdog. automatic uses it when available and otherwise ignores it. required prevents leadership unless watchdog activation succeeds.
  • device: Path to watchdog device. Defaults to /dev/watchdog.
  • safety_margin: Number of seconds of safety margin between watchdog triggering and leader key expiration.


Tags

  • clonefrom: true or false. If true, other nodes may prefer this node as their bootstrap pg_basebackup source. With multiple nodes tagged clonefrom, selection is random. Default: false.
  • noloadbalance: true or false. If set to true the node will return HTTP Status Code 503 for the GET /replica REST API health-check and therefore will be excluded from the load-balancing. Defaults to false.
  • replicatefrom: The name of another replica to replicate from. Used to support cascading replication.
  • nosync: true or false. If set to true the node will never be selected as a synchronous replica.
  • sync_priority: integer priority for synchronous standby selection with synchronous_mode set to on. Higher values are preferred. Values of 0 or less exclude the node from synchronous_standby_names, like nosync: true. This is the opposite of sync_priority in pg_stat_replication.
  • nofailover: true or false, controls whether this node is allowed to participate in the leader race and become a leader. Defaults to false, meaning this node can_ participate in leader races.
  • failover_priority: integer failover priority. Higher values are preferred when nodes have received/replayed the same WAL amount. A higher receive/replay LSN takes precedence over priority. Values of 0 or less prevent leader election participation and promotion, like nofailover: true. Currently, failover_priority does not work with quorum-based synchronous replication.
  • nostream: true or false. If true, disable WAL streaming through the replication protocol. Use archive recovery, if restore_command is configured, and pg_wal/pg_xlog polling instead. Also disable permanent logical slot copying and synchronization on this node and its cascading replicas. This tag has no effect on a primary.
Warning

Provide only one of nofailover or failover_priority. Providing nofailover: true is the same as failover_priority: 0, and providing nofailover: false will give the node priority 1.

In addition to these predefined tags, you can also add your own ones:

  • key1: true
  • key2: false
  • key3: 1.4
  • key4: "RandomString"

Tags appear in the REST API and patronictl_list. Use them in instance health checks. An undefined tag or a value different from the query value returns HTTP 503.

3.3 - Environment Configuration Settings

Environment variables for overriding Patroni configuration parameters.

Source: https://patroni.readthedocs.io/en/latest/ENVIRONMENT.html

System environment variables can override some Patroni configuration file parameters. This page lists all supported variables. Environment values always take precedence over file values.


Global/Universal

  • PATRONI_CONFIGURATION: sets the complete Patroni configuration through PATRONI_CONFIGURATION. Patroni then ignores all other environment variables.
  • PATRONI_THREAD_POOL_SIZE: thread pool size for asynchronous tasks and REST API communication with other members during leader races or failsafe checks. Minimum: 5. Default: 5.
  • PATRONI_THREAD_STACK_SIZE: stack size for Patroni threads. Use a multiple of 64kB. Minimum: 64kB. Patroni default: 512kB.
  • PATRONI_NAME: name of the node where the current instance of Patroni is running. Must be unique for the cluster. The value __patroni_strict_sync_replica_placeholder__ is reserved for internal use by Patroni and cannot be used as a node name.
  • PATRONI_NAMESPACE: path within the configuration store where Patroni will keep information about the cluster. Default value: “/service”
  • PATRONI_SCOPE: cluster name
  • PG_MALLOC_ARENA_MAX: custom value for MALLOC_ARENA_MAX environment variable for postmaster process. If not set, postmaster will inherit MALLOC_ARENA_MAX value.

Log

  • PATRONI_LOG_TYPE: sets the format of logs. Can be either plain or json. To use json format, you must have the jsonlogger installed. The default value is plain.
  • PATRONI_LOG_LEVEL: sets the general logging level. Default value is INFO (see the docs for Python logging)
  • PATRONI_LOG_TRACEBACK_LEVEL: sets the level where tracebacks will be visible. Default value is ERROR. Set it to DEBUG if you want to see tracebacks only if you enable PATRONI_LOG_LEVEL=DEBUG.
  • PATRONI_LOG_FORMAT: log format. For plain logs, use a string. For json, use a string or a list of LogRecord attributes. In lists, use field names without %( and ). To rename a field, use a dictionary with the original field as key and the output name as value. Default: %(asctime)s %(levelname)s: %(message)s.
  • PATRONI_LOG_DATEFORMAT: sets the datetime formatting string. (see the formatTime() documentation)
  • PATRONI_LOG_STATIC_FIELDS: add additional fields to the log. This option is only available when the log type is set to json. Example PATRONI_LOG_STATIC_FIELDS="{app: patroni}"
  • PATRONI_LOG_MAX_QUEUE_SIZE: maximum internal log queue size. Patroni writes records to an in-memory queue. A separate thread reads them and writes to stderr or a file. The default 1000 records retain approximately 1h20m of logs.
  • PATRONI_LOG_DIR: application log directory. It must exist and be writable by the Patroni user. By default, Patroni retains four 25MB files. Adjust retention with PATRONI_LOG_FILE_NUM and PATRONI_LOG_FILE_SIZE.
  • PATRONI_LOG_MODE: Permissions for log files (for example, 0644). If not specified, permissions will be set based on the current umask value.
  • PATRONI_LOG_FILE_NUM: The number of application logs to retain.
  • PATRONI_LOG_FILE_SIZE: Size of patroni.log file (in bytes) that triggers a log rolling.
  • PATRONI_LOG_LOGGERS: Redefine logging level per python module. Example PATRONI_LOG_LOGGERS="{patroni.postmaster: WARNING, urllib3: DEBUG}"
  • PATRONI_LOG_DEDUPLICATE_HEARTBEAT_LOGS: suppresses consecutive identical heartbeat messages when true. Default: false.
Warning

HA loop timing helps diagnose failovers caused by exhausted resources and similar problems. With PATRONI_LOG_DEDUPLICATE_HEARTBEAT_LOGS set to true, loop execution produces no log unless the leader changes. These diagnostics are then unavailable in the logs.


Citus

Enable Citus integration. Patroni then registers workers on the coordinator. See Citus support.

  • PATRONI_CITUS_GROUP: the Citus group id, integer. Use 0 for coordinator and 1, 2, etc… for workers
  • PATRONI_CITUS_DATABASE: database for the citus extension. Use the same database on the coordinator and all workers. Currently, only one database is supported.

Consul

  • PATRONI_CONSUL_HOST: the host:port for the Consul local agent.
  • PATRONI_CONSUL_URL: url for the Consul local agent, in format: http(s)://host:port
  • PATRONI_CONSUL_PORT: (optional) Consul port
  • PATRONI_CONSUL_SCHEME: (optional) http or https, defaults to http
  • PATRONI_CONSUL_TOKEN: (optional) ACL token
  • PATRONI_CONSUL_VERIFY: (optional) whether to verify the SSL certificate for HTTPS requests
  • PATRONI_CONSUL_CACERT: (optional) The ca certificate. If present it will enable validation.
  • PATRONI_CONSUL_CERT: (optional) File with the client certificate
  • PATRONI_CONSUL_KEY: (optional) File with the client key. Can be empty if the key is part of certificate.
  • PATRONI_CONSUL_DC: (optional) Datacenter to communicate with. By default the datacenter of the host is used.
  • PATRONI_CONSUL_CONSISTENCY: (optional) Select consul consistency mode. Possible values are default, consistent, or stale (more details in consul API reference)
  • PATRONI_CONSUL_CHECKS: (optional) list of Consul health checks used for the session. By default an empty list is used.
  • PATRONI_CONSUL_REGISTER_SERVICE: (optional) registers a service named by scope. Its role tag is master, primary, replica, or standby-leader. Default: false.
  • PATRONI_CONSUL_SERVICE_TAGS: (optional) additional static tags to add to the Consul service apart from the role (primary/replica/standby-leader). By default an empty list is used.
  • PATRONI_CONSUL_SERVICE_CHECK_INTERVAL: (optional) how often to perform health check against registered url
  • PATRONI_CONSUL_SERVICE_CHECK_TLS_SERVER_NAME: (optional) override SNI host when connecting via TLS, see also consul agent check API reference.

Etcd

  • PATRONI_ETCD_PROXY: proxy url for the etcd. If you are connecting to the etcd using proxy, use this parameter instead of PATRONI_ETCD_URL
  • PATRONI_ETCD_URL: url for the etcd, in format: http(s)://(username:password@)host:port
  • PATRONI_ETCD_HOSTS: list of etcd endpoints in format ‘host1:port1’,‘host2:port2’,etc…
  • PATRONI_ETCD_USE_PROXIES: if true, treats hosts as a fixed proxy list. Patroni does not discover etcd topology.
  • PATRONI_ETCD_PROTOCOL: http or https, if not specified http is used. If the url or proxy is specified - will take protocol from them.
  • PATRONI_ETCD_HOST: the host:port for the etcd endpoint.
  • PATRONI_ETCD_SRV: domain for SRV-based cluster discovery. Patroni queries these services in order until one succeeds: _etcd-client-ssl, _etcd-client, _etcd-ssl, _etcd, _etcd-server-ssl, _etcd-server. For _etcd-server-ssl or _etcd-server, it queries available members through the ETCD peer protocol. Otherwise, it uses hosts from the SRV records.
  • PATRONI_ETCD_SRV_SUFFIX: suffix for discovery SRV names. Requires PATRONI_ETCD_SRV. Use it to distinguish etcd clusters in one domain. For example, PATRONI_ETCD_SRV_SUFFIX=foo and PATRONI_ETCD_SRV=example.org produce _etcd-client-ssl-foo._tcp.example.com. Patroni applies this suffix to each possible ETCD SRV service name.
  • PATRONI_ETCD_USERNAME: username for etcd authentication.
  • PATRONI_ETCD_PASSWORD: password for etcd authentication.
  • PATRONI_ETCD_CACERT: The ca certificate. If present it will enable validation.
  • PATRONI_ETCD_CERT: File with the client certificate.
  • PATRONI_ETCD_KEY: File with the client key. Can be empty if the key is part of certificate.

Etcdv3

For Etcdv3, replace ETCD with ETCD3 in Etcd variable names. Examples include PATRONI_ETCD3_HOST and PATRONI_ETCD3_CACERT.

Warning

Protocol versions 2 and 3 cannot see each other’s keys. Changing Patroni configuration alone cannot migrate Etcd to Etcdv3. Patroni uses the Etcd gRPC-gateway proxy for the V3 API. This prevents TLS common name authentication.


ZooKeeper

  • PATRONI_ZOOKEEPER_HOSTS: Comma separated list of ZooKeeper cluster members: “‘host1:port1’,‘host2:port2’,’etc…’”. It is important to quote every single entity!
  • PATRONI_ZOOKEEPER_USE_SSL: (optional) Whether SSL is used or not. Defaults to false. If set to false, all SSL specific parameters are ignored.
  • PATRONI_ZOOKEEPER_CACERT: (optional) The CA certificate. If present it will enable validation.
  • PATRONI_ZOOKEEPER_CERT: (optional) File with the client certificate.
  • PATRONI_ZOOKEEPER_KEY: (optional) File with the client key.
  • PATRONI_ZOOKEEPER_KEY_PASSWORD: (optional) The client key password.
  • PATRONI_ZOOKEEPER_VERIFY: (optional) Whether to verify certificate or not. Defaults to true.
  • PATRONI_ZOOKEEPER_SET_ACLS: (optional) default ACL that Kazoo applies to each new ZNode. Use x509 (default) or another supported ZooKeeper scheme, such as digest. Supply a dictionary: each key is the full principal, optionally prefixed with its scheme. Each value lists one or more permissions: CREATE, READ, WRITE, DELETE, ADMIN, or ALL. Example: set_acls: {CN=principal1: [CREATE, READ], digest:principal2:+pjROuBuuwNNSujKyH8dGcEnFPQ=: [ALL]}.
  • PATRONI_ZOOKEEPER_AUTH_DATA: (optional) connection authentication dictionary. Use scheme as the key and credential as the value. Default: empty dictionary.
Note

It is required to install kazoo>=2.6.0 to support SSL.


Exhibitor

  • PATRONI_EXHIBITOR_HOSTS: initial list of Exhibitor (ZooKeeper) nodes in format: ‘host1,host2,etc…’. This list updates automatically whenever the Exhibitor (ZooKeeper) cluster topology changes.
  • PATRONI_EXHIBITOR_PORT: Exhibitor port.


Kubernetes

  • PATRONI_KUBERNETES_BYPASS_API_SERVICE: (optional) normally, Patroni contacts the kubernetes service at KUBERNETES_SERVICE_HOST. With PATRONI_KUBERNETES_BYPASS_API_SERVICE set to true, it discovers the API nodes behind the service and contacts them directly.
  • PATRONI_KUBERNETES_NAMESPACE: (optional) Kubernetes namespace where the Patroni pod is running. Default value is default.
  • PATRONI_KUBERNETES_LABELS: labels in {label1: value1, label2: value2} format. Patroni uses them to find cluster Pods and Endpoints or ConfigMaps. It also adds them to each Endpoint or ConfigMap it creates.
  • PATRONI_KUBERNETES_SCOPE_LABEL: (optional) name of the label containing cluster name. Default value is cluster-name.
  • PATRONI_KUBERNETES_BOOTSTRAP_LABELS: (optional) labels in {label1: value1, label2: value2} format. Patroni assigns them to pods in these states: initializing new cluster, running custom bootstrap script, starting after custom bootstrap, or creating replica.
  • PATRONI_KUBERNETES_ROLE_LABEL: (optional) name of the label containing role (primary, replica or other custom value). Patroni will set this label on the pod it runs in. Default value is role.
  • PATRONI_KUBERNETES_LEADER_LABEL_VALUE: (optional) value of the pod label when Postgres role is primary. Default value is primary.
  • PATRONI_KUBERNETES_FOLLOWER_LABEL_VALUE: (optional) value of the pod label when Postgres role is replica. Default value is replica.
  • PATRONI_KUBERNETES_STANDBY_LEADER_LABEL_VALUE: (optional) value of the pod label when Postgres role is standby_leader. Default value is primary.
  • PATRONI_KUBERNETES_TMP_ROLE_LABEL: (optional) name of the temporary label containing role (primary or replica). Value of this label will always use the default of corresponding role. Set only when necessary.
  • PATRONI_KUBERNETES_USE_ENDPOINTS: (optional) if set to true, Patroni will use Endpoints instead of ConfigMaps to run leader elections and keep cluster state.
  • PATRONI_KUBERNETES_POD_IP: (optional) Patroni pod IP address. Required when PATRONI_KUBERNETES_USE_ENDPOINTS is enabled. On promotion, Patroni uses this value to populate leader endpoint subsets.
  • PATRONI_KUBERNETES_PORTS: (optional) named Service ports require identical Endpoint port names. Otherwise, the service cannot work. For {Kind: Service, spec: {ports: [{name: postgresql, port: 5432, targetPort: 5432}]}}, set PATRONI_KUBERNETES_PORTS='[{"name": "postgresql", "port": 5432}]'. Patroni uses this value to update leader Endpoint subsets. Applies only with PATRONI_KUBERNETES_USE_ENDPOINTS.
  • PATRONI_KUBERNETES_CACERT: (optional) CA_BUNDLE file with trusted CA certificates for Kubernetes API SSL verification. Defaults to the ServiceAccount secret value.
  • PATRONI_RETRIABLE_HTTP_CODES: (optional) Kubernetes API status codes to retry. By default, Patroni retries 500, 503, and 504, and responses with a retry-after HTTP header.

Raft (deprecated)

  • PATRONI_RAFT_SELF_ADDR: ip:port to listen on for Raft connections. The self_addr must be accessible from other nodes of the cluster. If not set, the node will not participate in consensus.
  • PATRONI_RAFT_BIND_ADDR: (optional) ip:port to listen on for Raft connections. If not specified the self_addr will be used.
  • PATRONI_RAFT_PARTNER_ADDRS: list of other Patroni nodes in the cluster in format "'ip1:port1','ip2:port2'". It is important to quote every single entity!
  • PATRONI_RAFT_DATA_DIR: directory where to store Raft log and snapshot. If not specified the current working directory is used.
  • PATRONI_RAFT_PASSWORD: (optional) Encrypt Raft traffic with a specified password, requires cryptography python module.
  • PATRONI_RAFT_MIN_TIMEOUT: (optional) minimum election timeout in seconds for the underlying pysyncobj Raft implementation. Must be greater than 3 * PATRONI_RAFT_APPEND_ENTRIES_PERIOD. Default: 0.4.
  • PATRONI_RAFT_MAX_TIMEOUT: (optional) maximum election timeout in seconds for the underlying pysyncobj Raft implementation. Must be greater than PATRONI_RAFT_MIN_TIMEOUT. Default: 1.4.
  • PATRONI_RAFT_CONNECTION_TIMEOUT: (optional) time in seconds after which a connection with no data received is considered dead. Must be greater than or equal to PATRONI_RAFT_MAX_TIMEOUT. Default: 3.5.
  • PATRONI_RAFT_APPEND_ENTRIES_PERIOD: (optional) interval in seconds for sending heartbeat commands. Must be less than one-third of PATRONI_RAFT_MIN_TIMEOUT. Default: 0.1.
  • PATRONI_RAFT_CONNECTION_RETRY_TIME: (optional) interval in seconds between reconnection attempts to offline nodes. Default: 5.0.
  • PATRONI_RAFT_LEADER_FALLBACK_TIMEOUT: (optional) time in seconds after which a leader with no response from the majority falls back to follower state. Must be greater than PATRONI_RAFT_APPEND_ENTRIES_PERIOD. Default: 30.0.
Note

Patroni validates these constraints at startup and will refuse to start if they are violated. These values cannot be changed at runtime and require a restart. See Raft settings for details, including the high-latency limitation.


PostgreSQL

  • PATRONI_POSTGRESQL_LISTEN: Postgres listen addresses and port. Separate multiple addresses with commas and append the port after the last address: listen: 127.0.0.1,127.0.0.2:5432. Patroni uses the first address for local PostgreSQL connections.
  • PATRONI_POSTGRESQL_CONNECT_ADDRESS: IP address + port through which Postgres is accessible from other nodes and applications.
  • PATRONI_POSTGRESQL_PROXY_ADDRESS: address and port of the connection pool beside Postgres, such as pgbouncer. Patroni stores it as proxy_url in the DCS member key for service discovery.
  • PATRONI_POSTGRESQL_DATA_DIR: The location of the Postgres data directory, either existing or to be initialized by Patroni.
  • PATRONI_POSTGRESQL_CONFIG_DIR: The location of the Postgres configuration directory, defaults to the data directory. Must be writable by Patroni.
  • PATRONI_POSTGRESQL_BIN_DIR: PostgreSQL binary directory: pg_ctl, initdb, pg_controldata, pg_basebackup, postgres, pg_isready, and pg_rewind. The default empty string uses PATH to find executables.
  • PATRONI_POSTGRESQL_BIN_PG_CTL: (optional) Custom name for pg_ctl binary.
  • PATRONI_POSTGRESQL_BIN_INITDB: (optional) Custom name for initdb binary.
  • PATRONI_POSTGRESQL_BIN_PG_CONTROLDATA: (optional) Custom name for pg_controldata binary.
  • PATRONI_POSTGRESQL_BIN_PG_BASEBACKUP: (optional) Custom name for pg_basebackup binary.
  • PATRONI_POSTGRESQL_BIN_POSTGRES: (optional) Custom name for postgres binary.
  • PATRONI_POSTGRESQL_BIN_IS_READY: (optional) Custom name for pg_isready binary.
  • PATRONI_POSTGRESQL_BIN_PG_REWIND: (optional) Custom name for pg_rewind binary.
  • PATRONI_POSTGRESQL_PGPASS: path to the .pgpass password file. Patroni creates this file before executing pg_basebackup and under some other circumstances. The location must be writable by Patroni.
  • PATRONI_REPLICATION_USERNAME: replication username; the user will be created during initialization. Replicas will use this user to access the replication source via streaming replication
  • PATRONI_REPLICATION_PASSWORD: replication password; the user will be created during initialization.
  • PATRONI_REPLICATION_SSLMODE: (optional) maps to sslmode. Specifies the TLS negotiation mode. See the PostgreSQL documentation for each mode. Default: prefer.
  • PATRONI_REPLICATION_SSLKEY: (optional) maps to sslkey. Path to the secret key for the client certificate.
  • PATRONI_REPLICATION_SSLPASSWORD: (optional) maps to sslpassword. Password for the secret key in PATRONI_REPLICATION_SSLKEY.
  • PATRONI_REPLICATION_SSLCERT: (optional) maps to sslcert. Path to the client certificate.
  • PATRONI_REPLICATION_SSLROOTCERT: (optional) maps to sslrootcert. File containing one or more trusted CA certificates. The client uses them to verify the server certificate.
  • PATRONI_REPLICATION_SSLCRL: (optional) maps to sslcrl. Certificate revocation list file. The client rejects servers whose certificates appear in the list.
  • PATRONI_REPLICATION_SSLCRLDIR: (optional) maps to sslcrldir. Directory containing certificate revocation list files. The client rejects servers whose certificates appear in these lists.
  • PATRONI_REPLICATION_SSLNEGOTIATION: (optional) maps to sslnegotiation. Controls server SSL negotiation when SSL is used.
  • PATRONI_REPLICATION_GSSENCMODE: (optional) maps to gssencmode. Controls whether to negotiate secure GSS TCP/IP and its priority.
  • PATRONI_REPLICATION_CHANNEL_BINDING: (optional) maps to channel_binding. Controls client channel binding.
  • PATRONI_SUPERUSER_USERNAME: name for the superuser, set during initialization (initdb) and later used by Patroni to connect to the postgres. Also this user is used by pg_rewind.
  • PATRONI_SUPERUSER_PASSWORD: password for the superuser, set during initialization (initdb).
  • PATRONI_SUPERUSER_SSLMODE: (optional) maps to sslmode. Specifies the TLS negotiation mode. See the PostgreSQL documentation for each mode. Default: prefer.
  • PATRONI_SUPERUSER_SSLKEY: (optional) maps to sslkey. Path to the secret key for the client certificate.
  • PATRONI_SUPERUSER_SSLPASSWORD: (optional) maps to sslpassword. Password for the secret key in PATRONI_SUPERUSER_SSLKEY.
  • PATRONI_SUPERUSER_SSLCERT: (optional) maps to sslcert. Path to the client certificate.
  • PATRONI_SUPERUSER_SSLROOTCERT: (optional) maps to sslrootcert. File containing one or more trusted CA certificates. The client uses them to verify the server certificate.
  • PATRONI_SUPERUSER_SSLCRL: (optional) maps to sslcrl. Certificate revocation list file. The client rejects servers whose certificates appear in the list.
  • PATRONI_SUPERUSER_SSLCRLDIR: (optional) maps to sslcrldir. Directory containing certificate revocation list files. The client rejects servers whose certificates appear in these lists.
  • PATRONI_SUPERUSER_SSLNEGOTIATION: (optional) maps to sslnegotiation. Controls server SSL negotiation when SSL is used.
  • PATRONI_SUPERUSER_GSSENCMODE: (optional) maps to gssencmode. Controls whether to negotiate secure GSS TCP/IP and its priority.
  • PATRONI_SUPERUSER_CHANNEL_BINDING: (optional) maps to channel_binding. Controls client channel binding.
  • PATRONI_REWIND_USERNAME: (optional) name for the user for pg_rewind; the user will be created during initialization of postgres 11+ and all necessary permissions will be granted.
  • PATRONI_REWIND_PASSWORD: (optional) password for the user for pg_rewind; the user will be created during initialization.
  • PATRONI_REWIND_SSLMODE: (optional) maps to sslmode. Specifies the TLS negotiation mode. See the PostgreSQL documentation for each mode. Default: prefer.
  • PATRONI_REWIND_SSLKEY: (optional) maps to sslkey. Path to the secret key for the client certificate.
  • PATRONI_REWIND_SSLPASSWORD: (optional) maps to sslpassword. Password for the secret key in PATRONI_REWIND_SSLKEY.
  • PATRONI_REWIND_SSLCERT: (optional) maps to sslcert. Path to the client certificate.
  • PATRONI_REWIND_SSLROOTCERT: (optional) maps to sslrootcert. File containing one or more trusted CA certificates. The client uses them to verify the server certificate.
  • PATRONI_REWIND_SSLCRL: (optional) maps to sslcrl. Certificate revocation list file. The client rejects servers whose certificates appear in the list.
  • PATRONI_REWIND_SSLCRLDIR: (optional) maps to sslcrldir. Directory containing certificate revocation list files. The client rejects servers whose certificates appear in these lists.
  • PATRONI_REWIND_SSLNEGOTIATION: (optional) maps to sslnegotiation. Controls server SSL negotiation when SSL is used.
  • PATRONI_REWIND_GSSENCMODE: (optional) maps to gssencmode. Controls whether to negotiate secure GSS TCP/IP and its priority.
  • PATRONI_REWIND_CHANNEL_BINDING: (optional) maps to channel_binding. Controls client channel binding.

REST API

  • PATRONI_RESTAPI_THREAD_POOL_SIZE: size of thread pool used by Patroni to process REST API requests. Minimal value is 5, default value is 5.
  • PATRONI_RESTAPI_CONNECT_ADDRESS: IP address and port to access the REST API.
  • PATRONI_RESTAPI_LISTEN: IP address and port that Patroni will listen to, to provide health-check information for HAProxy.
  • PATRONI_RESTAPI_USERNAME: Basic-auth username to protect unsafe REST API endpoints.
  • PATRONI_RESTAPI_PASSWORD: Basic-auth password to protect unsafe REST API endpoints.
  • PATRONI_RESTAPI_CERTFILE: Specifies the file with the certificate in the PEM format. If the certfile is not specified or is left empty, the API server will work without SSL.
  • PATRONI_RESTAPI_KEYFILE: Specifies the file with the secret key in the PEM format.
  • PATRONI_RESTAPI_KEYFILE_PASSWORD: Specifies a password for decrypting the keyfile.
  • PATRONI_RESTAPI_CAFILE: Specifies the file with the CA_BUNDLE with certificates of trusted CAs to use while verifying client certs.
  • PATRONI_RESTAPI_CIPHERS: (optional) Specifies the permitted cipher suites (e.g. “ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:!SSLv1:!SSLv2:!SSLv3:!TLSv1:!TLSv1.1”)
  • PATRONI_RESTAPI_VERIFY_CLIENT: (optional) client certificate verification mode: none (default), optional, or required. none disables verification. required requires certificates for all calls; successful signature verification authenticates the client. optional requires and checks certificates only for unsafe PUT, POST, PATCH, and DELETE requests.
  • PATRONI_RESTAPI_ALLOWLIST: (optional) hosts permitted to call unsafe endpoints. Each entry can be a host name, IP address, or CIDR network. Default: allow all. With allowlist or allowlist_include_members set, all unlisted sources are rejected.
  • PATRONI_RESTAPI_ALLOWLIST_INCLUDE_MEMBERS: (optional) if true, permits unsafe endpoint access from cluster members registered in the DCS. It uses each member’s api_url host name or IP address. The operating system may use a different address for outgoing connections.
  • PATRONI_RESTAPI_HTTP_EXTRA_HEADERS: (optional) HTTP headers let the REST API server pass additional information with an HTTP response.
  • PATRONI_RESTAPI_HTTPS_EXTRA_HEADERS: (optional) HTTPS headers let the REST API server pass additional information with an HTTP response when TLS is enabled. This will also pass additional information set in http_extra_headers.
  • PATRONI_RESTAPI_REQUEST_QUEUE_SIZE: (optional): Sets request queue size for TCP socket used by Patroni REST API. Once the queue is full, further requests get a “Connection denied” error. The default value is 5.
  • PATRONI_RESTAPI_SERVER_TOKENS: (optional) Configures the value of the Server HTTP header. Original (default) will expose the original behaviour and display the BaseHTTP and Python versions, e.g. BaseHTTP/0.6 Python/3.12.3. Minimal: The header will contain only the Patroni version, e.g. Patroni/4.0.0. ProductOnly: The header will contain only the product name, e.g. Patroni.

Warning

  • The PATRONI_RESTAPI_CONNECT_ADDRESS must be accessible from all nodes of a given Patroni cluster. Internally Patroni is using it during the leader race to find nodes with minimal replication lag.
  • If you enabled client certificates validation (PATRONI_RESTAPI_VERIFY_CLIENT is set to required), you also must provide valid client certificates in the PATRONI_CTL_CERTFILE, PATRONI_CTL_KEYFILE, PATRONI_CTL_KEYFILE_PASSWORD. If not provided, Patroni will not work correctly.

CTL

  • PATRONICTL_CONFIG_FILE: (optional) location of the configuration file.
  • PATRONI_CTL_USERNAME: (optional) Basic-auth username for accessing protected REST API endpoints. If not provided patronictl will use the value provided for REST API “username” parameter.
  • PATRONI_CTL_PASSWORD: (optional) Basic-auth password for accessing protected REST API endpoints. If not provided patronictl will use the value provided for REST API “password” parameter.
  • PATRONI_CTL_INSECURE: (optional) Allow connections to REST API without verifying SSL certs.
  • PATRONI_CTL_CACERT: (optional) CA_BUNDLE file or directory with trusted CAs for REST API SSL verification. If absent, patronictl uses the REST API “cafile” value.
  • PATRONI_CTL_CERTFILE: (optional) Specifies the file with the client certificate in the PEM format.
  • PATRONI_CTL_KEYFILE: (optional) Specifies the file with the client secret key in the PEM format.
  • PATRONI_CTL_KEYFILE_PASSWORD: (optional) Specifies a password for decrypting the client keyfile.

4 - Patroni REST API

Reference for Patroni REST API endpoints and operational behaviors.

Source: https://patroni.readthedocs.io/en/latest/rest_api.html

Patroni uses its REST API during leader races. patronictl uses it for failovers, switchovers, reinitialization, restarts, and reloads. HAProxy and other load balancers use it for HTTP health checks. Monitoring systems can also use it. This page lists the available endpoints.


Health check endpoints

Health check GET requests return an HTTP status code and a JSON document with node status. Use HEAD or OPTIONS instead of GET if you do not need JSON.

  • The following requests to Patroni REST API will return HTTP status code 200 only when the Patroni node is running as the primary with leader lock:

    • GET /
    • GET /primary
    • GET /read-write
  • GET /standby-leader: returns HTTP status code 200 only when the Patroni node is running as the leader in a standby cluster.

  • GET /leader: returns HTTP 200 if the node holds the leader lock. Unlike the preceding endpoints, it does not distinguish PostgreSQL roles primary and standby_leader.

  • GET /replica: returns HTTP 200 only if the node is running, its role is replica, and noloadbalance is unset.

  • GET /replica?replication_state=<required state>: adds a replication state check to replica. Use replication_state=streaming to exclude replicas still catching up through archive recovery.

  • GET /replica?lag=<max-lag>: adds a lag check to replica. HTTP 200 requires lag below the limit. For performance, Patroni uses DCS cluster.last_leader_operation as the leader WAL position to calculate lag. Specify max-lag as an integer byte count or a readable value, such as 16kB, 64MB, or 1GB.

    • GET /replica?lag=1048576
    • GET /replica?lag=1024kB
    • GET /replica?lag=10MB
    • GET /replica?lag=1GB
  • GET /replica?tag_key1=value1&tag_key2=value2: also checks custom key1 and key2 tags in the YAML tags section. An undefined tag or a value different from the query value returns HTTP 503.

    The following requests check leader or standby leader status. They ignore custom tags:

    • GET /?tag_key1=value1&tag_key2=value2
    • GET /leader?tag_key1=value1&tag_key2=value2
    • GET /primary?tag_key1=value1&tag_key2=value2
    • GET /read-write?tag_key1=value1&tag_key2=value2
    • GET /standby_leader?tag_key1=value1&tag_key2=value2
    • GET /standby-leader?tag_key1=value1&tag_key2=value2
  • GET /read-only: like the above endpoint, but also includes the primary.

  • GET /synchronous or GET /sync: returns HTTP status code 200 only when the Patroni node is running as a synchronous standby.

  • GET /read-only-sync: like the above endpoint, but also includes the primary.

  • GET /quorum: returns HTTP status code 200 only when this Patroni node is listed as a quorum node in synchronous_standby_names on the primary.

  • GET /read-only-quorum: like the above endpoint, but also includes the primary.

  • GET /asynchronous or GET /async: returns HTTP status code 200 only when the Patroni node is running as an asynchronous standby.

  • GET /asynchronous?lag=<max-lag> or GET /async?lag=<max-lag>: adds a lag check to asynchronous or async. HTTP 200 requires lag below the limit. For performance, Patroni uses DCS cluster.last_leader_operation as the leader WAL position to calculate lag. Specify max-lag as an integer byte count or a readable value, such as 16kB, 64MB, or 1GB.

    • GET /async?lag=1048576
    • GET /async?lag=1024kB
    • GET /async?lag=10MB
    • GET /async?lag=1GB
  • GET /health: returns HTTP status code 200 only when PostgreSQL is up and running.

  • GET /liveness: returns HTTP 200 if the heartbeat loop operates correctly. Returns 503 if the last run was more than ttl seconds ago on the primary or 2*ttl on a replica. Use this for livenessProbe.

  • GET /readiness?lag=<max-lag>&mode=apply|write: returns HTTP 200 for a leader or a running, replicating node within the lag limit. The lag parameter limits standby lag and defaults to maximum_lag_on_failover. Use bytes or readable values, such as 16kB, 64MB, or 1GB. Mode specifies whether WAL must be replayed (apply) or only received (write). The default is apply.

    As a Kubernetes readinessProbe, this prevents new pods from becoming ready before they catch up to the leader. With a PodDisruptionBudget, it prevents premature leader termination during rolling restarts. It also excludes replicas that cannot keep up from read-only traffic. Use this endpoint for readinessProbe where Kubernetes endpoints cannot support leader elections, such as OpenShift.

The liveness endpoint is lightweight and runs no SQL. Configure probes to start failing around leader key expiration. With the default ttl of 30s, use this example:

readinessProbe:
  httpGet:
    scheme: HTTP
    path: /readiness
    port: 8008
  initialDelaySeconds: 3
  periodSeconds: 10
  timeoutSeconds: 5
  successThreshold: 1
  failureThreshold: 3
livenessProbe:
  httpGet:
    scheme: HTTP
    path: /liveness
    port: 8008
  initialDelaySeconds: 3
  periodSeconds: 10
  timeoutSeconds: 5
  successThreshold: 1
  failureThreshold: 3

Monitoring endpoint

Patroni uses GET /patroni during leader races. Monitoring systems can also use it. Its JSON structure matches the health check endpoints.

Example: A healthy cluster

$ curl -s http://localhost:8008/patroni | jq .
{
  "state": "running",
  "postmaster_start_time": "2024-08-28 19:39:26.352526+00:00",
  "role": "primary",
  "server_version": 160004,
  "xlog": {
    "location": 67395656
  },
  "timeline": 1,
  "replication": [
    {
      "usename": "replicator",
      "application_name": "patroni2",
      "client_addr": "10.89.0.6",
      "state": "streaming",
      "sync_state": "async",
      "sync_priority": 0
    },
    {
      "usename": "replicator",
      "application_name": "patroni3",
      "client_addr": "10.89.0.2",
      "state": "streaming",
      "sync_state": "async",
      "sync_priority": 0
    }
  ],
  "dcs_last_seen": 1692356718,
  "tags": {
    "clonefrom": true
  },
  "database_system_identifier": "7268616322854375442",
  "patroni": {
    "version": "4.0.0",
    "scope": "demo",
    "name": "patroni1"
  }
}

Example: An unlocked cluster

$ curl -s http://localhost:8008/patroni  | jq .
{
  "state": "running",
  "postmaster_start_time": "2024-08-28 19:39:26.352526+00:00",
  "role": "replica",
  "server_version": 160004,
  "xlog": {
    "received_location": 67419744,
    "replayed_location": 67419744,
    "replayed_timestamp": null,
    "paused": false
  },
  "timeline": 1,
  "replication": [
    {
      "usename": "replicator",
      "application_name": "patroni2",
      "client_addr": "10.89.0.6",
      "state": "streaming",
      "sync_state": "async",
      "sync_priority": 0
    },
    {
      "usename": "replicator",
      "application_name": "patroni3",
      "client_addr": "10.89.0.2",
      "state": "streaming",
      "sync_state": "async",
      "sync_priority": 0
    }
  ],
  "cluster_unlocked": true,
  "dcs_last_seen": 1692356928,
  "tags": {
    "clonefrom": true
  },
  "database_system_identifier": "7268616322854375442",
  "patroni": {
    "version": "4.0.0",
    "scope": "demo",
    "name": "patroni1"
  }
}

Example: An unlocked cluster with DCS failsafe mode enabled

$ curl -s http://localhost:8008/patroni  | jq .
{
  "state": "running",
  "postmaster_start_time": "2024-08-28 19:39:26.352526+00:00",
  "role": "replica",
  "server_version": 160004,
  "xlog": {
    "location": 67420024
  },
  "timeline": 1,
  "replication": [
    {
      "usename": "replicator",
      "application_name": "patroni2",
      "client_addr": "10.89.0.6",
      "state": "streaming",
      "sync_state": "async",
      "sync_priority": 0
    },
    {
      "usename": "replicator",
      "application_name": "patroni3",
      "client_addr": "10.89.0.2",
      "state": "streaming",
      "sync_state": "async",
      "sync_priority": 0
    }
  ],
  "cluster_unlocked": true,
  "failsafe_mode_is_active": true,
  "dcs_last_seen": 1692356928,
  "tags": {
    "clonefrom": true
  },
  "database_system_identifier": "7268616322854375442",
  "patroni": {
    "version": "4.0.0",
    "scope": "demo",
    "name": "patroni1"
  }
}

Example: A cluster with the pause mode enabled

$ curl -s http://localhost:8008/patroni  | jq .
{
  "state": "running",
  "postmaster_start_time": "2024-08-28 19:39:26.352526+00:00",
  "role": "replica",
  "server_version": 160004,
  "xlog": {
    "location": 67420024
  },
  "timeline": 1,
  "replication": [
    {
      "usename": "replicator",
      "application_name": "patroni2",
      "client_addr": "10.89.0.6",
      "state": "streaming",
      "sync_state": "async",
      "sync_priority": 0
    },
    {
      "usename": "replicator",
      "application_name": "patroni3",
      "client_addr": "10.89.0.2",
      "state": "streaming",
      "sync_state": "async",
      "sync_priority": 0
    }
  ],
  "pause": true,
  "dcs_last_seen": 1724874295,
  "tags": {
    "clonefrom": true
  },
  "database_system_identifier": "7268616322854375442",
  "patroni": {
    "version": "4.0.0",
    "scope": "demo",
    "name": "patroni1"
  }
}

Retrieve the Patroni metrics in Prometheus format through the GET /metrics endpoint.

$ curl http://localhost:8008/metrics

# HELP patroni_version Patroni semver without periods. \
# TYPE patroni_version gauge
patroni_version{scope="batman",name="patroni1"} 040000
# HELP patroni_postgres_running Value is 1 if Postgres is running, 0 otherwise.
# TYPE patroni_postgres_running gauge
patroni_postgres_running{scope="batman",name="patroni1"} 1
# HELP patroni_postmaster_start_time Epoch seconds since Postgres started.
# TYPE patroni_postmaster_start_time gauge
patroni_postmaster_start_time{scope="batman",name="patroni1"} 1724873966.352526
# HELP patroni_primary Value is 1 if this node is the leader, 0 otherwise.
# TYPE patroni_primary gauge
patroni_primary{scope="batman",name="patroni1"} 1
# HELP patroni_xlog_location Current location of the Postgres transaction log, 0 if this node is not the leader.
# TYPE patroni_xlog_location counter
patroni_xlog_location{scope="batman",name="patroni1"} 22320573386952
# HELP patroni_standby_leader Value is 1 if this node is the standby_leader, 0 otherwise.
# TYPE patroni_standby_leader gauge
patroni_standby_leader{scope="batman",name="patroni1"} 0
# HELP patroni_replica Value is 1 if this node is a replica, 0 otherwise.
# TYPE patroni_replica gauge
patroni_replica{scope="batman",name="patroni1"} 0
# HELP patroni_sync_standby Value is 1 if this node is a sync standby replica, 0 otherwise.
# TYPE patroni_sync_standby gauge
patroni_sync_standby{scope="batman",name="patroni1"} 0
# HELP patroni_quorum_standby Value is 1 if this node is a quorum standby replica, 0 otherwise.
# TYPE patroni_quorum_standby gauge
patroni_quorum_standby{scope="batman",name="patroni1"} 0
# HELP patroni_xlog_received_location Current location of the received Postgres transaction log, 0 if this node is not a replica.
# TYPE patroni_xlog_received_location counter
patroni_xlog_received_location{scope="batman",name="patroni1"} 0
# HELP patroni_xlog_replayed_location Current location of the replayed Postgres transaction log, 0 if this node is not a replica.
# TYPE patroni_xlog_replayed_location counter
patroni_xlog_replayed_location{scope="batman",name="patroni1"} 0
# HELP patroni_xlog_replayed_timestamp Current timestamp of the replayed Postgres transaction log, 0 if null.
# TYPE patroni_xlog_replayed_timestamp gauge
patroni_xlog_replayed_timestamp{scope="batman",name="patroni1"} 0
# HELP patroni_xlog_paused Value is 1 if the Postgres xlog is paused, 0 otherwise.
# TYPE patroni_xlog_paused gauge
patroni_xlog_paused{scope="batman",name="patroni1"} 0
# HELP patroni_postgres_streaming Value is 1 if Postgres is streaming, 0 otherwise.
# TYPE patroni_postgres_streaming gauge
patroni_postgres_streaming{scope="batman",name="patroni1"} 1
# HELP patroni_postgres_in_archive_recovery Value is 1 if Postgres is replicating from archive, 0 otherwise.
# TYPE patroni_postgres_in_archive_recovery gauge
patroni_postgres_in_archive_recovery{scope="batman",name="patroni1"} 0
# HELP patroni_postgres_server_version Version of Postgres (if running), 0 otherwise.
# TYPE patroni_postgres_server_version gauge
patroni_postgres_server_version{scope="batman",name="patroni1"} 160004
# HELP patroni_cluster_unlocked Value is 1 if the cluster is unlocked, 0 if locked.
# TYPE patroni_cluster_unlocked gauge
patroni_cluster_unlocked{scope="batman",name="patroni1"} 0
# HELP patroni_failsafe_mode_is_active Value is 1 if failsafe mode is active, 0 otherwise.
# TYPE patroni_failsafe_mode_is_active gauge
patroni_failsafe_mode_is_active{scope="batman",name="patroni1"} 0
# HELP patroni_failsafe_mode_enabled Value is 1 if failsafe_mode is enabled, 0 otherwise.
# TYPE patroni_failsafe_mode_enabled gauge
patroni_failsafe_mode_enabled{scope="batman",name="patroni1"} 0
# HELP patroni_failsafe_member Value is 1 if this node is a member of failsafe, 0 otherwise.
# TYPE patroni_failsafe_member gauge
patroni_failsafe_member{scope="batman",name="patroni1"} 0
# HELP patroni_postgres_timeline Postgres timeline of this node (if running), 0 otherwise.
# TYPE patroni_postgres_timeline gauge
patroni_postgres_timeline{scope="batman",name="patroni1"} 24
# HELP patroni_dcs_last_seen Epoch timestamp when DCS was last contacted successfully by Patroni.
# TYPE patroni_dcs_last_seen gauge
patroni_dcs_last_seen{scope="batman",name="patroni1"} 1724874235
# HELP patroni_pending_restart Value is 1 if the node needs a restart, 0 otherwise.
# TYPE patroni_pending_restart gauge
patroni_pending_restart{scope="batman",name="patroni1"} 1
# HELP patroni_is_paused Value is 1 if auto failover is disabled, 0 otherwise.
# TYPE patroni_is_paused gauge
patroni_is_paused{scope="batman",name="patroni1"} 1
# HELP patroni_postgres_state Numeric representation of Postgres state.
# Values: 0=initdb, 1=initdb_failed, 2=custom_bootstrap, 3=custom_bootstrap_failed, 4=creating_replica, 5=running, 6=starting, 7=bootstrap_starting, 8=start_failed, 9=restarting, 10=restart_failed, 11=stopping, 12=stopped, 13=stop_failed, 14=crashed
# TYPE patroni_postgres_state gauge
patroni_postgres_state{scope="batman",name="patroni1"} 5
# HELP patroni_failover_priority Failover priority of this node.
# TYPE patroni_failover_priority gauge
patroni_failover_priority{scope="batman",name="patroni1"} 1

PostgreSQL State Values

The patroni_postgres_state metric represents the current PostgreSQL state numerically. Monitoring and alerting systems can use it to track state changes. The PostgresqlState.get_metrics_description() static method generates these values.

ValueState NameDescription
0initdbInitializing new cluster
1initdb_failedInitialization of new cluster failed
2custom_bootstrapRunning custom bootstrap script
3custom_bootstrap_failedCustom bootstrap script failed
4creating_replicaCreating replica from primary
5runningPostgreSQL is running normally
6startingPostgreSQL is starting up
7bootstrap_startingStarting after custom bootstrap
8start_failedPostgreSQL start failed
9restartingPostgreSQL is restarting
10restart_failedPostgreSQL restart failed
11stoppingPostgreSQL is stopping
12stoppedPostgreSQL is stopped
13stop_failedPostgreSQL stop failed
14crashedPostgreSQL has crashed

PostgreSQL State Values

Note

Existing numeric values never change, to preserve monitoring compatibility. Future states receive new values.


Cluster status endpoints

  • The GET /cluster endpoint generates a JSON document describing the current cluster topology and state:
$ curl -s http://localhost:8008/cluster | jq .
{
  "members": [
    {
      "name": "patroni1",
      "role": "leader",
      "state": "running",
      "api_url": "http://10.89.0.4:8008/patroni",
      "host": "10.89.0.4",
      "port": 5432,
      "timeline": 5,
      "tags": {
        "clonefrom": true
      }
    },
    {
      "name": "patroni2",
      "role": "replica",
      "state": "streaming",
      "api_url": "http://10.89.0.6:8008/patroni",
      "host": "10.89.0.6",
      "port": 5433,
      "timeline": 5,
      "tags": {
        "clonefrom": true
      },
      "receive_lag": 0,
      "receive_lsn": "0/4000060",
      "replay_lag": 0,
      "replay_lsn": "0/4000060",
      "lag": 0,
      "lsn": "0/4000060"
    }
  ],
  "scope": "demo",
  "scheduled_switchover": {
    "at": "2023-09-24T10:36:00+02:00",
    "from": "patroni1",
    "to": "patroni3"
  }
}
  • GET /history returns cluster switchover and failover history. Its format matches history files in pg_wal, with one addition: the timestamp when each timeline was created.
$ curl -s http://localhost:8008/history | jq .
[
  [
    1,
    25623960,
    "no recovery target specified",
    "2019-09-23T16:57:57+02:00"
  ],
  [
    2,
    25624344,
    "no recovery target specified",
    "2019-09-24T09:22:33+02:00"
  ],
  [
    3,
    25624752,
    "no recovery target specified",
    "2019-09-24T09:26:15+02:00"
  ],
  [
    4,
    50331856,
    "no recovery target specified",
    "2019-09-24T09:35:52+02:00"
  ]
]


Config endpoint

GET /config: Get the current version of the dynamic configuration:

$ curl -s http://localhost:8008/config | jq .
{
  "ttl": 30,
  "loop_wait": 10,
  "retry_timeout": 10,
  "maximum_lag_on_failover": 1048576,
  "postgresql": {
    "use_slots": true,
    "use_pg_rewind": true,
    "parameters": {
      "hot_standby": "on",
      "wal_level": "hot_standby",
      "max_wal_senders": 5,
      "max_replication_slots": 5,
      "max_connections": "100"
    }
  }
}

PATCH /config: Change the existing configuration.

$ curl -s -XPATCH -d \
    '{"loop_wait":5,"ttl":20,"postgresql":{"parameters":{"max_connections":"101"}}}' \
    http://localhost:8008/config | jq .
{
  "ttl": 20,
  "loop_wait": 5,
  "maximum_lag_on_failover": 1048576,
  "retry_timeout": 10,
  "postgresql": {
    "use_slots": true,
    "use_pg_rewind": true,
    "parameters": {
      "hot_standby": "on",
      "wal_level": "hot_standby",
      "max_wal_senders": 5,
      "max_replication_slots": 5,
      "max_connections": "101"
    }
  }
}

The above REST API call patches the existing configuration and returns the new configuration.

Check that the node applied the configuration. With loop_wait=5, it should log every 5 seconds. Changing “max_connections” requires restart, so the output should show “pending_restart”:

$ curl -s http://localhost:8008/patroni | jq .
{
  "database_system_identifier": "6287881213849985952",
  "postmaster_start_time": "2024-08-28 19:39:26.352526+00:00",
  "xlog": {
    "location": 2197818976
  },
  "timeline": 1,
  "dcs_last_seen": 1724874545,
  "database_system_identifier": "7408277255830290455",
  "pending_restart": true,
  "pending_restart_reason": {
    "max_connections": {
      "old_value": "100",
      "new_value": "101"
    }
  },
  "patroni": {
    "version": "4.0.0",
    "scope": "batman",
    "name": "patroni1"
  },
  "state": "running",
  "role": "primary",
  "server_version": 160004
}

Removing parameters:

To remove or reset a setting, patch it with null:

$ curl -s -XPATCH -d \
    '{"postgresql":{"parameters":{"max_connections":null}}}' \
    http://localhost:8008/config | jq .
{
  "ttl": 20,
  "loop_wait": 5,
  "retry_timeout": 10,
  "maximum_lag_on_failover": 1048576,
  "postgresql": {
    "use_slots": true,
    "use_pg_rewind": true,
    "parameters": {
      "hot_standby": "on",
      "unix_socket_directories": ".",
      "wal_level": "hot_standby",
      "max_wal_senders": 5,
      "max_replication_slots": 5
    }
  }
}

The above call removes postgresql.parameters.max_connections from the dynamic configuration.

PUT /config: unconditionally replace the complete dynamic configuration:

$ curl -s -XPUT -d \
    '{"maximum_lag_on_failover":1048576,"retry_timeout":10,"postgresql":{"use_slots":true,"use_pg_rewind":true,"parameters":{"hot_standby":"on","wal_level":"hot_standby","unix_socket_directories":".","max_wal_senders":5}},"loop_wait":3,"ttl":20}' \
    http://localhost:8008/config | jq .
{
  "ttl": 20,
  "maximum_lag_on_failover": 1048576,
  "retry_timeout": 10,
  "postgresql": {
    "use_slots": true,
    "parameters": {
      "hot_standby": "on",
      "unix_socket_directories": ".",
      "wal_level": "hot_standby",
      "max_wal_senders": 5
    },
    "use_pg_rewind": true
  },
  "loop_wait": 3
}

Switchover and failover endpoints

Switchover

The /switchover endpoint requires a healthy cluster with a leader. It can also schedule a future switchover.

A candidate is optional for /switchover but required for /failover. Without a candidate, all eligible nodes enter the leader race after the leader steps down.

The POST JSON body must include leader. Optional fields are candidate and scheduled_at. Use scheduled_at to schedule a future switchover.

HTTP 200 means switchover or failover completed successfully. HTTP 202 means Patroni scheduled the switchover. Errors return 400, 412, or 503, with details in the response body.

DELETE /switchover can be used to delete the currently scheduled switchover.

Example: perform a switchover to any healthy standby

$ curl -s http://localhost:8008/switchover -XPOST -d '{"leader":"postgresql1"}'
Successfully switched over to "postgresql2"

Example: perform a switchover to a specific node

$ curl -s http://localhost:8008/switchover -XPOST -d \
    '{"leader":"postgresql1","candidate":"postgresql2"}'
Successfully switched over to "postgresql2"

Example: schedule a switchover from the leader to any other healthy standby in the cluster at a specific time.

$ curl -s http://localhost:8008/switchover -XPOST -d \
    '{"leader":"postgresql0","scheduled_at":"2019-09-24T12:00+00"}'
Switchover scheduled

Failover

Use /failover for manual failover when no sufficiently healthy node is available. For example, promote an asynchronous standby when all synchronous standbys are unsuitable. A missing leader is not required: failover also works on a healthy cluster.

In the JSON body of the POST request you must specify the candidate field. If the leader field is specified, a switchover is triggered instead.

Example:

$ curl -s http://localhost:8008/failover -XPOST -d '{"candidate":"postgresql1"}'
Successfully failed over to "postgresql1"
Warning

Be very careful when using this endpoint, as this can cause data loss in certain situations. In most cases, the switchover endpoint satisfies the administrator’s needs.

POST /switchover and POST /failover endpoints are used by patronictl_switchover and patronictl_failover, respectively.

DELETE /switchover is used by patronictl flush cluster-name switchover.

FailoverSwitchover
Requires leader specifiednoyes
Requires candidate specifiedyesno
Can be run in pauseyesyes (only to a specific candidate)
Can be schedulednoyes (if not in pause)

Failover/Switchover comparison

Healthy standby

A member must pass these checks to enter a switchover leader race or become the selected failover/switchover leader:

  • be reachable via Patroni API;
  • not have nofailover tag set to true;
  • have watchdog fully functional (if required by the configuration);
  • in case of a switchover in a healthy cluster or an automatic failover, not exceed maximum replication lag (maximum_lag_on_failover configuration parameter);
  • For a healthy-cluster switchover or automatic failover, check the check_timeline configuration parameter. If it is true, the member timeline must not be smaller than the cluster timeline;
  • in synchronous mode:
    • In case of a switchover (both with and without a candidate): be listed in the /sync key members;
    • For a failover in both healthy and unhealthy clusters, this check is omitted.
Warning

Without a leader, manual failover can promote a candidate that fails these checks. It can be absent from /sync in synchronous mode, exceed the lag limit, or have an older timeline than the last cluster timeline.


Restart endpoint

  • POST /restart: restart Postgres on the specified node. The POST JSON body can contain these optional conditions:
    • restart_pending: if true, restart only when configuration changes require it.
    • role: restart only if the current node role matches the request.
    • postgres_version: restart only if the current Postgres version is lower than the requested version.
    • timeout: maximum wait for PostgreSQL to accept connections. Overrides primary_start_timeout.
    • schedule: future restart timestamp with time zone.
  • DELETE /restart: delete the scheduled restart.

POST /restart and DELETE /restart endpoints are used by patronictl_restart and patronictl flush cluster-name restart respectively.


Reload endpoint

POST /reload makes Patroni reread and apply its configuration file. This is equivalent to SIGHUP. Changes to parameters such as shared_buffers still require an explicit Postgres restart. Use POST /restart or patronictl_restart.

The reload endpoint is used by patronictl_reload.


Reinitialize endpoint

POST /reinitialize: recreate the data directory on the specified replica. This operation is not allowed on a primary. It removes the data directory and runs pg_basebackup or another replica creation method.

This call may fail while Patroni repeatedly tries to restart a failed Postgres instance. Set {"force":true} in the request body to override this condition.

Set {“from-leader”:true} in the request body to take the basebackup directly from the leader. Use this for reinitialization when all replicas have failed.

The reinitialize endpoint is used by patronictl_reinit.

5 - patronictl

Command reference for patronictl configuration, syntax, and subcommands.

Source: https://patroni.readthedocs.io/en/latest/patronictl.html

The patronictl command-line interface communicates with the Patroni REST API and the DCS. Use it for cluster operations, interactively or in scripts.


Configuration

patronictl uses 3 sections of the configuration:

  • ctl: REST API authentication and server identity verification. See ctl settings.
  • restapi: fallback settings when ctl does not supply REST API authentication or server verification. patronictl uses restapi.authentication if ctl.authentication is absent, and restapi.cafile if ctl.cacert is absent. See REST API settings.
  • DCS, such as etcd: DCS connection and authentication settings.

Supply these options through environment variables or a configuration file. See the corresponding sections in Environment Configuration Settings and YAML Configuration Settings.

Patronictl reads environment variables and uses their values directly.

By default, patronictl looks for patronictl.yaml in one of these system-specific directories. You can also specify a different file.

  • Mac OS X: ~/Library/Application Support/patroni
  • Mac OS X (POSIX): ~/.patroni
  • Unix: ~/.config/patroni
  • Unix (POSIX): ~/.patroni
  • Windows (roaming): C:\Users\<user>\AppData\Roaming\patroni
  • Windows (not roaming): C:\Users\<user>\AppData\Local\patroni

You can override that behavior either by:

  • Setting the environment variable PATRONICTL_CONFIG_FILE with the path to a custom configuration file;
  • Using the -c / --config-file command-line argument of patronictl with the path to a custom configuration file.
Note

On the patroni host, patronictl can use the daemon’s configuration file if it contains all required sections.


Usage

This section describes the operations available through patronictl.

The patronictl command accepts these global arguments:

-c / --config-file
As explained before, used to provide a path to a configuration file for patronictl.

-d / --dcs-url / --dcs
Provide a connection string to the DCS used by Patroni.

This argument sets or overrides the DCS and namespace in patronictl configuration.

Use DCS://HOST:PORT/NAMESPACE. For example, etcd3://localhost:2379/service connects to etcd v3 on localhost and stores cluster data under the service namespace. Missing components use configuration values or defaults.

-k / --insecure
Flag to bypass validation of REST API server SSL certificate.

This is the synopsis for running a command from the patronictl:

patronictl [ { -c | --config-file } CONFIG_FILE ]
  [ { -d | --dcs-url | --dcs } DCS_URL ] 
  [ { -k | --insecure } ]
  SUBCOMMAND
Note

Synopsis notation:

  • Square brackets enclose optional arguments.
  • Curly brackets enclose alternatives; select one.
  • [, ... ] permits repetition.
  • Uppercase names require a value.

All patronictl subcommands use this notation. Replace SUBCOMMAND in the general synopsis with the relevant subcommand synopsis.

The following sections describe each patronictl command. Examples use postgres0.yml, postgres1.yml, and postgres2.yml from the Patroni GitHub repository.

patronictl demote-cluster

Synopsis

demote-cluster
  [ CLUSTER_NAME ]
  [ --host HOST ]
  [ --port PORT ]
  [ --restore-command RESTORE_COMMAND ]
  [ --primary-slot-name PRIMARY_SLOT_NAME ]
  [ --force ]

Description

patronictl demote-cluster converts a regular Patroni cluster into a standby cluster.

The command builds standby_cluster from the supplied remote primary connection options and adds it to dynamic configuration. It waits until the leader becomes a standby leader. Before the change, it prints the topology and requests confirmation unless --force is set.

At least one of --host, --port or --restore-command must be specified.

Parameters

CLUSTER_NAME: Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--host: Address of the remote node.

--port: Port of the remote node.

--restore-command: Command to restore WAL records from the remote primary.

--primary-slot-name: Name of the replication slot on the remote node to use for replication.

--force: Flag to skip confirmation prompts when demoting the cluster.

Useful for scripts.

Examples

Demote the cluster to a standby cluster that follows a remote primary endpoint:

$ patronictl -c postgres0.yml demote-cluster batman --host 192.0.2.10 --port 5432 --primary-slot-name batman --force

patronictl dsn

Synopsis

dsn
  [ CLUSTER_NAME ]
  [ { { -r | --role } { leader | primary | standby-leader | replica | standby | any } | { -m | --member } MEMBER_NAME } ]
  [ --group CITUS_GROUP ]

Description

patronictl dsn gets the connection string for one member of the Patroni cluster.

If several members match, the command selects one and gives priority to the primary.

Parameters

CLUSTER_NAME: Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

-r / --role
Choose a member that has the given role.

Role can be one of:

  • leader: the leader of either a regular Patroni cluster or a standby Patroni cluster; or
  • primary: the leader of a regular Patroni cluster; or
  • standby-leader: the leader of a standby Patroni cluster; or
  • replica: a replica of a Patroni cluster; or
  • standby: same as replica; or
  • any: any role. Same as omitting this parameter; or

-m / --member
Choose a member of the cluster with the given name.

MEMBER_NAME is the name of the member.

--group
Choose a member that is part of the given Citus group.

CITUS_GROUP is the ID of the Citus group.

Examples

Get DSN of the primary node:

$ patronictl -c postgres0.yml dsn batman -r primary
host=127.0.0.1 port=5432

Get DSN of the node named postgresql1:

$ patronictl -c postgres0.yml dsn batman --member postgresql1
host=127.0.0.1 port=5433

patronictl edit-config

Synopsis

edit-config
  [ CLUSTER_NAME ]
  [ --group CITUS_GROUP ]
  [ { -q | --quiet } ]
  [ { -s | --set } CONFIG="VALUE" [, ... ] ]
  [ { -p | --pg } PG_CONFIG="PG_VALUE" [, ... ] ]
  [ { --apply | --replace } CONFIG_FILE ]
  [ --force ]

Description

patronictl edit-config changes cluster dynamic configuration and writes it to the DCS.

Note

In a TTY, the command displays the configuration diff through a pager. It tries less or more by default. Set PAGER to use another pager.

Parameters

CLUSTER_NAME: Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--group
Change dynamic configuration of the given Citus group.

If omitted, patronictl uses citus.group if configured.

CITUS_GROUP is the ID of the Citus group.

-q / --quiet
Flag to skip showing the configuration diff.

-s / --set
Set a given dynamic configuration option with a given value.

CONFIG is the name of the dynamic configuration path in the YAML tree, with levels joined by . .

VALUE is the value for CONFIG. If it is null, then CONFIG will be removed from the dynamic configuration.

-p / --pg
Set a given dynamic Postgres configuration option with the given value.

This is shorthand for --s / --set with postgresql.parameters. before CONFIG.

PG_CONFIG is the name of the Postgres configuration to be set.

PG_VALUE is the value for PG_CONFIG. If it is null, then PG_CONFIG will be removed from the dynamic configuration.

--apply
Apply dynamic configuration from the given file.

It is similar to specifying multiple -s / --set options, one for each configuration from CONFIG_FILE.

CONFIG_FILE is the YAML file containing changes to apply. Use - to read from stdin.

--replace
Replace the dynamic configuration in the DCS with the dynamic configuration specified in the given file.

CONFIG_FILE is the YAML file containing replacement configuration. Use - to read from stdin.

--force
Flag to skip confirmation prompts when changing the dynamic configuration.

Useful for scripts.

Examples

Change max_connections Postgres GUC:

patronictl -c postgres0.yml edit-config batman --pg max_connections="150" --force
---
+++
@@ -1,6 +1,8 @@
loop_wait: 10
maximum_lag_on_failover: 1048576
postgresql:
+  parameters:
+    max_connections: 150
  pg_hba:
  - host replication replicator 127.0.0.1/32 md5
  - host all all 0.0.0.0/0 md5

Configuration changed

Change loop_wait and ttl settings:

patronictl -c postgres0.yml edit-config batman --set loop_wait="15" --set ttl="45" --force
---
+++
@@ -1,4 +1,4 @@
-loop_wait: 10
+loop_wait: 15
maximum_lag_on_failover: 1048576
postgresql:
  pg_hba:
@@ -6,4 +6,4 @@
  - host all all 0.0.0.0/0 md5
  use_pg_rewind: true
retry_timeout: 10
-ttl: 30
+ttl: 45

Configuration changed

Remove maximum_lag_on_failover setting from dynamic configuration:

patronictl -c postgres0.yml edit-config batman --set maximum_lag_on_failover="null" --force
---
+++
@@ -1,5 +1,4 @@
loop_wait: 10
-maximum_lag_on_failover: 1048576
postgresql:
  pg_hba:
  - host replication replicator 127.0.0.1/32 md5

Configuration changed

patronictl failover

Synopsis

failover
  [ CLUSTER_NAME ]
  [ --group CITUS_GROUP ]
  --candidate CANDIDATE_NAME
  [ --force ]

Description

patronictl failover performs a manual failover in the cluster.

Use this command when the cluster is unhealthy, for example:

  • There is no leader; or
  • There is no synchronous standby available in a synchronous cluster.

With synchronous mode enabled, this command can also fail over to an asynchronous node.

Note

patronictl failover also works on a healthy cluster. We recommend patronictl switchover for healthy clusters.

Warning

Failover can lose data if the promoted replica is behind the primary.

Parameters

CLUSTER_NAME: Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--group
Perform a failover in the given Citus group.

CITUS_GROUP is the ID of the Citus group.

--candidate
The node to be promoted on failover.

CANDIDATE_NAME is the name of the node to be promoted.

--force
Flag to skip confirmation prompts when performing the failover.

Useful for scripts.

Examples

Fail over to node postgresql2:

$ patronictl -c postgres0.yml failover batman --candidate postgresql2 --force
Current cluster topology
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  3 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  3 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  3 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
2023-09-12 11:52:27.50978 Successfully failed over to "postgresql2"
+ Cluster: batman (7277694203142172922) -+---------+----+-------------+---------+------------+---------+
| Member      | Host           | Role    | State   | TL | Receive LSN |     Lag | Replay LSN |     Lag |
+-------------+----------------+---------+---------+----+-------------+---------+------------+---------+
| postgresql0 | 127.0.0.1:5432 | Replica | stopped |    |     unknown | unknown |    unknown | unknown |
| postgresql1 | 127.0.0.1:5433 | Replica | running |  3 |   0/4000188 |       0 |  0/4000188 |       0 |
| postgresql2 | 127.0.0.1:5434 | Leader  | running |  3 |             |         |            |         |
+-------------+----------------+---------+---------+----+-------------+---------+------------+---------+

patronictl flush

Synopsis

flush
  CLUSTER_NAME
  [ MEMBER_NAME [, ... ] ]
  { restart | switchover }
  [ --group CITUS_GROUP ]
  [ { -r | --role } { leader | primary | standby-leader | replica | standby | any } ]
  [ --force ]

Description

patronictl flush discards scheduled events, if any.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

MEMBER_NAME
Discard scheduled events for the given Patroni member(s).

Specify one or more members. If omitted, the command considers all members.

Note

Only used if discarding scheduled restart events.

restart
Discard scheduled restart events.

switchover
Discard scheduled switchover event.

--group
Discard scheduled events from the given Citus group.

CITUS_GROUP is the ID of the Citus group.

-r / --role
Discard scheduled events for members that have the given role.

Role can be one of:

  • leader: the leader of either a regular Patroni cluster or a standby Patroni cluster; or
  • primary: the leader of a regular Patroni cluster; or
  • standby-leader: the leader of a standby Patroni cluster; or
  • replica: a replica of a Patroni cluster; or
  • standby: same as replica; or
  • any: any role. Same as omitting this parameter.
Note

Only used if discarding scheduled restart events.

--force
Flag to skip confirmation prompts when performing the flush.

Useful for scripts.

Examples

Discard a scheduled switchover event:

$ patronictl -c postgres0.yml flush batman switchover --force
Success: scheduled switchover deleted

Discard scheduled restart of all standby nodes:

$ patronictl -c postgres0.yml flush batman restart -r replica --force
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+---------------------------+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag | Scheduled restart         |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+---------------------------+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  5 |             |     |            |     | 2025-03-23T18:00:00-03:00 |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  5 |   0/4000400 |   0 |  0/4000400 |   0 | 2025-03-23T18:00:00-03:00 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  5 |   0/4000400 |   0 |  0/4000400 |   0 | 2025-03-23T18:00:00-03:00 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+---------------------------+
Success: flush scheduled restart for member postgresql1
Success: flush scheduled restart for member postgresql2

Discard scheduled restart of nodes postgresql0 and postgresql1:

$ patronictl -c postgres0.yml flush batman postgresql0 postgresql1 restart --force
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+---------------------------+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag | Scheduled restart         |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+---------------------------+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  5 |             |     |            |     | 2025-03-23T18:00:00-03:00 |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  5 |   0/4000400 |   0 |  0/4000400 |   0 | 2025-03-23T18:00:00-03:00 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  5 |   0/4000400 |   0 |  0/4000400 |   0 | 2025-03-23T18:00:00-03:00 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+---------------------------+
Success: flush scheduled restart for member postgresql0
Success: flush scheduled restart for member postgresql1

patronictl history

Synopsis

history
  [ CLUSTER_NAME ]
  [ --group CITUS_GROUP ]
  [ { -f | --format } { pretty | tsv | json | yaml } ]

Description

patronictl history shows a history of failover and switchover events from the cluster, if any.

The following information is included in the output:

TL
Postgres timeline at which the event occurred.

LSN
Postgres LSN at which the event occurred.

Reason
Reason fetched from the Postgres .history file.

Timestamp
Time when the event occurred.

New Leader
Patroni member that has been promoted during the event.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--group
Show history of events from the given Citus group.

CITUS_GROUP is the ID of the Citus group.

If omitted, patronictl uses citus.group if configured.

-f / --format
How to format the list of events in the output.

Format can be one of:

  • pretty: prints history as a pretty table; or
  • tsv: prints history as tabular information, with columns delimited by \t; or
  • json: prints history in JSON format; or
  • yaml: prints history in YAML format.

The default is pretty.

--force
Flag to skip confirmation prompts when performing the flush.

Useful for scripts.

Examples

Show the history of events:

$ patronictl -c postgres0.yml history batman
+----+----------+------------------------------+----------------------------------+-------------+
| TL |      LSN | Reason                       | Timestamp                        | New Leader  |
+----+----------+------------------------------+----------------------------------+-------------+
|  1 | 24392648 | no recovery target specified | 2023-09-11T22:11:27.125527+00:00 | postgresql0 |
|  2 | 50331864 | no recovery target specified | 2023-09-12T11:34:03.148097+00:00 | postgresql0 |
|  3 | 83886704 | no recovery target specified | 2023-09-12T11:52:26.948134+00:00 | postgresql2 |
|  4 | 83887280 | no recovery target specified | 2023-09-12T11:53:09.620136+00:00 | postgresql0 |
+----+----------+------------------------------+----------------------------------+-------------+

Show the history of events in YAML format:

$ patronictl -c postgres0.yml history batman -f yaml
- LSN: 24392648
  New Leader: postgresql0
  Reason: no recovery target specified
  TL: 1
  Timestamp: '2023-09-11T22:11:27.125527+00:00'
- LSN: 50331864
  New Leader: postgresql0
  Reason: no recovery target specified
  TL: 2
  Timestamp: '2023-09-12T11:34:03.148097+00:00'
- LSN: 83886704
  New Leader: postgresql2
  Reason: no recovery target specified
  TL: 3
  Timestamp: '2023-09-12T11:52:26.948134+00:00'
- LSN: 83887280
  New Leader: postgresql0
  Reason: no recovery target specified
  TL: 4
  Timestamp: '2023-09-12T11:53:09.620136+00:00'

patronictl list

Synopsis

list
  [ CLUSTER_NAME [, ... ] ]
  [ --group CITUS_GROUP ]
  [ { -e | --extended } ]
  [ { -t | --timestamp } ]
  [ { -f | --format } { pretty | tsv | json | yaml } ]
  [ { -W | { -w | --watch } TIME } ]

Description

patronictl list shows information about Patroni cluster and its members.

The following information is included in the output:

Cluster
Name of the Patroni cluster.

Member
Name of the Patroni member.

Host
Host where the member is located.

Role
Current role of the member.

Can be one among:

  • Leader: the current leader of a regular Patroni cluster; or
  • Standby Leader: the current leader of a Patroni standby cluster; or
  • Sync Standby: a synchronous standby of a Patroni cluster with synchronous mode enabled; or
  • Replica: a regular standby of a Patroni cluster.

State
Current state of Postgres in the Patroni member.

Some examples among the possible states:

  • running: if Postgres is currently up and running;
  • streaming: if a replica and Postgres is currently streaming WALs from the primary node;
  • in archive recovery: if a replica and Postgres is currently fetching WALs from the archive;
  • stopped: if Postgres had been shut down;
  • crashed: if Postgres has crashed.

TL
Current Postgres timeline in the Patroni member.

Receive LSN
Last WAL location received through streaming replication and synchronized to disk: pg_catalog.pg_last_(xlog|wal)_receive_(location|lsn)().

Receive Lag
Replication lag between the Receive LSN position of the member and its upstream in MB.

Replay LSN
Last WAL location replayed during member recovery: pg_catalog.pg_last_(xlog|wal)_replay_(location|lsn)().

Replay Lag
Replication lag between the Replay LSN position of the member and its upstream in MB.

Besides that, the following information may be included in the output:

System identifier
Postgres system identifier.

Note

Shown in the table header.

Only shown if output format is pretty.

Group
Citus group ID.

Note

Shown in the table header.

Only shown if a Citus cluster.

Pending restart
* indicates that the node needs a restart for some Postgres configuration to take effect. An empty value indicates the node does not require a restart.

Note

Shown as a member attribute.

Shown if:

  • Printing in pretty or tsv format and with extended output enabled; or
  • If node requires a restart.

Scheduled restart
Scheduled restart time for the member’s Postgres instance. Empty if no restart is scheduled.

Note

Shown as a member attribute.

Shown if:

  • Printing in pretty or tsv format and with extended output enabled; or
  • If node has a scheduled restart.

Tags
Member tags. Empty if no tags are set or all tags have default values.

Note

Shown as a member attribute.

Shown if:

  • Printing in pretty or tsv format and with extended output enabled; or
  • If node has any custom tags, or any default tags with non-default values.

Scheduled switchover
Timestamp at which a switchover has been scheduled for the Patroni cluster, if any.

Note

Shown in the table footer.

Only shown if there is a scheduled switchover, and output format is pretty.

Maintenance mode

If the cluster monitoring is currently paused.

Note

Shown in the table footer.

Only shown if the cluster is paused, and output format is pretty.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--group
Show information about members from the given Citus group.

CITUS_GROUP is the ID of the Citus group.

-e / --extended
Show extended information.

Force showing Pending restart, Scheduled restart and Tags attributes, even if their value is empty.

Note

Only applies to pretty and tsv output formats.

-t / --timestamp
Print timestamp before printing information about the cluster and its members.

-f / --format
How to format the list of events in the output.

Format can be one of:

  • pretty: prints history as a pretty table; or
  • tsv: prints history as tabular information, with columns delimited by \t; or
  • json: prints history in JSON format; or
  • yaml: prints history in YAML format.

The default is pretty.

-W
Automatically refresh information every 2 seconds.

-w / --watch
Automatically refresh information at the specified interval.

TIME is the interval between refreshes, in seconds.

Examples

Show information about the cluster in pretty format:

$ patronictl -c postgres0.yml list batman
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  5 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+

Show information about the cluster in pretty format with extended columns:

$ patronictl -c postgres0.yml list batman -e
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+-----------------+------------------------+-------------------+------+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag | Pending restart | Pending restart reason | Scheduled restart | Tags |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+-----------------+------------------------+-------------------+------+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  5 |             |     |            |     |                 |                        |                   |      |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |                 |                        |                   |      |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |                 |                        |                   |      |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+-----------------+------------------------+-------------------+------+

Show information about the cluster in YAML format, with timestamp of execution:

$ patronictl -c postgres0.yml list batman -f yaml -t
2023-09-12 13:30:48
- Cluster: batman
  Host: 127.0.0.1:5432
  Member: postgresql0
  Role: Leader
  State: running
  TL: 5
- Cluster: batman
  Host: 127.0.0.1:5433
  Receive LSN: 0/40004E8
  Receive Lag: 0
  Replay LSN: 0/40004E8
  Replay Lag: 0
  Member: postgresql1
  Role: Replica
  State: streaming
  TL: 5
- Cluster: batman
  Host: 127.0.0.1:5434
  Receive LSN: 0/40004E8
  Receive Lag: 0
  Replay LSN: 0/40004E8
  Replay Lag: 0
  Member: postgresql2
  Role: Replica
  State: streaming
  TL: 5

patronictl pause

Synopsis

pause
  [ CLUSTER_NAME ]
  [ --group CITUS_GROUP ]
  [ --wait ]

Description

patronictl pause temporarily puts the Patroni cluster in maintenance mode and disables automatic failover.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--group
Pause the given Citus group.

CITUS_GROUP is the ID of the Citus group.

If omitted, patronictl uses citus.group if configured.

--wait
Wait until all Patroni members are paused before returning control to the caller.

Examples

Put the cluster in maintenance mode, and wait until all nodes have been paused:

$ patronictl -c postgres0.yml pause batman --wait
'pause' request sent, waiting until it is recognized by all nodes
Success: cluster management is paused

patronictl promote-cluster

Synopsis

promote-cluster
  [ CLUSTER_NAME ]
  [ --force ]

Description

patronictl promote-cluster converts a standby cluster into a regular Patroni cluster.

The command removes standby_cluster from dynamic configuration and waits until the leader becomes primary. Before the change, it prints the topology and requests confirmation unless --force is set.

Parameters

CLUSTER_NAME: Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--force: Flag to skip confirmation prompts when promoting the cluster.

Useful for scripts.

Examples

Promote the standby cluster to run as a regular Patroni cluster:

$ patronictl -c postgres0.yml promote-cluster batman --force

patronictl query

Synopsis

query
  [ CLUSTER_NAME ]
  [ --group CITUS_GROUP ]
  [ { { -r | --role } { leader | primary | standby-leader | replica | standby | any } | { -m | --member } MEMBER_NAME } ]
  [ { -d | --dbname } DBNAME ]
  [ { -U | --username } USERNAME ]
  [ --password ]
  [ --format { pretty | tsv | json | yaml } ]
  [ { { -f | --file } FILE_NAME | { -c | --command } SQL_COMMAND } ]
  [ --delimiter ]
  [ { -W | { -w | --watch } TIME } ]

Description

patronictl query executes a SQL command or script against a member of the Patroni cluster.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--group
Query the given Citus group.

CITUS_GROUP is the ID of the Citus group.

-r / --role
Choose a member that has the given role.

Role can be one of:

  • leader: the leader of either a regular Patroni cluster or a standby Patroni cluster; or
  • primary: the leader of a regular Patroni cluster; or
  • standby-leader: the leader of a standby Patroni cluster; or
  • replica: a replica of a Patroni cluster; or
  • standby: same as replica; or
  • any: any role. Same as omitting this parameter.

-m / --member
Choose a member that has the given name.

MEMBER_NAME is the name of the member to be picked.

-d / --dbname
Database to connect and run the query.

DBNAME is the name of the database. If not given, defaults to USERNAME.

-U / --username
User to connect to the database.

USERNAME name of the user. If not given, defaults to the operating system user running patronictl query.

--password
Prompt for the password of the connecting user.

Patroni uses libpq. You can therefore supply a password through ~/.pgpass or PGPASSWORD.

--format
How to format the output of the query.

Format can be one of:

  • pretty: prints query output as a pretty table; or
  • tsv: prints query output as tabular information, with columns delimited by \t; or
  • json: prints query output in JSON format; or
  • yaml: prints query output in YAML format.

The default is tsv.

-f / --file
Use a file as source of commands to run queries.

FILE_NAME is the path to the source file.

-c / --command
Run the given SQL command in the query.

SQL_COMMAND is the SQL command to be executed.

--delimiter
The delimiter when printing information in tsv format, or \t if omitted.

-W
Automatically re-run the query every 2 seconds.

-w / --watch
Automatically re-run the query at the specified interval.

TIME is the interval between re-runs, in seconds.

Examples

Run a SQL command as postgres user, and ask for its password:

$ patronictl -c postgres0.yml query batman -U postgres --password -c "SELECT now()"
Password:
now
2023-09-12 18:10:53.228084+00:00

Run a SQL command as postgres user, and take password from libpq environment variable:

$ PGPASSWORD=patroni patronictl -c postgres0.yml query batman -U postgres -c "SELECT now()"
now
2023-09-12 18:11:37.639500+00:00

Run a SQL command and print in pretty format every 2 seconds:

$ patronictl -c postgres0.yml query batman -c "SELECT now()" --format pretty -W
+----------------------------------+
| now                              |
+----------------------------------+
| 2023-09-12 18:12:16.716235+00:00 |
+----------------------------------+
+----------------------------------+
| now                              |
+----------------------------------+
| 2023-09-12 18:12:18.732645+00:00 |
+----------------------------------+
+----------------------------------+
| now                              |
+----------------------------------+
| 2023-09-12 18:12:20.750573+00:00 |
+----------------------------------+

Run a SQL command on database test and print the output in YAML format:

$ patronictl -c postgres0.yml query batman -d test -c "SELECT now() AS column_1, 'test' AS column_2" --format yaml
- column_1: 2023-09-12 18:14:22.052060+00:00
  column_2: test

Run a SQL command on member postgresql2:

$ patronictl -c postgres0.yml query batman -m postgresql2 -c "SHOW port"
port
5434

Run a SQL command on any of the standbys:

$ patronictl -c postgres0.yml query batman -r replica -c "SHOW port"
port
5433

patronictl reinit

Synopsis

reinit
  CLUSTER_NAME
  [ MEMBER_NAME [, ... ] ]
  [ --group CITUS_GROUP ]
  [ --wait ]
  [ --force ]
  [ --from-leader ]

Description

patronictl reinit rebuilds a Postgres standby instance managed by a replica member of the Patroni cluster.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

MEMBER_NAME
Name of the replica member for which the Postgres instance will be rebuilt.

Multiple replica members can be specified. If no members are specified, the command does nothing.

--group
Rebuild a replica member of the given Citus group.

CITUS_GROUP is the ID of the Citus group.

--wait
Wait until the reinitialization of the Postgres standby node(s) is finished.

--force
Flag to skip confirmation prompts when rebuilding Postgres standby instances.

--from-leader
Flag to get basebackup from leader directly.

Useful for scripts.

Examples

Request a rebuild of all replica members of the Patroni cluster and immediately return control to the caller:

$ patronictl -c postgres0.yml reinit batman postgresql1 postgresql2 --force
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  5 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
Success: reinitialize for member postgresql1
Success: reinitialize for member postgresql2

Request a rebuild of postgresql2 and wait for it to complete:

$ patronictl -c postgres0.yml reinit batman postgresql2 --wait --force
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  5 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
Success: reinitialize for member postgresql2
Waiting for reinitialize to complete on: postgresql2
Reinitialize is completed on: postgresql2

Request a rebuild of postgresql2 and get basebackup from leader directly:

$ patronictl -c postgres0.yml reinit batman postgresql2 --from-leader
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  5 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
Success: reinitialize for member postgresql2

patronictl reload

Synopsis

reload
  CLUSTER_NAME
  [ MEMBER_NAME [, ... ] ]
  [ --group CITUS_GROUP ]
  [ { -r | --role } { leader | primary | standby-leader | replica | standby | any } ]
  [ --force ]

Description

patronictl reload requests a reload of local configuration for one or more Patroni members.

It also triggers pg_ctl reload on the managed Postgres instance, even if nothing has changed.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

MEMBER_NAME
Request a reload of local configuration for the given Patroni member(s).

Specify one or more members. If omitted, the command considers all members.

--group
Request a reload of members of the given Citus group.

CITUS_GROUP is the ID of the Citus group.

-r / --role
Select members that have the given role.

Role can be one of:

  • leader: the leader of either a regular Patroni cluster or a standby Patroni cluster; or
  • primary: the leader of a regular Patroni cluster; or
  • standby-leader: the leader of a standby Patroni cluster; or
  • replica: a replica of a Patroni cluster; or
  • standby: same as replica; or
  • any: any role. Same as omitting this parameter.

--force
Flag to skip confirmation prompts when requesting a reload of the local configuration.

Useful for scripts.

Examples

Request a reload of the local configuration of all members of the Patroni cluster:

$ patronictl -c postgres0.yml reload batman --force
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  5 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
Reload request received for member postgresql0 and will be processed within 10 seconds
Reload request received for member postgresql1 and will be processed within 10 seconds
Reload request received for member postgresql2 and will be processed within 10 seconds

patronictl remove

Synopsis

remove
  CLUSTER_NAME
  [ --group CITUS_GROUP ]
  [ { -f | --format } { pretty | tsv | json | yaml } ]

Description

patronictl remove removes information of the cluster from the DCS.

It is an interactive action.

Warning

This operation will destroy the information of the Patroni cluster from the DCS.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

--group
Remove information about the Patroni cluster related with the given Citus group.

CITUS_GROUP is the ID of the Citus group.

-f / --format
How to format the list of members in the output when prompting for confirmation.

Format can be one of:

  • pretty: prints members as a pretty table; or
  • tsv: prints members as tabular information, with columns delimited by \t; or
  • json: prints members in JSON format; or
  • yaml: prints members in YAML format.

The default is pretty.

Examples

Remove information about Patroni cluster batman from the DCS:

$ patronictl -c postgres0.yml remove batman
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  5 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  5 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
Please confirm the cluster name to remove: batman
You are about to remove all information in DCS for batman, please type: "Yes I am aware": Yes I am aware
This cluster currently is healthy. Please specify the leader name to continue: postgresql0

patronictl restart

Synopsis

restart
  CLUSTER_NAME
  [ MEMBER_NAME [, ...] ]
  [ --group CITUS_GROUP ]
  [ { -r | --role } { leader | primary | standby-leader | replica | standby | any } ]
  [ --any ]
  [ --pg-version PG_VERSION ]
  [ --pending ]
  [ --timeout TIMEOUT ]
  [ --scheduled TIMESTAMP ]
  [ --force ]

Description

patronictl restart requests a restart of the Postgres instance managed by a member of the Patroni cluster.

The restart can be performed immediately or scheduled for later.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

--group
Restart the Patroni cluster related with the given Citus group.

CITUS_GROUP is the ID of the Citus group.

-r / --role
Choose members that have the given role.

Role can be one of:

  • leader: the leader of either a regular Patroni cluster or a standby Patroni cluster; or
  • primary: the leader of a regular Patroni cluster; or
  • standby-leader: the leader of a standby Patroni cluster; or
  • replica: a replica of a Patroni cluster; or
  • standby: same as replica; or
  • any: any role. Same as omitting this parameter.

--any
Restart a single random node among the ones which match the given filters.

--pg-version
Select only members which version of the managed Postgres instance is older than the given version.

PG_VERSION is the Postgres version to be compared.

--pending
Select only members which are flagged as Pending restart.

--timeout: abort a restart that exceeds the timeout. If this occurs on the primary, fail over to a replica.

TIMEOUT is the amount of seconds to wait before aborting the restart.

--scheduled
Schedule a restart to occur at the given timestamp.

TIMESTAMP specifies restart time. Use an unambiguous format, preferably with a time zone. Use now for an immediate restart.

--force
Flag to skip confirmation prompts when requesting the restart operations.

Useful for scripts.

Examples

Restart all members of the cluster immediately:

$ patronictl -c postgres0.yml restart batman --force
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  6 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  6 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  6 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
Success: restart on member postgresql0
Success: restart on member postgresql1
Success: restart on member postgresql2

Restart a random member of the cluster immediately:

$ patronictl -c postgres0.yml restart batman --any --force
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  6 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  6 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  6 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
Success: restart on member postgresql1

Schedule a restart to occur at 2023-09-13T18:00-03:00:

$ patronictl -c postgres0.yml restart batman --scheduled 2023-09-13T18:00-03:00 --force
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  6 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  6 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  6 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
Success: restart scheduled on member postgresql0
Success: restart scheduled on member postgresql1
Success: restart scheduled on member postgresql2

patronictl resume

Synopsis

resume
  [ CLUSTER_NAME ]
  [ --group CITUS_GROUP ]
  [ --wait ]

Description

patronictl resume takes the Patroni cluster out of maintenance mode and re-enables automatic failover.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--group
Resume the given Citus group.

CITUS_GROUP is the ID of the Citus group.

If omitted, patronictl uses citus.group if configured.

--wait
Wait until all Patroni members are unpaused before returning control to the caller.

Examples

Put the cluster out of maintenance mode:

$ patronictl -c postgres0.yml resume batman --wait
'resume' request sent, waiting until it is recognized by all nodes
Success: cluster management is resumed

patronictl show-config

Synopsis

show-config
  [ CLUSTER_NAME ]
  [ --group CITUS_GROUP ]

Description

patronictl show-config shows the dynamic configuration of the cluster that is stored in the DCS.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--group
Show dynamic configuration of the given Citus group.

CITUS_GROUP is the ID of the Citus group.

If omitted, patronictl uses citus.group if configured.

Examples

Show dynamic configuration of cluster batman:

$ patronictl -c postgres0.yml show-config batman
loop_wait: 10
postgresql:
  parameters:
    max_connections: 250
  pg_hba:
  - host replication replicator 127.0.0.1/32 md5
  - host all all 0.0.0.0/0 md5
  use_pg_rewind: true
retry_timeout: 10
ttl: 30

patronictl switchover

Synopsis

switchover
  [ CLUSTER_NAME ]
  [ --group CITUS_GROUP ]
  [ { --leader | --primary } LEADER_NAME ]
  --candidate CANDIDATE_NAME
  [ --force ]

Description

patronictl switchover performs a switchover in the cluster.

Use this command when the cluster is healthy, for example:

  • There is a leader;
  • There are synchronous standbys available in a synchronous cluster.
Note

For an unhealthy cluster, consider patronictl failover.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--group
Perform a switchover in the given Citus group.

CITUS_GROUP is the ID of the Citus group.

--leader / --primary
Indicate who is the leader to be demoted at switchover time.

LEADER_NAME should match the name of the current leader in the cluster.

--candidate
The node to be promoted on switchover, and take the primary role.

CANDIDATE_NAME is the name of the node to be promoted.

--scheduled
Schedule a switchover to occur at the given timestamp.

TIMESTAMP specifies switchover time. Use an unambiguous format, preferably with a time zone. Use now for an immediate switchover.

--force
Flag to skip confirmation prompts when performing the switchover.

Useful for scripts.

Examples

Switch over with node postgresql2:

$ patronictl -c postgres0.yml switchover batman --leader postgresql0 --candidate postgresql2 --force
Current cluster topology
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  6 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  6 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  6 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
2023-09-13 14:15:23.07497 Successfully switched over to "postgresql2"
+ Cluster: batman (7277694203142172922) -+---------+----+-------------+---------+------------+---------+
| Member      | Host           | Role    | State   | TL | Receive LSN |     Lag | Replay LSN |     Lag |
+-------------+----------------+---------+---------+----+-------------+---------+------------+---------+
| postgresql0 | 127.0.0.1:5432 | Replica | stopped |    |     unknown | unknown |    unknown | unknown |
| postgresql1 | 127.0.0.1:5433 | Replica | running |  6 |   0/4000188 |       0 |  0/4000188 |       0 |
| postgresql2 | 127.0.0.1:5434 | Leader  | running |  6 |             |         |            |         |
+-------------+----------------+---------+---------+----+-------------+---------+------------+---------+

Schedule a switchover between postgresql0 and postgresql2 to occur at 2023-09-13T18:00:00-03:00:

$ patronictl -c postgres0.yml switchover batman --leader postgresql0 --candidate postgresql2 --scheduled 2023-09-13T18:00-03:00 --force
Current cluster topology
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  8 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  8 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  8 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
2023-09-13 14:18:11.20661 Switchover scheduled
+ Cluster: batman (7277694203142172922) -+-----------+----+-------------+-----+------------+-----+
| Member      | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0 | 127.0.0.1:5432 | Leader  | running   |  8 |             |     |            |     |
| postgresql1 | 127.0.0.1:5433 | Replica | streaming |  8 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| postgresql2 | 127.0.0.1:5434 | Replica | streaming |  8 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+-------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
Switchover scheduled at: 2023-09-13T18:00:00-03:00
                    from: postgresql0
                    to: postgresql2

patronictl topology

Synopsis

topology
  [ CLUSTER_NAME [, ... ] ]
  [ --group CITUS_GROUP ]
  [ { -W | { -w | --watch } TIME } ]

Description

patronictl topology shows cluster and member information as a tree.

The following information is included in the output:

Cluster
Name of the Patroni cluster.

Note

Shown in the table header.

System identifier
Postgres system identifier.

Note

Shown in the table header.

Member
Name of the Patroni member.

Note

Information in this column is shown as a tree view of members in terms of replication connections.

Host
Host where the member is located.

Role
Current role of the member.

Can be one among:

  • Leader: the current leader of a regular Patroni cluster; or
  • Standby Leader: the current leader of a Patroni standby cluster; or
  • Sync Standby: a synchronous standby of a Patroni cluster with synchronous mode enabled; or
  • Replica: a regular standby of a Patroni cluster.

State
Current state of Postgres in the Patroni member.

Some examples among the possible states:

  • running: if Postgres is currently up and running;
  • streaming: if a replica and Postgres is currently streaming WALs from the primary node;
  • in archive recovery: if a replica and Postgres is currently fetching WALs from the archive;
  • stopped: if Postgres had been shut down;
  • crashed: if Postgres has crashed.

TL
Current Postgres timeline in the Patroni member.

Receive LSN
Last WAL location received through streaming replication and synchronized to disk: pg_catalog.pg_last_(xlog|wal)_receive_(location|lsn)().

Receive Lag
Replication lag between the Receive LSN position of the member and its upstream in MB.

Replay LSN
Last WAL location replayed during member recovery: pg_catalog.pg_last_(xlog|wal)_replay_(location|lsn)().

Replay Lag
Replication lag between the Replay LSN position of the member and its upstream in MB.

Besides that, the following information may be included in the output:

Group
Citus group ID.

Note

Shown in the table header.

Only shown if a Citus cluster.

Pending restart
* indicates the node needs a restart for some Postgres configuration to take effect. An empty value indicates the node does not require a restart.

Note

Shown as a member attribute.

Shown if node requires a restart.

Scheduled restart
Scheduled restart time for the member’s Postgres instance. Empty if no restart is scheduled.

Note

Shown as a member attribute.

Shown if node has a scheduled restart.

Tags
Member tags. Empty if no tags are set or all tags have default values.

Note

Shown as a member attribute.

Shown if node has any custom tags, or any default tags with non-default values.

Scheduled switchover
Timestamp at which a switchover has been scheduled for the Patroni cluster, if any.

Note

Shown in the table footer.

Only shown if there is a scheduled switchover.

Maintenance mode

If the cluster monitoring is currently paused.

Note

Shown in the table footer.

Only shown if the cluster is paused.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

If omitted, patronictl uses scope if configured.

--group
Show information about members from the given Citus group.

CITUS_GROUP is the ID of the Citus group.

-W
Automatically refresh information every 2 seconds.

-w / --watch
Automatically refresh information at the specified interval.

TIME is the interval between refreshes, in seconds.

Examples

Show topology of the cluster batman – postgresql1 and postgresql2 are replicating from postgresql0:

$ patronictl -c postgres0.yml topology batman
+ Cluster: batman (7277694203142172922) ---+-----------+----+-------------+-----+------------+-----+
| Member        | Host           | Role    | State     | TL | Receive LSN | Lag | Replay LSN | Lag |
+---------------+----------------+---------+-----------+----+-------------+-----+------------+-----+
| postgresql0   | 127.0.0.1:5432 | Leader  | running   |  8 |             |     |            |     |
| + postgresql1 | 127.0.0.1:5433 | Replica | streaming |  8 |   0/40004E8 |   0 |  0/40004E8 |   0 |
| + postgresql2 | 127.0.0.1:5434 | Replica | streaming |  8 |   0/40004E8 |   0 |  0/40004E8 |   0 |
+---------------+----------------+---------+-----------+----+-------------+-----+------------+-----+

patronictl version

Synopsis

version
  [ CLUSTER_NAME [, ... ] ]
  [ MEMBER_NAME [, ... ] ]
  [ --group CITUS_GROUP ]

Description

patronictl version shows the patronictl version. It can also show versions for Patroni clusters and their members.

Parameters

CLUSTER_NAME
Name of the Patroni cluster.

MEMBER_NAME
Name of the member of the Patroni cluster.

--group
Consider a Patroni cluster with the given Citus group.

CITUS_GROUP is the ID of the Citus group.

Examples

Get version of patronictl only:

$ patronictl -c postgres0.yml version
patronictl version 4.0.0

Get version of patronictl and of all members of cluster batman:

$ patronictl -c postgres0.yml version batman
patronictl version 4.0.0

postgresql0: Patroni 4.0.0 PostgreSQL 16.4
postgresql1: Patroni 4.0.0 PostgreSQL 16.4
postgresql2: Patroni 4.0.0 PostgreSQL 16.4

Get version of patronictl and of members postgresql1 and postgresql2 of cluster batman:

$ patronictl -c postgres0.yml version batman postgresql1 postgresql2
patronictl version 4.0.0

postgresql1: Patroni 4.0.0 PostgreSQL 16.4
postgresql2: Patroni 4.0.0 PostgreSQL 16.4

6 - Replica imaging and bootstrap

Replica imaging, bootstrap, and custom replica creation workflows.

Source: https://patroni.readthedocs.io/en/latest/replica_bootstrap.html

Patroni supports custom replica creation and custom bootstrap for a new, empty cluster. These are separate operations. Patroni creates replicas only when the cluster has an initialize key in the DCS. Without that key, only the first node to acquire the initialize lock runs bootstrap.


Bootstrap

By default, Patroni initializes new clusters with PostgreSQL initdb. Some operations, such as copying an existing cluster, require a custom bootstrap method. Patroni can run a user-defined script and supply the cluster name and data directory. Configure this in the bootstrap section:

bootstrap:
    method: <custom_bootstrap_method_name>
    <custom_bootstrap_method_name>:
        command: <path_to_custom_bootstrap_script> [param1 [, ...]]
        keep_existing_recovery_conf: False
        no_params: False
        recovery_conf:
            recovery_target_action: promote
            recovery_target_timeline: latest
            restore_command: <method_specific_restore_command>

Each bootstrap method must define a name and a command. The special initdb method selects the default behavior. You can also omit method to use this default. Specify command as an absolute path or a path relative to the patroni command. In addition to fixed configuration parameters, Patroni supplies two cluster-specific arguments:

--scope
Name of the cluster to be bootstrapped

--datadir
Path to the data directory of the cluster instance to be bootstrapped

Set no_params to True to omit these two arguments.

If the script returns 0, Patroni tries to configure and start the PostgreSQL instance it created. Any intermediate failure or non-zero script result means bootstrap failed. Patroni cleans up and releases the initialize lock so another node can try bootstrap.

If the custom method includes recovery_conf, Patroni generates recovery.conf before it starts the new instance. On PostgreSQL >= 12, it sets recovery options in the Postgres configuration instead. Typically, specify at least one recovery_target_* parameter and set recovery_target_action to promote.

With keep_existing_recovery_conf set to True, Patroni keeps an existing recovery.conf on PostgreSQL <= 11. On PostgreSQL >= 12, it keeps existing recovery.signal and standby.signal files and does not override recovery settings. Use this with backup tools such as pgBackRest that generate recovery configuration.

Patroni passes additional key/value pairs from the custom method configuration to command as --name=value arguments. For example:

bootstrap:
    method: <custom_bootstrap_method_name>
    <custom_bootstrap_method_name>:
        command: <path_to_custom_bootstrap_script>
        arg1: value1
        arg2: value2

This adds --arg1=value1 --arg2=value2 when Patroni runs command.

Note

Patroni does not chain bootstrap methods. If the selected method fails, it does not fall back to the default method.

For example, bootstrap a new Patroni cluster from a Barman backup:

bootstrap:
    method: barman
    barman:
        keep_existing_recovery_conf: true
        command: patroni_barman --api-url https://barman-host:7480 recover
        barman-server: my_server
        ssh-command: ssh postgres@patroni-host
Note

Configure Barman and pg-backup-api on the Barman host before you use patroni_barman recover. It runs barman recover remotely through the backup API. The example shows only some available parameters. Run patroni_barman recover --help for details.


Building replicas

Patroni uses pg_basebackup to create replicas. This method requires a running leader. It has no backup compression during transfer or built-in cleanup of outdated backups. You may prefer WAL-E, pgBackRest, Barman, another backup tool, or a custom script. Patroni supports custom scripts to clone replicas. Configure them in the postgresql section:

postgresql:
    create_replica_methods:
        - <method name>
    <method name>:
        command: <command name>
        keep_data: True
        no_params: True
        no_leader: 1

example: wal_e

postgresql:
    create_replica_methods:
        - wal_e
        - basebackup
    wal_e:
        command: patroni_wale_restore
        no_leader: 1
        envdir: '{{WALE_ENV_DIR}}'
        use_iam: 1
    basebackup:
        max-rate: '100M'

example: pgbackrest

postgresql:
    create_replica_methods:
        - pgbackrest
        - basebackup
    pgbackrest:
        command: /usr/bin/pgbackrest --stanza=<scope> --delta restore
        keep_data: True
        no_params: True
    basebackup:
        max-rate: '100M'

example: Barman

postgresql:
    create_replica_methods:
        - barman
        - basebackup
    barman:
        command: patroni_barman --api-url https://barman-host:7480 recover
        barman-server: my_server
        ssh-command: ssh postgres@patroni-host
    basebackup:
        max-rate: '100M'
Note

Configure Barman and pg-backup-api on the Barman host before you use patroni_barman recover. It runs barman recover remotely through the backup API. The example shows only some available parameters. Run patroni_barman recover --help for details.

The create_replica_methods list specifies methods and their execution order. Patroni stops after the first method that returns 0. Give each method a separate configuration section with its command and custom parameters. Patroni passes parameters as --name=value arguments. In addition to custom parameters, it supplies these cluster-specific arguments:

--scope
Which cluster this replica belongs to

--datadir
Path to the data directory of the replica

--role
Always ‘replica’

--connstring
Connection string for the source cluster member, which can be the primary or another replica. The specified user can run SQL and replication protocol commands.

If no_leader is defined, Patroni can run the method without a running leader or replica. It passes an empty connection string. This permits restoration of a previous cluster from a binary backup.

If keep_data is defined, Patroni does not clean PGDATA before restore.

If no_params is defined, Patroni restricts parameters passed to the custom command.

The special basebackup method applies when create_replica_methods is empty. You can also list it explicitly. It initializes a replica with pg_basebackup. The backup source is the leader unless a replica has the clonefrom tag. If such replicas exist, Patroni selects one as the source.

No configuration is required, but you can add a basebackup section. As with other methods, specify only long options that start with –. Overriding the connection string or selecting tar or compressed backup output prevents Patroni from creating a replica. Patroni does not validate parameter names or values in basebackup.

If the WAL directory uses a symlink, specify the correct --waldir path. This preserves the symlink after replica creation or reinitialization. This option requires v10 or later.

Specify basebackup parameters as a key/value map or a list. Each list element can be a key/value pair or a single key for a valueless option, such as --verbose. For example:

postgresql:
    basebackup:
        max-rate: '100M'
        checkpoint: 'fast'

and

postgresql:
    basebackup:
        - verbose
        - max-rate: '100M'
        - waldir: /pg-wal-mount/external-waldir

If every method fails, Patroni retries them all in order during the next event loop cycle.

7 - Replication modes

Asynchronous and synchronous replication modes managed by Patroni.

Source: https://patroni.readthedocs.io/en/latest/replication_modes.html

Patroni uses PostgreSQL streaming replication. See the Postgres documentation. Patroni configures asynchronous replication by default. Select a replication design for your business requirements. Compare asynchronous replication, synchronous replication, and other HA solutions before you select one.


Asynchronous mode durability

Asynchronous mode permits some committed transaction loss to maintain availability. If the primary fails or becomes unavailable, Patroni automatically promotes a sufficiently healthy standby. Transactions absent from that standby remain on a forked timeline on the old primary. They are effectively unrecoverable1.

The maximum_lag_on_failover parameter controls potential transaction loss. Patroni does not sample the primary transaction log position in real time. The worst-case loss includes maximum_lag_on_failover bytes plus the log written during the last ttl seconds. The average additional interval is loop_wait/2 seconds. Typical replication delay in steady state is much less than one second.

By default, Patroni ignores replica timelines during leader elections. To require the same timeline as the former primary, set check_timeline to true. This prevents a replica on a different timeline from becoming leader.


PostgreSQL synchronous replication

Patroni supports Postgres synchronous replication. It confirms that a secondary has received writes before it returns success to the client. This maintains consistency across the cluster. It increases write latency and reduces write throughput. Throughput depends entirely on network performance.

On hosted networks, such as AWS or Rackspace, synchronous replication makes write performance much more variable. This also applies to other networks you do not control. If the leader cannot reach its replicas, it effectively becomes read-only.

For a simple synchronous replication test, add these lines to the parameters section of each YAML configuration file:

synchronous_commit: "on"
synchronous_standby_names: "*"

When using PostgreSQL synchronous replication, use at least three Postgres data nodes to ensure write availability if one host fails.

PostgreSQL synchronous replication does not always prevent transaction loss. If the primary and its synchronous replica fail together, Patroni promotes a third node. That node may lack some transactions.


Synchronous mode

If you cannot permit committed transaction loss, enable Patroni synchronous_mode. Patroni then promotes only a standby known to contain all transactions that may have returned successful commit status to clients2. Writes can become unavailable even while some servers remain available. Administrators can still promote a standby through manual failover, even if this loses transactions.

Synchronous mode does not always guarantee that commits are durable on multiple nodes. If no suitable standby exists, the primary still accepts writes without a replication guarantee. If the primary fails in this state, Patroni promotes no standby. When the former primary returns, Patroni promotes it automatically unless an administrator performed a manual failover. This behavior permits synchronous mode with two-node clusters.

With synchronous_mode, a standby crash blocks commits until the next Patroni iteration switches the primary to standalone mode. The worst-case write delay is ttl seconds; the average is loop_wait/2 seconds. Manual standby shutdowns and restarts do not interrupt commits. Before PostgreSQL shutdown, the standby tells the primary to release it from synchronous standby duties.

If each write must be durable on at least two nodes, also enable synchronous_mode_strict with synchronous_mode. Patroni then keeps synchronous replication enabled even if no synchronous standby candidate exists. Client writes block until at least one synchronous replica becomes available. A Postgres transaction that explicitly disables synchronous_commit is an exception.

When synchronous_mode_strict is enabled and no active replication connections satisfy the minimum replication factor, Patroni determines the value of synchronous_standby_names as follows:

  1. Last known sync nodes are available in the /sync key in DCS: Patroni uses the nodes stored there for synchronous_standby_names. For example, /sync may contain leader=node1, sync_standby=node2,node3. If both standbys stop streaming, Patroni continues to use:

    synchronous_standby_names = 'node2,node3'

    These nodes are the last ones known to have received the latest commit. Commits will block until at least one of them reconnects.

  2. Manual failover to an asynchronous node: A node outside /sync may be promoted, for example with patronictl failover --force. It sets synchronous_standby_names to the former primary. Only the former primary is guaranteed to have the latest committed data.

  3. The /sync key is empty: This can occur immediately after strict mode is enabled or after bootstrap without replicas. Patroni sets:

    synchronous_standby_names = '__patroni_strict_sync_replica_placeholder__'

    This sentinel value matches no real node name. Writes block until an eligible replica starts streaming from the primary. The placeholder replaces the old * wildcard, which could let an unqualified node satisfy the synchronous replication requirement.

Warning

The value __patroni_strict_sync_replica_placeholder__ is reserved by Patroni and must not be used as the name of a Patroni node in patroni.yaml. Patroni will refuse to start if this name is configured.

When strict mode is active, Patroni logs "No active replication connections and synchronous_mode_strict is requested. Commits will be delayed." It logs this warning once per activation, not on each HA loop iteration.

To prevent a standby from becoming synchronous, set its nosync tag to true. We recommend this for standbys on slow networks that would reduce synchronous replication performance. Setting nostream to true has the same effect.

Enable or disable synchronous mode with patronictl edit-config or the Patroni REST interface. See dynamic configuration.

Note: PostgreSQL synchronous replication can lose transactions even with synchronous_mode_strict. A backend can be cancelled while it waits for replication acknowledgment, through client timeout cancellation or backend failure. Its transaction changes then become visible to other backends before replication completes. These changes can be lost if a standby is promoted.


Synchronous Replication Factor

The synchronous_node_count parameter specifies the number of synchronous standbys. Its default is 1. It has no effect when synchronous_mode is off. Otherwise, Patroni updates DCS state and PostgreSQL synchronous_standby_names as members join or leave. If the configured count exceeds the number of eligible nodes, Patroni reduces it automatically.


Maximum lag on synchronous node

By default, Patroni retains nodes marked synchronous in pg_stat_replication, even if other nodes are ahead. This minimizes changes to synchronous_standby_names. Set maximum_lag_on_syncnode to change this behavior. It limits the replication lag permitted for a synchronous node.

With multiple standbys, Patroni uses the maximum replica LSN. With one standby, it uses the leader’s current WAL LSN. The default is -1. Values of 0 or less prevent Patroni from replacing an unhealthy synchronous standby. Use a sufficiently high value to avoid frequent replacements during high transaction volume.


Synchronous mode implementation

In synchronous mode, Patroni stores the latest primary and current synchronous standbys in the DCS /sync key. Strict update ordering maintains these invariants:

  • A node that can accept writes must be marked as the latest leader. Patroni crashes or PostgreSQL shutdown failures can violate this invariant.
  • A node listed as synchronous in the DCS /sync key must remain a synchronous standby in PostgreSQL.
  • Only the leader or a current synchronous standby can promote itself automatically.

Patroni assigns one or more synchronous standbys to synchronous_standby_names, according to synchronous_node_count.

Each HA loop iteration reevaluates synchronous standby selection. Connected synchronous standbys remain selected unless they request removal of synchronous status. Otherwise, Patroni selects eligible members that are furthest ahead in replication.

Example:

/config key in DCS

synchronous_mode: on
synchronous_node_count: 2
...

/sync key in DCS

{
    "leader": "node0",
    "sync_standby": "node1,node2"
}

postgresql.conf

synchronous_standby_names = 'FIRST 2 (node1,node2)'

In these examples, only node1 and node2 are known synchronous nodes. Only these nodes can be promoted automatically if the primary, node0, fails.


Quorum commit mode

Starting from PostgreSQL v10 Patroni supports quorum-based synchronous replication.

In this mode, Patroni stores synchronization state in the DCS. This includes the latest known primary, the quorum requirement, and eligible voters. In steady state, the voters are the leader and all synchronous standbys. Strict update ordering coordinates promotions and synchronous_standby_names. This guarantees that every subset of voters sufficient for quorum always includes a node with the latest successful commit.

Each HA loop iteration reevaluates synchronous standbys and quorum from node availability and requested cluster configuration. On PostgreSQL versions above 9.6, all eligible nodes become synchronous standbys as soon as they catch up to the leader.

Quorum commit reduces worst-case latency, including during normal operation. Other standbys can compensate for slow replication to one standby.

To enable quorum mode, set synchronous_mode to quorum with patronictl edit-config or the REST interface. See dynamic configuration.

Other parameters, like synchronous_node_count, maximum_lag_on_syncnode, and synchronous_mode_strict continue to work the same way as with synchronous_mode=on.

With quorum commit and synchronous_mode_strict, Patroni preserves the last known /sync voters when no active replica exists. It sets synchronous_standby_names to ANY N (<last known voters>). If /sync has no voters, it uses ANY 1 (__patroni_strict_sync_replica_placeholder__).

Example:

/config key in DCS

synchronous_mode: quorum
synchronous_node_count: 2
...

/sync key in DCS

{
    "leader": "node0",
    "sync_standby": "node1,node2,node3",
    "quorum": 1
}

postgresql.conf

synchronous_standby_names = 'ANY 2 (node1,node2,node3)'

If node0 fails in this example, two of node1, node2, and node3 have received the latest transaction. We do not know which two. To evaluate node1, compare its LSN with at least one of node2 or node3. This corresponds to quorum=1 in /sync. If node1 is not behind at least one of them, its promotion guarantees no user-visible data loss.


  1. The data remains, but data recovery specialists must recover it manually. With use_pg_rewind, Patroni automatically erases the forked timeline when the failed primary rejoins. For correct operation, use_pg_rewind requires data page checksums and/or wal_log_hints set to on. Enable checksums with the --data-checksums option for initdb. ↩︎

  2. Clients can change each transaction’s behavior with synchronous_commit. Values of off and local avoid replication delays but permit transaction loss on failover. ↩︎

8 - Standby cluster

Standby cluster setup, behavior, and replication from remote primary.

Source: https://patroni.readthedocs.io/en/latest/standby_cluster.html

Patroni supports cascading replication to a remote datacenter or region through the standby cluster feature. A standby cluster has:

  • A standby leader, which behaves like a regular cluster leader but replicates from a remote node.
  • Cascade replicas, which replicate from the standby leader.

The standby leader holds and updates a leader lock in the DCS. If the lock expires, the cascade replicas elect another leader from the standbys.

The standby and primary clusters share only replication information. If they use the same DCS, they must use different DCS scopes. The primary cluster does not show the standby cluster in patronictl_list or patronictl_topology output.

Use create_replica_methods in the standby_cluster section to specify replica creation and WAL recovery methods in standby mode. After the cluster detaches and operates normally, replica creation uses create_replica_methods in the postgresql section. Both standby and normal create_replica_methods refer to keys in the postgresql section.

To configure a standby cluster, add a standby_cluster section to the Patroni configuration:

bootstrap:
    dcs:
        standby_cluster:
            host: 1.2.3.4
            port: 5432
            primary_slot_name: patroni
            create_replica_methods:
            - basebackup

These options apply only during cluster bootstrap. After bootstrap, change them through the DCS.

Patroni expects postgresql.conf or postgresql.conf.backup in PGDATA on the remote primary. It will not start if this file is missing after a basebackup. If the primary stores postgresql.conf elsewhere, copy it to PGDATA.

If the standby cluster uses replication slots, create the corresponding slot on the primary cluster. The standby cluster does not create it automatically. You can use permanent replication slots on the primary cluster to maintain it. Use the name from primary_slot_name, or its default if you did not set primary_slot_name.

If the remote site has no single primary endpoint, list all source cluster hosts in standby_cluster.host. For multiple comma-separated hosts, Patroni will:

  • Add target_session_attrs=read-write to primary_conninfo on the standby leader.
  • Use target_session_attrs=read-write when it checks whether pg_rewind is necessary or runs pg_rewind on any standby cluster node.
  • Require data page checksums and/or wal_log_hints set to on for successful pg_rewind operation. Enable checksums with the --data-checksums option for initdb. Otherwise, pg_rewind cannot operate correctly.

To replicate from another standby cluster or a standby member of the primary cluster, specify one host in standby_cluster.host. However, pg_rewind will fail on the standby cluster in this configuration.

Warning

Member names must be unique across the primary cluster and all connected standby clusters. Set each member name in the name field of its Patroni configuration.

Patroni sets synchronous_standby_names on the primary with member names. These names also become the application_name of each replication connection in pg_stat_replication. Duplicate names create two connections with identical application_name values. PostgreSQL can then use a standby cluster connection to satisfy synchronous replication instead of the intended primary cluster member. It can acknowledge synchronous commits before transactions are durable on the correct standby.

This failure is silent: replication continues and logs contain no errors. The cluster effectively has no valid synchronous standby. Data loss can occur if the primary fails.

9 - Watchdog support

Watchdog integration and fencing considerations for Patroni clusters.

Source: https://patroni.readthedocs.io/en/latest/watchdog.html

Multiple PostgreSQL primaries can lose transactions because their timelines diverge. This is called split-brain. Patroni must prevent PostgreSQL from accepting transaction commits after the leader key expires in the DCS. Normally, Patroni stops PostgreSQL if the leader lock update fails for any reason. This protection can fail for these reasons:

  • Patroni crashes because of a bug, insufficient memory, or an accidental kill by a system administrator.
  • PostgreSQL shutdown takes too long.
  • System load, a VM pause by the hypervisor, or other infrastructure problems prevent Patroni from running.

Patroni supports watchdog devices to guarantee correct behavior under these conditions. A software or hardware watchdog resets the whole system if it receives no keepalive heartbeat within a specified time. This adds protection if the usual Patroni split-brain controls fail.

Patroni tries to activate the watchdog before it promotes PostgreSQL to primary. If activation fails and watchdog mode is required, the node refuses to become leader. Before it enters a leader election, Patroni checks whether the watchdog configuration permits it to become leader. After it demotes PostgreSQL, for example during manual failover, Patroni disables the watchdog. Patroni also disables the watchdog while paused.

By default, the watchdog expires 5 seconds before the TTL. With loop_wait=10 and ttl=30, the HA loop has at least 15 seconds before a forced reset. This interval is ttl - safety_margin - loop_wait. DCS access times out after 10 seconds by default. If the DCS is unavailable, for example because of network problems, Patroni and PostgreSQL have at least 5 seconds to terminate all client connections. This interval is ttl - safety_margin - loop_wait - retry_timeout.

The safety margin reserves time between a leader key update and a watchdog keepalive. Patroni tries to send the keepalive immediately after the DCS confirms the update. A long process suspension at this point can delay the keepalive beyond the safety margin without triggering the watchdog. The watchdog can then expire after the leader key, which invalidates the guarantee.

To guarantee watchdog expiration under all conditions, set safety_margin to -1. This sets the watchdog timeout to half the TTL: ttl // 2. If you need this guarantee, you probably should increase ttl and/or reduce loop_wait and retry_timeout.

Currently, Patroni supports only the Linux watchdog device interface.


Setting up software watchdog on Linux

On Linux, the default configuration tries to use /dev/watchdog if Patroni can access it. The Linux kernel software watchdog is sufficiently secure for most use cases.

Before you start Patroni, run these commands as root to enable the software watchdog:

modprobe softdog
# Replace postgres with the user you will be running patroni under
chown postgres /dev/watchdog

For tests, add soft_noboot=1 to the modprobe command to disable reboots. The watchdog then only writes to the kernel ring buffer. Use dmesg to read the message.

Patroni logs watchdog information after it enables the watchdog successfully.

10 - Pause/Resume mode for the cluster

Pause and resume mode behavior for Patroni cluster management.

Source: https://patroni.readthedocs.io/en/latest/pause.html


The goal

Patroni sometimes needs to suspend cluster management while it retains cluster state in the DCS. Examples include major version upgrades and corruption recovery. During these operations, nodes often start and stop for reasons that Patroni does not know. Temporary promotions can also violate the assumption that only one primary runs. Pause mode lets Patroni detach from the running cluster, like maintenance mode in Pacemaker.


The implementation

In pause mode, Patroni does not change PostgreSQL state, with these exceptions:

  • Patroni updates each node’s member key in the DCS with current cluster information. It runs read-only queries on each running member.
  • Patroni updates the leader lock for the Postgres primary that holds it. If that node is manually demoted, Patroni releases the lock instead of promoting the node again.
  • Manual unscheduled restarts, failovers, switchovers, and reinitialization are allowed. Scheduled actions are not allowed. A manual switchover must specify the target node.
  • If Patroni detects multiple primaries, it logs a warning. It does not demote a primary that lacks the leader lock.
  • If the cluster has no leader lock, a running primary acquires it. With multiple primaries, the first to acquire the lock wins. With no primary, Patroni does not promote a replica. One exception applies if the old primary released the lock by demoting itself for a manual promotion. Only the candidate named in that request may acquire the lock. After a new leader acquires the lock, Patroni redirects replicas from the previous leader to the new leader.
  • Patroni does not start a stopped Postgres instance. When Patroni stops, it does not stop the Postgres instance that it manages.
  • Patroni does not remove replication slots that do not represent another cluster member or are absent from the permanent slot configuration.

User guide

patronictl supports pause and resume commands.

You can also send a PATCH request to {namespace}/{cluster}/config with {"pause": true/false/null}.

11 - DCS Failsafe Mode

DCS failsafe mode behavior, requirements, and operational caveats.

Source: https://patroni.readthedocs.io/en/latest/dcs_failsafe_mode.html


The problem

Patroni uses the Distributed Configuration Store (DCS) for leader elections and network partition detection. A node can run Postgres as primary only if it can update the DCS leader lock. If the update fails, Patroni immediately demotes Postgres and starts it read-only. Failure frequency depends on the DCS. It is close to zero with Etcd dedicated to Patroni, but can be higher with the Etcd-backed K8s API.


Reasons for the current implementation

The leader lock update failure could be caused by two main reasons:

  1. Network partitioning
  2. DCS being down

A single node generally cannot distinguish these two causes. Patroni therefore assumes a network partition, the worst case. Other cluster nodes may acquire the leader lock and promote Postgres in a network partition. To prevent split-brain, Patroni demotes the old primary before the lock expires.


DCS Failsafe Mode

Enable failsafe_mode only through global dynamic configuration in the DCS /config key. In failsafe mode, a primary may continue after a leader lock update fails for reasons other than a version/value/index mismatch. It must be able to contact every known cluster member through the Patroni REST API.


Low-level implementation details

  • The DCS has a permanent /failsafe key.
  • This key contains all known members of the Patroni cluster at a given time.
  • The current leader maintains the /failsafe key.
  • A member can enter a leader race and become leader only if it is in the /failsafe key.
  • For a single-node cluster, the /failsafe key contains one member.
  • During a DCS outage, the primary contacts all members in /failsafe through the POST /failsafe REST API. It may remain primary if all replicas acknowledge it.
  • If any member does not respond, Patroni demotes the primary.
  • Replicas use incoming POST /failsafe requests to confirm that the primary is alive. They cache this information for ttl seconds.

F.A.Q.

  • Why MUST the current primary see ALL other members? Can’t we rely on quorum here?

    The DCS and Patroni can have different quorum views. DCS nodes must be distributed evenly across availability zones. Patroni has no equivalent rule or mechanism to enforce one. Most Patroni nodes, including the primary, could occupy the losing network partition while a minority occupies the winning partition. The primary must then be demoted. Only a check of ALL other members detects this case.

  • What if node/pod gets terminated while DCS is down?

    While the DCS is inaccessible, Patroni checks all other members every heartbeat cycle, or loop_wait seconds. If a node or pod terminates, the check fails. Patroni demotes Postgres to read-only. It cannot recover until DCS access returns.

  • What if all members of the Patroni cluster are lost while DCS is down?

    You can configure Patroni to create replicas from backup without a cluster leader. However, a new member absent from /failsafe cannot acquire the leader lock or promote.

  • What will happen if the primary lost access to DCS while replicas didn’t?

    The primary runs the failsafe code and contacts all known replicas. The replicas use this contact to confirm that the primary is alive. They do not start a leader race, even if the DCS leader lock expires.

  • How to enable the Failsafe Mode?

    Before you enable failsafe_mode, make sure all members have an up-to-date Patroni version. Then use the PATCH /config REST API or patronictl edit-config -s failsafe_mode=true.

12 - Using Patroni with Kubernetes

Using Patroni with Kubernetes objects, labels, and service discovery.

Source: https://patroni.readthedocs.io/en/latest/kubernetes.html

Patroni can store cluster state and the leader key in Kubernetes objects. This lets it run Postgres in Kubernetes without a separate consistency store, such as an extra Etcd deployment. Patroni supports two object types for the leader and configuration keys. Select the type with kubernetes.use_endpoints or the PATRONI_KUBERNETES_USE_ENDPOINTS environment variable.


Use Endpoints

This mode is recommended but disabled by default for compatibility. When enabled, Patroni creates Endpoints and stores cluster configuration and the leader key in their metadata: annotations fields. A leader change updates both the leader annotations and the addresses of the leader pod in one operation. This is safer than ConfigMaps.


Use ConfigMaps

In this mode, Patroni creates ConfigMaps and stores keys in their metadata. A leader change needs at least two updates: one for the leader ConfigMap and one for its Endpoint.

To route traffic to the Postgres leader, configure the Kubernetes Postgres service label selector with role_label from the Patroni configuration.

Some environments, such as OpenShift, require ConfigMaps.


Configuration

Patroni Kubernetes settings and environment variables are described in the general chapters of the documentation.

Customize role label

By default, Patroni labels its pod with the node role, such as role=primary. Customize the label key and values with kubernetes.role_label, kubernetes.leader_label_value, kubernetes.follower_label_value, and kubernetes.standby_leader_label_value.

To reduce downtime when you change default role labels to custom labels, use these steps:

  1. Set kubernetes.tmp_role_label to a temporary label, such as tmp_role, with the original role value. After the pods restart, Patroni sets these labels:
labels:
  cluster-name: foo
  role: primary
  tmp_role: primary
  1. After all pods have been updated, modify the service selector to select the temporary label.
selector:
  cluster-name: foo
  tmp_role: primary
  1. Add the custom role label, for example kubernetes.leader_label_value=primary. After the pods restart, Patroni sets these labels:
labels:
  cluster-name: foo
  role: primary
  tmp_role: primary
  1. After all pods have been updated again, modify the service selector to use new role value.
selector:
  cluster-name: foo
  role: primary
  1. Finally, remove the temporary label from your configuration and update all pods.
labels:
  cluster-name: foo
  role: primary

Examples

  • The kubernetes directory contains an example Docker image and Kubernetes manifest for tests. The current example cannot use PersistentVolumes because of permission problems.
  • The Spilo Project provides a full-featured Docker image with Persistent Volume support.
  • A Helm chart deploys the Spilo image with Patroni configured to run in Kubernetes.
  • For Patroni and Spilo clusters at scale, see postgres-operator. It uses the operator pattern to manage Spilo clusters.

13 - Citus support

Patroni integration details for Citus coordinator and worker groups.

Source: https://patroni.readthedocs.io/en/latest/citus.html

Patroni automates deployment of Multi-Node Citus clusters.


TL;DR

Apply these rules:

  1. Install the Citus PostgreSQL extension on every node. The minimum supported version is 10.0. We recommend at least 11.2 for transparent worker switchovers and restarts.
  2. Use the same cluster name (scope) on all Citus nodes.
  3. Use the same superuser credentials on the coordinator and all workers. Configure pg_hba.conf to permit superuser access between all nodes.
  4. Permit worker access to the coordinator REST API. Use the same credentials. If client certificates are configured, the coordinator must accept worker certificates.
  5. Add this section to patroni.yaml:
citus:
  group: X  # 0 for coordinator and 1, 2, 3, etc for workers
  database: citus  # must be the same on all nodes

Then start Patroni. It performs these operations:

  1. Set bootstrap.dcs.synchronous_mode to quorum, unless you explicitly set another value.
  2. Add the citus extension to shared_preload_libraries.
  3. Set max_prepared_transactions to 2*max_connections, unless it is explicitly set in dynamic configuration.
  4. Change citus.local_hostname from localhost to the address Patroni uses for local PostgreSQL connections. PostgreSQL might not listen on localhost.
  5. Create citus.database, then run CREATE EXTENSION citus.
  6. Add current superuser credentials to pg_dist_authinfo for cross-node communication. Update them if you later change the superuser username, password, sslcert, or sslkey.
  7. On the coordinator primary, discover worker primaries and add them to pg_dist_node with citus_add_node().
  8. Maintain pg_dist_node after failover or switchover in coordinator or worker clusters.

patronictl

Coordinator and worker clusters are separate PostgreSQL/Patroni clusters. Citus groups them logically. Most operations therefore cannot manage them as one entity.

A citus section in patroni.yaml changes patronictl behavior in two ways:

  1. By default, list and topology show all coordinators and workers in the Citus formation. The Group column identifies their Citus groups.
  2. patronictl commands accept --group. Some use a default from patroni.yaml. For example, patronictl_pause defaults to group in the citus section. patronictl_switchover and patronictl_remove require an explicit group.

An example of patronictl_list output for the Citus cluster:

postgres@coord1:~$ patronictl list demo
+ Citus cluster: demo ----------+----------------+---------+----+-------------+-----+------------+-----+
| Group | Member  | Host        | Role           | State   | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------+---------+-------------+----------------+---------+----+-------------+-----+------------+-----+
|     0 | coord1  | 172.27.0.10 | Replica        | running |  1 |   0/41C0368 |   0 |  0/41C0368 |   0 |
|     0 | coord2  | 172.27.0.6  | Quorum Standby | running |  1 |   0/41C0368 |   0 |  0/41C0368 |   0 |
|     0 | coord3  | 172.27.0.4  | Leader         | running |  1 |             |     |            |     |
|     1 | work1-1 | 172.27.0.8  | Quorum Standby | running |  1 |   0/31D3198 |   0 |  0/31D3198 |   0 |
|     1 | work1-2 | 172.27.0.2  | Leader         | running |  1 |             |     |            |     |
|     2 | work2-1 | 172.27.0.5  | Quorum Standby | running |  1 |   0/31CDFC0 |   0 |  0/31CDFC0 |   0 |
|     2 | work2-2 | 172.27.0.7  | Leader         | running |  1 |             |     |            |     |
+-------+---------+-------------+----------------+---------+----+-------------+-----+------------+-----+

If we add the --group option, the output will change to:

postgres@coord1:~$ patronictl list demo --group 0
+ Citus cluster: demo (group: 0, 7179854923829112860) -+-------------+-----+------------+-----+
| Member | Host        | Role           | State   | TL | Receive LSN | Lag | Replay LSN | Lag |
+--------+-------------+----------------+---------+----+-------------+-----+------------+-----+
| coord1 | 172.27.0.10 | Replica        | running |  1 |   0/41C0368 |   0 |  0/41C0368 |   0 |
| coord2 | 172.27.0.6  | Quorum Standby | running |  1 |   0/41C0368 |   0 |  0/41C0368 |   0 |
| coord3 | 172.27.0.4  | Leader         | running |  1 |             |     |            |     |
+--------+-------------+----------------+---------+----+-------------+-----+------------+-----+

postgres@coord1:~$ patronictl list demo --group 1
+ Citus cluster: demo (group: 1, 7179854923881963547) -+-------------+-----+------------+-----+
| Member  | Host       | Role           | State   | TL | Receive LSN | Lag | Replay LSN | Lag |
+---------+------------+----------------+---------+----+-------------+-----+------------+-----+
| work1-1 | 172.27.0.8 | Quorum Standby | running |  1 |   0/31D3198 |   0 |  0/31D3198 |   0 |
| work1-2 | 172.27.0.2 | Leader         | running |  1 |             |     |            |     |
+---------+------------+----------------+---------+----+-------------+-----+------------+-----+

Citus worker switchover

Citus can make an orchestrated worker switchover nearly transparent to applications. Applications connect to the coordinator, which connects to workers. Citus can pause coordinator SQL traffic for the shards on the affected worker. The coordinator holds this traffic during switchover. Traffic resumes when the new worker primary can accept read/write queries.

An example of patronictl_switchover on the worker cluster:

postgres@coord1:~$ patronictl switchover demo
+ Citus cluster: demo ----------+----------------+---------+----+-------------+-----+------------+-----+
| Group | Member  | Host        | Role           | State   | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------+---------+-------------+----------------+---------+----+-------------+-----+------------+-----+
|     0 | coord1  | 172.27.0.10 | Replica        | running |  1 |   0/41C0368 |   0 |  0/41C0368 |   0 |
|     0 | coord2  | 172.27.0.6  | Quorum Standby | running |  1 |   0/41C0368 |   0 |  0/41C0368 |   0 |
|     0 | coord3  | 172.27.0.4  | Leader         | running |  1 |             |     |            |     |
|     1 | work1-1 | 172.27.0.8  | Leader         | running |  1 |             |     |            |     |
|     1 | work1-2 | 172.27.0.2  | Quorum Standby | running |  1 |   0/31D3198 |   0 |  0/31D3198 |   0 |
|     2 | work2-1 | 172.27.0.5  | Quorum Standby | running |  1 |   0/31CDFC0 |   0 |  0/31CDFC0 |   0 |
|     2 | work2-2 | 172.27.0.7  | Leader         | running |  1 |             |     |            |     |
+-------+---------+-------------+----------------+---------+----+-------------+-----+------------+-----+
Citus group: 2
Primary [work2-2]:
Candidate ['work2-1'] []:
When should the switchover take place (e.g. 2024-08-26T08:02 )  [now]:
Current cluster topology
+ Citus cluster: demo (group: 2, 7179854924063375386) -+-------------+-----+------------+-----+
| Member  | Host       | Role           | State   | TL | Receive LSN | Lag | Replay LSN | Lag |
+---------+------------+----------------+---------+----+-------------+-----+------------+-----+
| work2-1 | 172.27.0.5 | Quorum Standby | running |  1 |   0/31CDFC0 |   0 |  0/31CDFC0 |   0 |
| work2-2 | 172.27.0.7 | Leader         | running |  1 |             |     |            |     |
+---------+------------+----------------+---------+----+-------------+-----+------------+-----+
Are you sure you want to switchover cluster demo, demoting current primary work2-2? [y/N]: y
2024-08-26 07:02:40.33003 Successfully switched over to "work2-1"
+ Citus cluster: demo (group: 2, 7179854924063375386) --------+---------+------------+---------+
| Member  | Host       | Role    | State   | TL | Receive LSN |     Lag | Replay LSN |     Lag |
+---------+------------+---------+---------+----+-------------+---------+------------+---------+
| work2-1 | 172.27.0.5 | Leader  | running |  1 |             |         |            |         |
| work2-2 | 172.27.0.7 | Replica | stopped |    |     unknown | unknown |    unknown | unknown |
+---------+------------+---------+---------+----+-------------+---------+------------+---------+

postgres@coord1:~$ patronictl list demo
+ Citus cluster: demo ----------+----------------+---------+----+-------------+-----+------------+-----+
| Group | Member  | Host        | Role           | State   | TL | Receive LSN | Lag | Replay LSN | Lag |
+-------+---------+-------------+----------------+---------+----+-------------+-----+------------+-----+
|     0 | coord1  | 172.27.0.10 | Replica        | running |  1 |   0/41C0368 |   0 |  0/41C0368 |   0 |
|     0 | coord2  | 172.27.0.6  | Quorum Standby | running |  1 |   0/41C0368 |   0 |  0/41C0368 |   0 |
|     0 | coord3  | 172.27.0.4  | Leader         | running |  1 |             |     |            |     |
|     1 | work1-1 | 172.27.0.8  | Leader         | running |  1 |             |     |            |     |
|     1 | work1-2 | 172.27.0.2  | Quorum Standby | running |  1 |   0/31D3198 |   0 |  0/31D3198 |   0 |
|     2 | work2-1 | 172.27.0.5  | Leader         | running |  2 |             |     |            |     |
|     2 | work2-2 | 172.27.0.7  | Quorum Standby | running |  2 |   0/31CDFC0 |   0 |  0/31CDFC0 |   0 |
+-------+---------+-------------+----------------+---------+----+-------------+-----+------------+-----+

And this is how it looks on the coordinator side:

# The worker primary notifies the coordinator that it is going to execute "pg_ctl stop".
2024-08-26 07:02:38,636 DEBUG: query(BEGIN, ())
2024-08-26 07:02:38,636 DEBUG: query(SELECT pg_catalog.citus_update_node(%s, %s, %s, true, %s), (3, '172.19.0.7-demoted', 5432, 10000))
# From this moment all application traffic on the coordinator to the worker group 2 is paused.

# The old worker primary is assigned as a secondary.
2024-08-26 07:02:40,084 DEBUG: query(SELECT pg_catalog.citus_update_node(%s, %s, %s, true, %s), (7, '172.19.0.7', 5432, 10000))

# The future worker primary notifies the coordinator that it acquired the leader lock in DCS and about to run "pg_ctl promote".
2024-08-26 07:02:40,085 DEBUG: query(SELECT pg_catalog.citus_update_node(%s, %s, %s, true, %s), (3, '172.19.0.5', 5432, 10000))

# The new worker primary just finished promote and notifies coordinator that it is ready to accept read-write traffic.
2024-08-26 07:02:41,485 DEBUG: query(COMMIT, ())
# From this moment the application traffic on the coordinator to the worker group 2 is unblocked.

Secondary nodes

Since Patroni v4.0.0, Citus secondary nodes without the noloadbalance tag are also registered in pg_dist_node. To use them for read-only queries, applications must change citus.use_secondary_nodes.


Peek into DCS

The Citus cluster (coordinator and workers) are stored in DCS as a fleet of Patroni clusters logically grouped together:

/service/batman/              # scope=batman
/service/batman/0/            # citus.group=0, coordinator
/service/batman/0/initialize
/service/batman/0/leader
/service/batman/0/members/
/service/batman/0/members/m1
/service/batman/0/members/m2
/service/batman/1/            # citus.group=1, worker
/service/batman/1/initialize
/service/batman/1/leader
/service/batman/1/members/
/service/batman/1/members/m3
/service/batman/1/members/m4
...

Most DCS implementations can read the whole Citus cluster with one recursive request using this structure. Only coordinators read the whole tree, to discover workers. Workers read their own group subtree and, in some cases, the coordinator subtree.


Citus on Kubernetes

Kubernetes does not support hierarchical structures. Patroni therefore includes the Citus group in every Kubernetes object name:

batman-0-leader  # the leader config map for the coordinator
batman-0-config  # the config map holding initialize, config, and history "keys"
...
batman-1-leader  # the leader config map for worker group 1
batman-1-config
...

The naming pattern is ${scope}-${citus.group}-${type}.

Patroni discovers Kubernetes objects with a label selector. All Patroni/Citus Pods and Endpoints/ConfigMaps must have matching labels. Configure Patroni to use these labels through Kubernetes settings or environment variables <kubernetes_environment>.

A couple of examples of Patroni configuration using Pods environment variables:

  1. for the coordinator cluster
apiVersion: v1
kind: Pod
metadata:
  labels:
    application: patroni
    citus-group: "0"
    citus-type: coordinator
    cluster-name: citusdemo
  name: citusdemo-0-0
  namespace: default
spec:
  containers:
  - env:
    - name: PATRONI_SCOPE
      value: citusdemo
    - name: PATRONI_NAME
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: metadata.name
    - name: PATRONI_KUBERNETES_POD_IP
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: status.podIP
    - name: PATRONI_KUBERNETES_NAMESPACE
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: metadata.namespace
    - name: PATRONI_KUBERNETES_LABELS
      value: '{application: patroni}'
    - name: PATRONI_CITUS_DATABASE
      value: citus
    - name: PATRONI_CITUS_GROUP
      value: "0"
  1. for the worker cluster from the group 2
apiVersion: v1
kind: Pod
metadata:
  labels:
    application: patroni
    citus-group: "2"
    citus-type: worker
    cluster-name: citusdemo
  name: citusdemo-2-0
  namespace: default
spec:
  containers:
  - env:
    - name: PATRONI_SCOPE
      value: citusdemo
    - name: PATRONI_NAME
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: metadata.name
    - name: PATRONI_KUBERNETES_POD_IP
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: status.podIP
    - name: PATRONI_KUBERNETES_NAMESPACE
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: metadata.namespace
    - name: PATRONI_KUBERNETES_LABELS
      value: '{application: patroni}'
    - name: PATRONI_CITUS_DATABASE
      value: citus
    - name: PATRONI_CITUS_GROUP
      value: "2"

Both examples set the citus-group label to identify the object’s Citus group. They set PATRONI_CITUS_GROUP to the same value. Patroni automatically adds citus-group: ${env.PATRONI_CITUS_GROUP} to new ConfigMaps and Endpoints:

apiVersion: v1
kind: ConfigMap
metadata:
  name: citusdemo-0-leader  # Is generated as ${env.PATRONI_SCOPE}-${env.PATRONI_CITUS_GROUP}-leader
  labels:
    application: patroni    # Is set from the ${env.PATRONI_KUBERNETES_LABELS}
    cluster-name: citusdemo # Is automatically set from the ${env.PATRONI_SCOPE}
    citus-group: '0'        # Is automatically set from the ${env.PATRONI_CITUS_GROUP}

See the kubernetes directory for a complete Patroni/Citus deployment example.

There are two important files for you:

  1. Dockerfile.citus
  2. citus_k8s.yaml

Citus upgrades and PostgreSQL major upgrades

Read the Citus upgrade documentation. One change applies: restart PostgreSQL with patronictl_restart instead of systemctl restart.

A PostgreSQL major upgrade with Citus requires both projects’ upgrade procedures. Combine the Citus major upgrade documentation with Patroni PostgreSQL major upgrade<major_upgrade> instructions. A Citus formation contains multiple Patroni clusters: the coordinator and workers. Upgrade each cluster independently.

14 - Convert a Standalone to a Patroni Cluster

Procedure to convert existing PostgreSQL data into a Patroni cluster.

Source: https://patroni.readthedocs.io/en/latest/existing_data.html

This section describes the process for converting a standalone PostgreSQL instance into a Patroni cluster.

To deploy a Patroni cluster without using a pre-existing PostgreSQL instance, see Running and Configuring instead.


Procedure

The following steps convert an existing Postgres cluster to Patroni management. All nodes must be running. These steps assume you do not intend to change the Postgres configuration during migration.

  1. Create the Postgres users described in the authentication section. In the sample SQL below, replace usernames and passwords for your environment. Skip this step if the required users already exist.

    -- Patroni superuser
    -- Replace PATRONI_SUPERUSER_USERNAME and PATRONI_SUPERUSER_PASSWORD accordingly
    CREATE USER PATRONI_SUPERUSER_USERNAME WITH SUPERUSER ENCRYPTED PASSWORD 'PATRONI_SUPERUSER_PASSWORD';
    
    -- Patroni replication user
    -- Replace PATRONI_REPLICATION_USERNAME and PATRONI_REPLICATION_PASSWORD accordingly
    CREATE USER PATRONI_REPLICATION_USERNAME WITH REPLICATION ENCRYPTED PASSWORD 'PATRONI_REPLICATION_PASSWORD';
    
    -- Patroni rewind user, if you intend to enable use_pg_rewind in your Patroni configuration
    -- Replace PATRONI_REWIND_USERNAME and PATRONI_REWIND_PASSWORD accordingly
    CREATE USER PATRONI_REWIND_USERNAME WITH ENCRYPTED PASSWORD 'PATRONI_REWIND_PASSWORD';
    GRANT EXECUTE ON function pg_catalog.pg_ls_dir(text, boolean, boolean) TO PATRONI_REWIND_USERNAME;
    GRANT EXECUTE ON function pg_catalog.pg_stat_file(text, boolean) TO PATRONI_REWIND_USERNAME;
    GRANT EXECUTE ON function pg_catalog.pg_read_binary_file(text) TO PATRONI_REWIND_USERNAME;
    GRANT EXECUTE ON function pg_catalog.pg_read_binary_file(text, bigint, bigint, boolean) TO PATRONI_REWIND_USERNAME;
  2. Complete these steps on each Postgres node. Finish one node before you continue to the next. Start with the primary, then process each standby:

    1. If systemd runs Postgres, disable the Postgres systemd unit. Patroni will manage Postgres startup and shutdown.
    2. Create a Patroni YAML configuration file. You can use Patroni configuration generation and validation tooling.
      • Note (specific for the primary node): If cluster members use replication slots, we recommend enabling use_slots. Configure the existing slots as permanent with slots. When use_slots is enabled, Patroni creates member replication slots and drops slots it does not recognize. Permanent slot configuration preserves your existing slots during migration. See Dynamic Configuration Settings for details.
    3. Start the patroni systemd service. Patroni detects that Postgres is running and starts monitoring it.
  3. Transfer Postgres startup management to Patroni. Restart members with patronictl restart cluster-name member-name. To minimize downtime, you may split this step:

    1. Immediate restart of the standby nodes.
    2. Scheduled restart of the primary node within a maintenance window.
  4. If you configured permanent slots in step 1.2., wait for the Patroni slots to catch up. Their restart_lsn must reach the restart_lsn of the corresponding original slots. Then remove the original slots from slots with patronictl edit-config cluster-name. Patroni can then drop the original slots when they are no longer needed. Use this example query to compare restart_lsn values:

    -- Assume original_slot_for_member_x is the name of the slot in your original
    -- cluster for replicating changes to member X, and slot_for_member_x is the
    -- slot created by Patroni for that purpose. You need restart_lsn of
    -- slot_for_member_x to be >= restart_lsn of original_slot_for_member_x
    SELECT slot_name,
           restart_lsn
    FROM pg_replication_slots
    WHERE slot_name IN (
        'original_slot_for_member_x',
        'slot_for_member_x'
    )

Major Upgrade of PostgreSQL Version

The only possible way to do a major upgrade currently is:

  1. Stop Patroni.
  2. Upgrade the PostgreSQL binaries. Run pg_upgrade on the primary.
  3. Update patroni.yml.
  4. Remove the initialize key from the DCS, or remove all cluster state with patronictl remove cluster-name. This is necessary because pg_upgrade runs initdb, which creates a database with a new PostgreSQL system identifier.
  5. If you removed all cluster state, you may copy patroni.dynamic.json from the old data directory to the new directory. This retains some PostgreSQL parameters that you set earlier.
  6. Start Patroni on the primary.
  7. On standby nodes, upgrade PostgreSQL binaries, update patroni.yml, and remove the contents of data_dir.
  8. Start Patroni on the standbys. Wait for replication to complete.

PostgreSQL does not support pg_upgrade on standby nodes. If you understand the procedure, you can use rsync as described in https://www.postgresql.org/docs/current/pgupgrade.html instead of removing data_dir. Letting Patroni replicate the data is the safest method.


FAQ

  • During Patroni startup, Patroni complains that it cannot bind to the PostgreSQL port.

    Check listen_addresses and port in postgresql.conf, and postgresql.listen in patroni.yml. Make sure pg_hba.conf permits this access.

  • After asking Patroni to restart the node, PostgreSQL displays the error message could not open configuration file "/etc/postgresql/10/main/pg_hba.conf": No such file or directory

    The cause depends on how you manage PostgreSQL configuration. With postgresql.config_dir, Patroni generates pg_hba.conf from bootstrap settings only during new-cluster bootstrap. Here, PGDATA was not empty, so no bootstrap occurred. The file must already exist.

15 - Integration with other tools

Integrating Patroni with external backup and orchestration tools.

Source: https://patroni.readthedocs.io/en/latest/tools_integration.html

Patroni can integrate with other tools in your stack. These examples show possible integrations. The list is not complete.


Barman

Patroni provides patroni_barman. This application communicates with pg-backup-api to run Barman operations remotely.

The application has two subcommands: recover and config-switch.

patroni_barman recover

Use the recover subcommand as a custom bootstrap method or replica creation method. See replica_imaging_and_bootstrap for details.

patroni_barman config-switch

Use the config-switch subcommand as an on_role_change callback in Patroni. For example, you may stream WALs from the primary to your Barman host. After a failover, you may want to stream from the new primary. Use patroni_barman config-switch as the on_role_change callback for this change.

Note

This subcommand uses barman config-switch, available since Barman 3.10. The command overrides a Barman server configuration with a predefined model. See the Barman documentation for details.

This example applies a configuration model when the Patroni node becomes primary:

postgresql:
    callbacks:
        on_role_change: >
            patroni_barman
                --api-url YOUR_API_URL
                config-switch
                --barman-server YOUR_BARMAN_SERVER_NAME
                --barman-model YOUR_BARMAN_MODEL_NAME
                --switch-when promoted
Note

Configure Barman and pg-backup-api on the Barman host before you use patroni_barman config-switch. This lets it run barman config-switch remotely through the backup API. You must also configure the Barman models in advance. The example uses only some available parameters. Run patroni_barman config-switch --help or see the Barman documentation for details.

16 - Security Considerations

Security considerations for DCS, REST API, and credential handling.

Source: https://patroni.readthedocs.io/en/latest/security.html

Protect two Patroni cluster interfaces from unauthorized access: the distributed configuration storage (DCS) and the Patroni REST API.


Protecting DCS

Patroni and patronictl store data in the DCS and retrieve data from it.

The DCS contains no sensitive information, but it permits changes to some Patroni/Postgres settings. Protect the DCS first.

Protection depends on the DCS type. See settings for authentication and encryption parameters: tokens, basic authentication, and client certificates.

The general recommendation is to enable TLS for all DCS communication.


Protecting the REST API

Protecting the REST API is a more complicated task.

Patroni uses its REST API during leader races. The patronictl tool uses it for failovers, switchovers, reinitialization, restarts, and reloads. HAProxy and other load balancers use it for HTTP health checks. You can also use it for monitoring.

The REST API has safe endpoints (GET requests) that only retrieve information. Unsafe endpoints (PUT, POST, PATCH and DELETE requests) change node state.

To protect unsafe endpoints with HTTP basic authentication, set restapi.authentication.username and restapi.authentication.password. Safe endpoints require TLS for protection.

With TLS enabled and a PKI established, API servers and clients can authenticate each other for all endpoints.

The restapi section enables TLS client authentication. The verify_client parameter specifies which calls require successful client certificate verification. Use verify_client: required for all calls, verify_client: optional for unsafe calls only, or verify_client: none for no calls.

The ctl section enables TLS server authentication for the client. The client, patronictl, uses the same configuration as Patroni. Set insecure: true to disable server certificate verification by the client. See settings for TLS client parameters.

PostgreSQL database access protection is outside this document. See https://www.postgresql.org/docs/current/client-authentication.html.

17 - HA multi datacenter

Multi-datacenter high-availability patterns with Patroni replication.

Source: https://patroni.readthedocs.io/en/latest/ha_multi_dc.html

A PostgreSQL cluster across multiple data centers uses replication for high availability. Replication can be synchronous or asynchronous. See replication modes.

Both modes require these considerations:

  • Postgres can run as primary or standby leader only if it owns and can update the leader key.
  • Use an odd number of etcd, ZooKeeper, or Consul nodes: 3 or 5.

Synchronous Replication

A multi-datacenter cluster needs at least 3 zones to tolerate a zone failure automatically.

The architecture diagram would be the following:

image

Deploy at least 3 etcd, ZooKeeper, or Consul nodes across the data centers, with one node in each zone.

Deploy at least 2 Postgres nodes in different data centers. Set synchronous_mode: true in the global dynamic configuration.

This enables synchronous replication. The primary selects one node as its synchronous standby.


Asynchronous Replication

With two data centers, use two independent etcd clusters and a Patroni standby cluster in the second data center. This is the preferred arrangement. If the first site fails, you can manually promote the standby_cluster.

The architecture diagram would be the following:

image

Automatic promotion is not possible because DC2 cannot determine the state of DC1.

Do not use pg_ctl promote in this scenario. To promote the healthy cluster manually, remove standby_cluster from the dynamic configuration.

Warning

If the source cluster is still up and running and you promote the standby cluster you create a split-brain.

There are two ways to restore the initial state:

  • Add the standby_cluster section again to trigger pg_rewind. For correct operation, pg_rewind requires data page checksums and/or wal_log_hints set to on. Enable checksums with the --data-checksums option for initdb. Other factors can still cause pg_rewind to fail.
  • Rebuild the standby cluster.

Before you promote the standby cluster, manually ensure that the source cluster is down (STONITH). When DC1 recovers, convert its cluster to a standby cluster.

Before conversion, you may inspect the database manually. Extract changes made between the network failure between DC1 and DC2 and the manual shutdown of the DC1 cluster.

You may then apply these changes manually to the DC2 cluster.

18 - FAQ

Frequently asked questions about Patroni operation and troubleshooting.

Source: https://patroni.readthedocs.io/en/latest/faq.html

This section answers common Patroni questions. Each subsection covers a different topic.

For more help or unexpected problems, see chatting and reporting_bugs.


Comparison with other HA solutions

Why does Patroni require a separate cluster of DCS nodes while other solutions like repmgr do not?
There are different ways of implementing HA solutions, each of them with their pros and cons.

Software like repmgr performs communication among the nodes to decide when actions should be taken.

Patroni uses DCS state as the authoritative source for its decisions.

A separate DCS cluster adds architectural complexity but reduces the risk of split-brain in your Postgres cluster.

What is the difference between Patroni and other HA solutions in regards to Postgres management?
Patroni does not just manage the high availability of the Postgres cluster but also manages Postgres itself.

If Postgres nodes do not exist, Patroni bootstraps the primary and standbys and manages their configuration. For existing nodes, Patroni takes over cluster management.

Patroni also attempts automatic recovery. After primary failure, it fails over to a replica and tries to rejoin the old primary as a replica. After replica failure, it tries to rejoin that replica.

Patroni is a template for HA solutions because it manages Postgres as a whole, including physical replication.


DCS

Can I use the same etcd cluster to store data from two or more Patroni clusters?
Yes, you can!

Information about a Patroni cluster is stored in the DCS under a path prefixed with the namespace and scope Patroni settings.

Multiple Patroni clusters can share a DCS cluster if their namespace and scope combinations are distinct.

What occurs if I attempt to use the same combination of namespace and scope for different Patroni clusters that point to the same DCS cluster?
The second cluster finds existing DCS information with an incompatible Postgres system identifier. Patroni interprets this as a different cluster and a configuration error. It stops management of the second cluster.

Make sure to use different namespace / scope when dealing with different Patroni clusters that share the same DCS cluster.

What occurs if I lose my DCS cluster?
The DCS is used to store basically status and the dynamic configuration of the Patroni cluster.

All Patroni clusters that use the lost DCS enter read-only mode unless dcs_failsafe_mode is enabled.

What should I do if I lose my DCS cluster?
There are three possible outcomes upon losing your DCS cluster:

  1. The DCS cluster recovers fully. Patroni needs no action and should recover after DCS recovery.
  2. The DCS cluster is recreated with the same endpoints. Patroni needs no configuration changes.
  3. A new DCS cluster has different endpoints. Update the DCS endpoints in every Patroni node’s configuration.

In scenarios 2. and 3., Patroni recreates DCS status information from current cluster state. It restores dynamic configuration from patroni.dynamic.json. Each Patroni member stores this backup in its Postgres data directory.

What occurs if I lose majority in my DCS cluster?
The DCS will become unresponsive, which will cause Patroni to demote the current read/write Postgres node.

Remember: Patroni relies on the state of the DCS to take actions on the cluster.

You can use the dcs_failsafe_mode to alleviate that situation.


patronictl

Do I need to run patronictl in the Patroni host?
No, you do not need to do that.

On a Patroni host, patronictl can use the same configuration file as the patroni agent. This is convenient if you have access to the host.

patronictl is a client and can run remotely. Configure it to reach the DCS and the REST APIs of the required Patroni members.

Why did the information from one of my Patroni members disappear from the output of patronictl_list command?
Information shown by patronictl_list is based on the contents of the DCS.

If a member disappears from the DCS, its Patroni agent probably stopped or cannot communicate with the DCS.

Without updates, member information expires from the DCS. The member then disappears from patronictl_list output.

Why is the information about one of my Patroni members not up-to-date in the output of patronictl_list command?
Information shown by patronictl_list is based on the contents of the DCS.

Patroni normally updates this information approximately every loop_wait seconds. Even during normal operation, DCS information can therefore lag by up to loop_wait seconds.

This interval is not fixed. Some Patroni operations update DCS information immediately.


Configuration

What is the difference between dynamic configuration and local configuration?
Dynamic, or global, configuration is stored in the DCS and applies to all cluster members. Store most configuration there.

Use local configuration for node-specific settings or overrides of global settings. Configure only the required member, through its configuration file or environment variables.

See more in config.

What are the types of configuration in Patroni, and what is the precedence?
The types are:

  • Dynamic configuration: applied to all members;
  • Local configuration: applied to the local member, overrides dynamic configuration;
  • Environment configuration: applied to the local member, overrides both dynamic and local configuration.

Note: Some Postgres GUCs can only be set globally through dynamic configuration. Patroni also enforces hard-coded values for some GUCs.

See more in config.

Is there any facility to help me create my Patroni configuration file?
Yes, there is.

Use patroni --generate-sample-config to generate a sample configuration. Use patroni --generate-config to generate configuration from an existing Postgres instance.

Please refer to generate_sample_config and generate_config for more details.

I changed my parameters under bootstrap.dcs configuration but Patroni is not applying the changes to the cluster members. What is wrong?
Patroni uses bootstrap.dcs only to bootstrap a new cluster. During bootstrap, it writes these values to the DCS.

After bootstrap, change dynamic configuration through the DCS.

Refer to the next question for more details.

How can I change my dynamic configuration?
Change DCS configuration with either method:

How can I change my local configuration?
Edit the member’s configuration file and signal its Patroni agent with SIHGUP. Use one of these methods:

  • Send a POST request to the REST API reload_endpoint; or

  • Run patronictl_reload; or

  • Locally signal the Patroni process with SIGHUP:

    • With systemd, run systemctl reload PATRONI_UNIT.service. Replace PATRONI_UNIT with the Patroni service name.
    • Otherwise, find the patroni process and run kill -s HUP PID. Replace PID with its process ID.

Note: patronictl_reload can fail in these cases:

  • Expired REST API certificates: use the -k option of patronictl to bypass this problem.
  • Wrong credentials: for example, you changed restapi or ctl credentials in a file shared by Patroni and patronictl.

How can I change my environment configuration?
The environment configuration is only read by Patroni during startup.

After an environment configuration change, restart the corresponding Patroni agent.

Avoid triggering failover during the restart. See patronictl_pause.

How can I reduce repetitive heartbeat log lines during normal operation?

To suppress repeated lines such as Lock owner: ... and no action. I am ..., set log.deduplicate_heartbeat_logs: true.

You can set it either in the Patroni YAML file (log settings) or with PATRONI_LOG_DEDUPLICATE_HEARTBEAT_LOGS=true.

This reduces log volume. It also removes per-loop heartbeat information that can help diagnose failover.

What occurs if I change a Postgres GUC that requires a reload?
After a dynamic or local configuration change, Patroni reloads the Postgres configuration.

What occurs if I change a Postgres GUC that requires a restart?
Patroni will mark the affected members with a flag of pending restart.

Choose when and how to restart affected members. Use either method:

Note: Some Postgres GUCs require a specific node restart order. See shared_memory_gucs.

What is the difference between etcd and etcd3 in Patroni configuration?
etcd uses the API version 2 of etcd, while etcd3 uses the API version 3 of etcd.

API version 3 cannot manage data stored through version 2, and version 2 cannot manage data stored through version 3.

We recommend that you configure etcd3 instead of etcd because:

  • API version 2 is disabled by default from Etcd v3.4 onward;
  • API version 2 will be completely removed on Etcd v3.6.

I enabled use_slots in Patroni. When a member stays offline for some time, the upstream node drops its replication slot. How can I prevent this? There are two options:

  1. Adjust member_slots_ttl, available since Patroni 4.0.0 with PostgreSQL 11 or later. The default is 30min. Patroni retains an absent member’s slot while its downtime is shorter than this threshold.
  2. Configure permanent physical replication slots for the members.

Since Patroni 3.2.0, member slots can be permanent slots managed by Patroni.

Patroni creates permanent physical slots on all nodes and retains them. It advances each slot’s LSN to the LSN consumed by its member.

If you remove a member later, you must adjust permanent slot configuration. Otherwise, Patroni retains its slots indefinitely.

Note: Before Patroni 3.2.0, permanent physical member slots were managed only on the current leader. After failover or switchover, Patroni created them on the new leader. This did not guarantee that the new leader had all WAL segments required by an absent node.

Note: Patroni 3.2.0 can still have a small race condition. A new replica slot can initially be ahead of the corresponding leader slot. If nobody consumes the slot, some files can still be missing after failover. We recommend continuous archiving so you can restore required WALs or perform PITR.

What is the difference between loop_wait, retry_timeout and ttl?
Patroni regularly runs an HA cycle to check cluster health. It may then take action, such as failover to a standby.

loop_wait is the delay in seconds before Patroni starts the next HA cycle.

retry_timeout sets the timeout for DCS and Postgres retries. If the DCS remains unresponsive beyond retry_timeout seconds, Patroni may demote the primary as a protective action.

ttl is the lease duration for the DCS leader lock. The leader renews it during HA cycles. If it cannot renew the lease for longer than ttl, the lock expires and starts a leader race.

Note: Patroni enforces minimum values and a timing rule for these settings. See dynamic.


Postgres management

Can I change Postgres GUCs directly in Postgres configuration?
You can, but you should avoid that.

Patroni manages Postgres configuration. It may overwrite changes that you make directly in configuration files.

To manage settings outside Patroni, use one of these methods:

  • Change Postgres GUCs through $PGDATA/postgresql.base.conf; or
  • Define a postgresql.custom_conf which will be used instead of postgresql.base.conf so you can manage that externally; or
  • Change GUCs using ALTER SYSTEM / ALTER DATABASE / ALTER USER.

You can find more information about that in the section important_configuration_rules.

We recommend managing all Postgres configuration through Patroni. This centralizes management and makes troubleshooting easier.

Can I restart Postgres nodes directly?
No, you should not attempt to manage Postgres directly!

Restarting Postgres outside Patroni can trigger failover.

Use the management operations that Patroni provides.

Is Patroni able to take over management of an already existing Postgres cluster?
Yes, it can!

Please refer to existing_data for detailed instructions.

How does Patroni manage Postgres?
Patroni starts and stops Postgres with binaries such as pg_ctl and postgres.

You MUST disable other Postgres management services, such as postgresql.service. Only Patroni should start, stop, or promote cluster instances. Other services can cause split-brain. For example, after primary failure, an enabled postgresql.service can restart Postgres independently and create a second primary.


Concepts and requirements

Which are the applications that make part of Patroni?
Patroni provides these applications:

  • patroni: The agent that manages a Postgres node.
  • patronictl: The command-line client for switchovers, restarts, configuration changes, and other cluster operations. See patronictl for details.

What is a standby cluster in Patroni?
A standby cluster has no running primary Postgres node and no read/write member.

Standby clusters replicate data from another cluster, often across data centers.

The standby leader replicates from a remote Postgres node. Other standbys use cascading replication from that leader.

Note: The standby cluster has no other knowledge of its source cluster. It can use restore_command instead of WAL streaming and an independent DCS cluster.

Refer to standby_cluster for more details.

What is a leader in Patroni?
A leader in Patroni is like a coordinator of the cluster.

In a regular Patroni cluster, the leader will be the read/write node.

In a standby cluster, the leader, also called standby leader, replicates from a remote Postgres node. It cascades those changes to other standby cluster members.

Does Patroni require a minimum number of Postgres nodes in the cluster?
No, you can run Patroni with any number of Postgres nodes.

Remember: Patroni is decoupled from the DCS.

What does pause mean in Patroni?
Pause suspends Patroni management of Postgres.

Use pause during maintenance to prevent automatic HA actions, such as failover when you stop the primary.

You can find more information about that in pause.


Automatic failover

How does the automatic failover mechanism of Patroni work?
Patroni automatic failover is based on what we call leader race.

Patroni stores cluster status in the DCS. The leader lock contains the name of the current leader.

The leader lock has a time-to-live. If the leader does not renew its lease in time, the DCS key expires.

When the leader lock expires, a leader race starts. All nodes check whether they are the best candidate for the leader role. Some checks call the REST APIs of all other Patroni members.

Each member that considers itself the best candidate tries to acquire the leader lock. The first to acquire it becomes the read/write node or standby leader. Patroni configures the other members to follow it.

Can I temporarily disable automatic failover in the Patroni cluster?
Yes, you can!

Temporarily pause the cluster to disable automatic failover, for example during maintenance.

Unpause the cluster to resume automatic failover.

You can find more information about that in pause.


Bootstrapping and standbys creation

How does Patroni create a primary Postgres node? What about a standby Postgres node?
By default, Patroni uses initdb to bootstrap a new cluster. It uses pg_basebackup to copy the leader and create standbys.

You can define custom bootstrap and replica creation methods.

Custom methods can restore backups from tools such as pgBackRest or Barman.

For detailed information please refer to custom_bootstrap and custom_replica_creation.


Monitoring

How can I monitor my Patroni cluster?
Patroni provides these rest_api endpoints:

  • /metrics: Monitoring metrics in Prometheus format.
  • /patroni: Cluster status in JSON. This information is similar to the /metrics output.

You can use those endpoints to implement monitoring checks.

19 - Release notes

Chronological Patroni release notes and change history.

Source: https://patroni.readthedocs.io/en/latest/releases.html


Version 4.1.5

Released 2026-08-12

Compatibility improvements

  • Compatibility with PostgreSQL 14.24, 15.19, 16.15, 17.11, 18.6 (Alexander Kukushkin)

    Add the new output_plugin_libraries GUC, which restricts logical decoding output plugins.

Improvements

  • Log REST API connection resets at DEBUG instead of WARNING (Kyle McLaren)

    Ensure the common “client went away mid-write” variants are silenced without affecting the handling of genuine (non-connection) errors.

Bugfixes

  • Fix thread_stack_size validation alignment (Sundong Kim)

    Changed aligned from 65535 to 65536 in the thread_stack_size schema. Previously, patroni --validate-config rejected almost all realistic values, including the daemon default 524288.

  • Allow validation of synchronous_mode to accept 'quorum' and boolean-like strings (Eray Araz)

    patroni --validate-config previously rejected synchronous_mode values such as quorum and the PostgreSQL-style boolean strings that are accepted at runtime.

Version 4.1.4

Released 2026-07-07

Bugfixes

  • Check NOTIFY_SOCKET environment variable before using systemd package (Polina Bungina)

    Import and use the package only when NOTIFY_SOCKET is set. This avoids FileNotFoundError: [Errno 2] No such file or directory.

  • Unify pg_replication_slots query (Polina Bungina)

    Incorrect handling of the failover and synced values was resulting in KeyError exceptions during removal of the incorrect logical replication slots.

  • Consider version-specific authentication parameters in configuration generation (Polina Bungina)

    patroni --generate-config now removes authentication parameters that do not apply to the connected PostgreSQL version. These parameters could be inherited accidentally from the environment.

  • Handle pg_rewind while a PostgreSQL instance is starting as a standby (Alexander Kukushkin)

    Fallback to pg_controldata information when a PostgreSQL instance is running but is not yet accepting connections.

  • Fix Prometheus metric type for patroni_postgres_timeline (Huseyin Demir)

    Changed patroni_postgres_timeline from counter to gauge. The value can decrease, for example to 0 when PostgreSQL stops.

  • Don’t stop watchdog until client backends are fully stopped (Alexander Kukushkin)

    If primary_stop_timeout was below the minimum watchdog timeout and expired, Patroni disabled the watchdog before all client backends exited.

  • Handle statement timeout error for monitoring query (Alexander Kukushkin)

    After a statement timeout, use the cached role to avoid primary demotion. Force pg_stat_statements.track to none for monitoring queries to avoid expensive pg_stat_statements garbage collection.

  • Drop Patroni-managed replication slots with wal_status=lost (Alexander Kukushkin)

    Replication slots with wal_status=lost are no longer usable. Patroni will now drop such slots and recreate them if needed.

  • Fix role representation in patronictl member validation error (Polina Bungina)

    Ensures the correct string representation is used within the exception message, preventing errors from being formatted like Error: No CtlPostgresqlRole.REPLICA among provided members.

Version 4.1.3

Released 2026-05-05

Stability improvements

  • Properly handle mislabeled Etcd error (Ants Aasma)

    Current Etcd versions raise Unknown error when Etcd leader is lost while updating the lease. Patroni will now override the reported error code to Unavailable.

Bugfixes

  • Use binary version when PG_VERSION file does not exist (Polina Bungina)

    Custom bootstrap and other cases may have no PG_VERSION file. Patroni treated the version as 0.0, which broke version-specific logic. It now tries to read the binary version.

  • Refactor logger initialization to avoid missing early log messages (Alexander Kukushkin)

    Create PatroniLogger before loading Config to capture early log messages.

  • Include MONOTONIC_USEC in RELOADING=1 systemd notification (Alexander Kukushkin)

    systemd 257+ requires MONOTONIC_USEC alongside RELOADING=1 for Type=notify-reload services. Without it, systemctl reload hangs indefinitely.

Improvements

  • Skip single-user crash recovery when backup_label exists (Vadim Ponomarev)

    For replicas restored from external backup without a custom bootstrap method, skip single-user crash recovery. Let PostgreSQL recover during normal startup.

  • Warn when running under systemd without python-systemd package (Alexander Kukushkin)

    Check NOTIFY_SOCKET before warning about a missing python-systemd package. Warn only when actually running under systemd, instead of always logging “systemd integration is not supported” at startup.

Version 4.1.2

Released 2026-04-21

Systemd support improvements

  • Add support for notify-reload systemd unit type (Ronan Dunklau)

    Allows systemctl reload to wait until Patroni has actually processed the configuration reload by sending RELOADING=1 and READY=1 notifications to systemd.

  • Send STOPPING=1 notification to systemd on shutdown (Alexander Kukushkin)

    Patroni now properly notifies systemd that it is shutting down, following the systemd notify protocol.

  • Do not let PostgreSQL to notify systemd (Alexander Kukushkin)

    Removed NotifyAccess=all from the example unit. Filter NOTIFY_SOCKET when starting PostgreSQL so it cannot send READY=1 or STOPPING=1. Existing PostgreSQL processes may already have NOTIFY_SOCKET when Patroni takes control. During their shutdown, reassert READY=1 to counteract STOPPING=1.

Version 4.1.1

Released 2026-04-08

Stability improvements

  • Compatibility with threading changes in python 3.11+ (Alexander Kukushkin)

    Avoid starting/stopping threads at runtime. Introduce thread pools for REST API and for executing async tasks. Allow configuring global thread_pool_size and restapi.thread_pool_size.

  • Compatibility with python 3.14 (Alexander Kukushkin)

    Run tests against python 3.14 and fix compatibility issues.

  • Compatibility with Etcd security fixes in v3.6.9, v3.5.28, and v3.4.42 (Alexander Kukushkin)

    These Etcd security releases require authentication for topology reads and lease keepalive. Patroni now authenticates both operations. It also reauthenticates after authentication failures and retries requests.

  • Improvements for Etcd3 error handling (Alexander Kukushkin)

    Handle broken JSON responses, be flexible in how JSON error is parsed, and improve reporting for etcd internal errors.

Bugfixes

  • Retry leader update on temporary Kubernetes 403 error (Sophia Ruan, Alexander Kukushkin)

    After a temporary Kubernetes 403 Permission Denied, Patroni checks whether the node still holds leadership. It retries leader updates within retry_timeout instead of immediately demoting. Temporary RBAC failures are one possible cause.

  • Fix issue with renaming leader node in sync mode and pause (Alexander Kukushkin)

    /sync key wasn’t updated after renaming the leader node with Patroni restart in pause (without Postgres restart). It prevented Patroni from promoting after the next restart without pause.

  • Trigger pg_rewind check when the same primary increased timeline (Alexander Kukushkin)

    Single-user crash recovery followed by promotion after leader lock acquisition can increase the same primary’s timeline. Other replicas may be isolated from the DCS during this sequence. They did not trigger the pg_rewind state machine because the leader and primary_conninfo were unchanged.

  • Only write superuser password during initdb bootstrap if it is non-empty (Michael Banck)

    Writing an empty password during initdb bootstrap was causing issues.

  • Fix bug with failover_priority with synchronous_mode=on (Alexander Kukushkin)

    tag.failover_priority values were ignored when synchronous_node_count > 1.

  • Fix bug with primary_conninfo password comparison (Alexander Kukushkin)

    Since PostgreSQL 10, Patroni uses a passfile in primary_conninfo. It failed to update that file after a YAML replication password change and reload.

  • Don’t restart replica with nofailover tag in pause mode (Alexander Kukushkin)

    Patroni used to start a manually shut down PostgreSQL replica in pause mode when it had nofailover tag set to true.

  • Fix check_recovery_conf() when PostgreSQL is in the starting state (Alexander Kukushkin)

    PostgreSQL v12 and later cannot answer pg_settings queries before accepting connections. Patroni now records missing recovery parameters internally when it writes postgresql.conf. It also restores the Postgresql.is_starting() check in Ha.is_healthiest_node().

  • Validate user options in dictionary format for initdb/basebackup (m4rrypro)

    Dictionary-form initdb or basebackup options bypassed option_is_allowed() validation. This permitted blocked options, unlike list-form options.

  • Allow server-side compression for basebackup option (m4rrypro)

    Previously, basebackup blocked compress entirely. PostgreSQL 15 introduced server-side compression compatible with plain output. Patroni now permits this form but still rejects client-side compression.

  • Don’t reload PostgreSQL config while running custom bootstrap (Alexander Kukushkin)

    Custom bootstrap can start and stop PostgreSQL multiple times. Reloading its configuration during this process could cause unexpected behavior.

  • Check that postgresql.parameters is a dictionary (Alexander Kukushkin)

    Discard new config if postgresql.parameters is not a dictionary.

Version 4.1.0

Released 2025-09-23

New features

  • Add support for systemd “notify” unit type (Ronan Dunklau)

    Without a notify unit, systemd could send SIGHUP immediately after starting Patroni. The signal could kill Patroni before it installed signal handlers.

  • Provide receive and replay LSN/lag information in API and ctl (Polina Bungina)

    Patroni REST API /cluster endpoint and patronictl list command now provide receive LSN, replay LSN, receive lag, and replay lag information for each replica member.

  • Ensure clean demotion to standby cluster (Polina Bungina)

    Make sure the introduction of the standby_cluster section in the dynamic configuration leads to a clean cluster demotion.

  • Implement patronictl demote-cluster and promote-cluster commands (Polina Bungina)

    New commands for cluster demotion and promotion handle both the dynamic configuration editing and checking the result status.

  • Implement sync_priority tag (Polina Bungina)

    This parameter controls the priority a member should have during synchronous replica selection when synchronous_mode is set to on.

  • Implement --print option for --validate-config (Polina Bungina)

    Print out local configuration (including environment configuration overrides) after it has been successfully validated.

  • Implement kubernetes.bootstrap_labels (Polina Bungina)

    Define pod labels for these states: initializing new cluster, running custom bootstrap script, starting after custom bootstrap, or creating replica.

  • Add configuration option to suppress duplicate heartbeat logs (Michael Morris)

    If set to true, successive heartbeat logs that are identical shall not be output.

  • Add optional cluster_type attribute to permanent replication slots (Michael Banck)

    This allows you to set whether a particular permanent replication slot should always be created, or just on a primary or standby cluster.

  • Make HTTP Server header configurable (David Grierson)

    Introduce the restapi.server_tokens configuration parameter that allows you to restrict information disclosed in the HTTP Server header.

  • Implement readiness API checks for replication on replica members (Ants Aasma)

    Previously, a replica became ready as soon as PostgreSQL started. It now requires active replication and sufficiently low lag behind the leader.

Improvements

  • Reduce log level of watchdog configuration failure (Ants Aasma)

    Show the Could not activate Linux watchdog device log line on debug logging level, unless the watchdog is configured with required mode. It was previously shown on info level.

  • Take advantage of written_lsn and latest_end_lsn from pg_stat_wal_receiver (Alexander Kukushkin)

    Prefer written_lsn, the write LSN, over pg_last_wal_receive_lsn(), which returns the flush LSN. latest_end_lsn identifies the source host’s WAL flush position. For primary sources, this improves replay lag calculations over DCS values updated every loop_wait seconds.

  • Avoid interactions with slots created with the failover=true option (Alexander Kukushkin)

    This change is required to make the logical failover slots feature fully functional.

  • Add PostgreSQL state to /metrics REST API endpoint (Ivan Filianin)

    PostgreSQL instance state information is now available in the Prometheus format output of the /metrics REST API endpoint.


Version 4.0.7

Released 2025-09-22

New features

  • Add support for PostgreSQL 18 RC1 (Alexander Kukushkin)

    GUC’s validator rules were extended. Patroni now properly handles the new background I/O worker.

Bugfixes

  • Fix potential issue around resolving localhost to IPv6 on Windows (András Váczi)

    PostgreSQL listen_addresses values 0.0.0.0 and 127.0.0.1 allow only IPv4. Windows often resolves localhost to IPv6 ::1. Patroni now uses 127.0.0.1 instead of localhost on Windows to avoid this mismatch.

  • Return global config only when /config key exists in DCS (Alexander Kukushkin)

    Patroni REST API was returning an empty configuration instead of raising an error if the /config key was missing in DCS.

  • Fix the issue of failsafe mode not being triggered in case of Etcd unavailability (Alexander Kukushkin)

    Patroni was not always properly handling etcd3 exceptions, which resulted in failsafe mode not being triggered.

  • Fix signal handler reentrancy deadlock (Waynerv)

    Patroni running in a Docker container with PID=1 in some special cases was experiencing deadlock after receiving SIGCHLD.

  • Recreate (permanent) physical slot when it doesn’t reserve WAL (Israel Barth Rubio)

    Physical slots created outside Patroni without WAL reservation caused replication slot cannot be advanced. Patroni now recreates them.

  • Handle watch cancellation messages in etcd3 properly (Alexander Kukushkin)

    etcd3 watch cancellation leaves the connection open, which caused Patroni to use stale data. Patroni now stops reading the chunked response and closes the connection.

  • Handle case when HTTPConnection socket is wrapped with pyopenssl (Alexander Kukushkin)

    Patroni was not correctly using pyopenssl interfaces, enforced in python-etcd.

Documentation improvements

  • Improve 2-node cluster guidance (Nikolay Samokhvalov)

    Clarify behaviour during failover and DCS requirements.


Version 4.0.6

Released 2025-06-06

Bugfixes

  • Fix bug in failover from a leader with a higher priority (Alexander Kukushkin)

    Make sure Patroni ignores the former leader with higher priority when it reports the same LSN as the current node.

  • Fix permissions for the postgresql.conf file created outside of PGDATA (Michael Banck)

    Respect the system-wide umask value when creating the postgresql.conf file outside of the PGDATA directory.

  • Fix bug with switchover in synchronous_mode=quorum (Alexander Kukushkin)

    Do not check quorum requirements when a candidate is specified.

  • Ignore stale Etcd nodes by comparing cluster term (Alexander Kukushkin)

    Memorize the last known “raft_term” of the Etcd cluster, and when executing client requests, compare it with the “raft_term” reported by an Etcd node.

  • Update PostgreSQL configuration files on SIGHUP (Alexander Kukushkin)

    Previously, Patroni was only replacing PostgreSQL configuration files if a change in global or local configuration was detected.

  • Properly handle Unavailable exception raised by etcd3 (Alexander Kukushkin)

    Patroni used to retry such requests on the same etcd3 node, while switching to another node is a better strategy.

  • Improve etcd3 lease handling (Alexander Kukushkin)

    Make sure Patroni refreshes the etcd3 lease at least once per HA loop.

  • Recheck annotations on 409 status code when attempting to acquire leader lock (Alexander Kukushkin)

    Implement the same behavior as was done for the leader object read in Patroni version 4.0.3.

  • Consider replay_lsn when advancing slots (Polina Bungina)

    Do not advance replica slots beyond replay_lsn. Advance a slot to replay_lsn if it exceeds the slot’s replica confirmed_flush_lsn but remains below its primary LSN.

  • Make sure CHECKPOINT is executed after promote (Alexander Kukushkin)

    An unfinished CHECKPOINT could prevent checkpoint task reset on demotion. The next promotion then used a stale result.

  • Avoid running “offline” demotion concurrently (Alexander Kukushkin)

    During slow shutdown, the next heartbeat could enter DCS error handling again. This logged AsyncExecutor is busy, demoting from the main thread and started another offline demotion.

  • Normalize the data_dir value before renaming the data directory on initialization failure (Waynerv)

    Prevent a trailing slash in the data_dir parameter value from breaking the renaming process after an initialization failure.

  • Check that synchronous_standby_names contains the expected value (Alexander Kukushkin)

    Non-quorum synchronous replication did not verify the actual synchronous_standby_names value. A stale value could remain when pg_stat_replication was a subset of it.


Version 4.0.5

Released 2025-02-20

Stability improvements

  • Compatibility with python-json-logger>=3.1 (Alexander Kukushkin)

    Get rid of the warnings produced by the old API usage.

  • Compatibility with Python 3.13 (Alexander Kukushkin)

    Run tests against Python 3.13.

  • Compatibility with pyinstaller>=4.4 (Joe Jensen)

    Fall back to the default iter_modules if pyinstaller toc attribute is not present.

  • Fix issues with PostgreSQL 9.5 support (Alexander Kukushkin)

    • Properly handle pg_rewind output format.
    • Consider synchronous_standby_names format not supporting “num” specification.
  • Compatibility with the latest changes in urlparse (Alexander Kukushkin)

    urlparse no longer accepts multiple hosts with [] in URLs. Use native PQconninfoParse() wrappers from libpq where possible. Keep the internal implementation only for older psycopg2 versions linked to outdated libpq.

Bugfixes

  • Show only the members to be restarted upon restart confirmation (András Váczi)

    Previously, when doing patronictl restart <clustername> --pending, the confirmation listed all members, regardless of whether their restart is pending.

  • Cancel long-running jobs on Patroni stop and remove data directory on replica bootstrap failure (Alexander Kukushkin)

    Previously, Patroni could be doing replica bootstrap, while pg_basebackup / wal-g / pgBackRest / barman or similar keep running.

  • Properly handle cluster names with a slash in patronictl edit-config (Antoni Mur)

    Replace a forward slash in cluster_name with an underscore.

  • Avoid dropping physical slots too early (Alexander Kukushkin)

    After failover, delay removal of physical slots containing xmin. On the new primary, wait for promotion. On replicas, wait for a cluster leader.

  • Handle all exceptions raised by subprocess in controldata() (Alexander Kukushkin)

    Patroni was not properly handling all exceptions possibly raised when calling pg_controldata utility.

  • Fix bug with a slot for a former leader not retained on failover (Alexander Kukushkin)

    Avoid falsely relying on members being present in DCS, while on failover /member key for the former leader is expiring exactly at the same time.

  • Fix a couple of bugs in the quorum state machine (Alexander Kukushkin)

    • Before demotion, include quorum requirements when checking for healthy leader-race candidates. Otherwise, the former leader could enter recovery with only asynchronous nodes around it.
    • QuorumStateResolver mishandled a replica that joined and disconnected quickly.

Improvements

  • Improve error on am empty or non-dictionary configuration file (Julian)

    Throw a more explicit exception when validating if Patroni configuration file contains a valid Mapping object.


Version 4.0.4

Released 2024-11-22

Stability improvements

  • Add compatibility with the py-consul module (Alexander Kukushkin)

    python-consul module is unmaintained for a long time, while py-consul is the official replacement. Backward compatibility with python-consul is retained.

  • Add compatibility with the prettytable>=3.12.0 module (Alexander Kukushkin)

    Address deprecation warnings.

  • Compatibility with the ydiff==1.4.2 module (Alexander Kukushkin)

    Fix compatibility issues for the latest version, constrain version in requirements.txt, and introduce latest version compatibility test.

Bugfixes

  • Run on_role_change callback after a failed primary recovery (Polina Bungina, Alexander Kukushkin)

    Also run the on_role_change callback when a primary fails to start after a crash. This increases the chance of callback execution, even if the subsequent start as a replica fails.

  • Fix a thread leak in patronictl list -W (Alexander Kukushkin)

    Cache DCS instance object to avoid thread leak.

  • Ensure only supported parameters are written to the connection string (Alexander Kukushkin)

    Patroni previously passed parameters from newer versions to the connection string. These parameters caused connection errors.


Version 4.0.3

Released 2024-10-18

Bugfixes

  • Disable pgaudit when creating users not to expose password (kviset)

    Patroni was logging superuser, replication, and rewind passwords on their creation when pgaudit extension was enabled.

  • Fix issue with mixed setups: primary on pre-Patroni v4 and replicas on v4+ (Alexander Kukushkin)

    If the leader runs Patroni before 4.0.0, use xlog_location from the /members key. Do not try to get the member’s slot position from the /status key. The previous behavior caused WAL accumulation on replicas.

  • Do not ignore valid PostgreSQL GUCs that don’t have Patroni validator (Polina Bungina)

    Still check against postgres --describe-config if a GUC does not have a Patroni validator but is, in fact, a valid GUC.

Improvements

  • Recheck annotations on 409 status code when reading leader object in K8s (Alexander Kukushkin)

    Avoid an additional update if PATCH request was canceled by Patroni, while the request successfully updated the target.

  • Add support of sslnegotiation client-side connection option (Alexander Kukushkin)

    sslnegotiation was added to the final PostgreSQL 17 release.


Version 4.0.2

Released 2024-09-17

Bugfixes

  • Handle exceptions while discovering configuration validation files (Alexander Kukushkin)

    Skip directories for which Patroni does not have sufficient permissions to perform list operations.

  • Make sure inactive hot physical replication slots don’t hold xmin (Alexander Kukushkin, Polina Bungina)

    Since version 3.2.0, Patroni creates physical replication slots for all members on replicas. It periodically advances them with pg_replication_slot_advance(). If hot_standby_feedback is enabled and the primary becomes a replica, the inactive slots can retain a NOT NULL xmin value. This value propagates to the new primary and prevents the xmin horizon from advancing. Vacuum then cannot remove dead tuples. Patroni now recreates slots that should be inactive but have a NOT NULL xmin value.

  • Fix unhandled DCSError during the startup phase (Waynerv)

    Ensure DCS connectivity before trying to check the uniqueness of the node name.

  • Explicitly include CMDLINE_OPTIONS GUCs when querying pg_settings (Alexander Kukushkin)

    When Patroni joins a running standby, restore all GUCs passed to postmaster as command line parameters. This follows the fix in Patroni 3.2.2.

  • Fix bug in synchronous_standby_names quoting logic (Alexander Kukushkin)

    PostgreSQL documentation requires double quotes around the ANY and FIRST keywords. Patroni previously omitted these quotes.

  • Fix keepalive connection out-of-range issue (hadizamani021)

    Calculate the keepalive option from ttl. Ensure that the result does not exceed the maximum value for the current platform.


Version 4.0.1

Released 2024-08-30

Bugfix

  • Patroni was creating unnecessary replication slots for itself (Alexander Kukushkin)

    It was happening if name contains upper-case or special characters.


Version 4.0.0

Released 2024-08-29

Warning
  • This version replaces the term “master” with “primary”. This introduces breaking changes. Read the release notes carefully. Reliable upgrades to Patroni 4+ require Patroni 3.1.0 or newer. Direct upgrades from older versions are possible. However, unexpected behavior can occur if the primary fails while other nodes run different Patroni versions.

Breaking changes

  • The following breaking changes were introduced when getting rid of the non-inclusive “master” term in the Patroni code:
    • On Kubernetes, Patroni sets the role label to primary by default. To retain the old behavior, set kubernetes.leader_label_value and kubernetes.standby_leader_label_value to master. This avoids downtime or long, complex migrations. Read more here.
    • Patroni role is written to DCS as primary instead of master.
    • Patroni role returned by Patroni REST API has been changed from master to primary.
    • Patroni REST API no longer accepts role=master in requests to /switchover, /failover, /restart endpoints.
    • /metrics REST API endpoint will no longer report patroni_master metric.
    • patronictl no longer accepts --master option for any command. --leader or --primary options should be used instead.
    • no_master option in the declarative configuration of custom replica creation methods is no longer treated as a special option, please use no_leader instead.
    • patroni_wale_restore script doesn’t accept --no_master option anymore.
    • patroni_barman script doesn’t accept --role=master option anymore.
    • All callback scripts are executed with role=primary option passed instead of role=master.
  • patronictl failover does not accept --leader option that was deprecated since Patroni 3.2.0.
  • User creation functionality (bootstrap.users configuration section) deprecated since Patroni 3.2.0 has been removed.

New features

  • Quorum-based failover (Ants Aasma, Alexander Kukushkin)

    This feature implements quorum-based synchronous replication, available from PostgreSQL v10. It reduces worst-case latency, even during normal operation. Other standbys can compensate for slower replication to one standby. Patroni adds safeguards against user-visible data loss. It selects the failover candidate based on the latest transaction received.

  • Register Citus secondaries in pg_dist_node (Alexander Kukushkin)

    Patroni now maintains the list of nodes with role==replica, state==running and without noloadbalance tag in pg_dist_node.

  • Configurable retention of members’ replication slots (Alexander Kukushkin)

    The global member_slots_ttl parameter controls how long Patroni retains member replication slots when the member key is absent.

  • Make permissions of log files created by Patroni configurable (Alexander Kukushkin)

    You can set specific permissions for log files that Patroni creates. If you do not specify permissions, Patroni uses the current umask value.

  • Compatibility with PostgreSQL 17 beta3 (Alexander Kukushkin)

    GUC validation rules now support PostgreSQL 17 beta3. Patroni handles all new auxiliary backends during shutdown. It also sets dbname in primary_conninfo, as required for logical replication slot synchronization.

  • Implement --ignore-listen-port option for Patroni config validation (Sahil Naphade)

    Make it possible to ignore already bound ports when running patroni --validate-config.

Improvements

  • Make wal_log_hints configurable (Paul_Kim)

    When use_pg_rewind is off, you can disable wal_log_hints to avoid its overhead.

  • Log pg_basebackup command in DEBUG level (Waynerv)

    Facilitates failed initialization debugging.

Bugfixes

  • Advance permanent slots for cascading nodes while in failsafe (Alexander Kukushkin)

    When failsafe mode is active, advance slots for cascading replicas on the primary. Replica responses to POST /failsafe now include their xlog_location for this purpose.

  • Don’t let the current node be chosen as synchronous (Alexander Kukushkin)

    A client can stream from the current primary with an application_name that matches the primary name. Patroni previously handled this incorrectly. It could declare the primary as a synchronous node and block switchovers.

  • Ignore restapi.allowlist_include_members for POST /failsafe (Alexander Kukushkin)

  • Improve GUCs validation (Polina Bungina)

    Patroni previously validated GUCs with postgres --describe-config. As a result, its configuration could not set GUCs absent from that output. This limitation is removed.

  • Add line with localhost to .pgpass file when unix sockets are detected (Alexander Kukushkin)

    If host starts with /, Patroni adds a line to the .pgpass file. This handles the case where host matches the default socket directory path.

  • Fix logging issues (Waynerv)

    Defined proper request URL in failsafe handling logs and fixed the order of timestamps in postmaster check log.


Version 3.3.2

Released 2024-07-11

Bugfixes

  • Fix plain Postgres synchronous replication mode (Israel Barth Rubio)

    Plain Postgres synchronous replication did not work after Patroni introduced synchronous_mode. Patroni now uses the user-configured synchronous_standby_names value when synchronous_mode is disabled.

  • Handle logical slots invalidation on a standby (Polina Bungina)

    Since PG16, the horizon can invalidate logical replication slots on a standby. Patroni now forces a copy to recreate these invalidated slots.

  • Fix race condition with logical slot advance and copy (Alexander Kukushkin)

    This bug could cause repeated copies of an invalidated logical replication slot, with a PostgreSQL restart for each copy.


Version 3.3.1

Released 2024-06-17

Stability improvements

  • Compatibility with Python 3.12 (Alexander Kukushkin)

    Handle a new attribute added to logging.LogRecord.

Bugfixes

  • Fix infinite recursion in replicatefrom tags handling (Alexander Kukushkin)

    As a part of this fix, also improve is_physical_slot() check and adjust documentation.

  • Fix wrong role reporting in standby clusters (Alexander Kukushkin)

    synchronous_standby_names and synchronous replication work only on a real primary node. Postgres ignores them for cascading replication. Before this fix, patronictl list and GET /cluster incorrectly reported some nodes as synchronous.

  • Fix availability of the allow_in_place_tablespaces GUC (Polina Bungina)

    allow_in_place_tablespaces was not only added to PostgreSQL 15 but also backpatched to PostgreSQL 10-14.


Version 3.3.0

Released 2024-04-04

Warning

All older Partoni versions are not compatible with ydiff>=1.3.

There are the following options available to “fix” the problem:

  1. upgrade Patroni to the latest version
  2. install ydiff<1.3 after installing Patroni
  3. install cdiff module

New features

  • Add ability to pass auth_data to Zookeeper client (Aras Mumcuyan)

    It allows to specify the authentication credentials to use for the connection.

  • Add a contrib script for Barman integration (Israel Barth Rubio)

    The patroni_barman application performs remote Barman operations. It can serve as a custom bootstrap method, a custom replica method, or an on_role_change callback. See the integration documentation for more information.

  • Support JSON log format (alisalemmi)

    Apart from plain (default), Patroni now also supports json log format. Requires python-json-logger>=2.0.2 library to be installed.

  • Show pending_restart_reason information (Polina Bungina)

    Show more information about PostgreSQL parameters that set the pending_restart flag. patronictl list and the /patroni REST API endpoint now show parameter names and their differences as pending_restart_reason.

  • Implement nostream tag (Grigory Smolkin)

    If nostream is true, the node does not use the replication protocol to stream WAL. It uses archive recovery if restore_command is configured. The tag also disables permanent logical replication slot copying and synchronization on this node and all its cascading replicas.

Improvements

  • Implement validation of the log section (Alexander Kukushkin)

    Until now validator was not checking the correctness of the logging configuration provided.

  • Improve logging for PostgreSQL parameters change (Polina Bungina)

    Convert old values to a human-readable format and log information about the pg_controldata vs Patroni global configuration mismatch.

Bugfixes

  • Properly filter out not allowed pg_basebackup options (Israel Barth Rubio)

    Patroni did not correctly filter forbidden options for the basebackup replica bootstrap method when they used the - setting: value format.

  • Fix etcd3 authentication error handling (Alexander Kukushkin)

    Retry an etcd3 authentication error once, unless authentication occurred immediately before the request. Do not restart watchers during reauthentication.

  • Improve logic of the validator files discovery (Waynerv)

    Use importlib library to discover the files with available configuration parameters when possible (for Python 3.9+). This implementation is more stable and doesn’t break the Patroni distributions based on zip archives.

  • Use target_session_attrs only when multiple hosts are specified in the standby_cluster section (Alexander Kukushkin)

    target_session_attrs=read-write is now added to the primary_conninfo on the standby leader node only when standby_cluster.host section contains multiple hosts separated by commas.

  • Add compatibility code for ydiff library version 1.3+ (Alexander Kukushkin)

    Patroni uses a nonpublic API from ydiff. This API belongs to a terminal tool, not a Python module interface. The API change in version 1.3 broke older Patroni versions.


Version 3.2.2

Released 2024-01-17

Bugfixes

  • Don’t let replica restore initialize key when DCS was wiped (Alexander Kukushkin)

    It was happening in the method where Patroni was supposed to take over a standalone PG cluster.

  • Use consistent read when fetching just updated sync key from Consul (Alexander Kukushkin)

    Consul cannot immediately return ModifyIndex for a key that was just updated. Patroni must read the key explicitly. The default permits stale reads, so Patroni sometimes received an outdated key version.

  • Reload Postgres config if a parameter that requires restart was reset to the original value (Polina Bungina)

    Previously Patroni wasn’t updating the config, but only resetting the pending_restart.

  • Fix erroneous inverted logic of the confirmation prompt message when doing a failover to an async candidate in synchronous mode (Polina Bungina)

    The problem existed only in patronictl.

  • Exclude leader from failover candidates in patronictl (Polina Bungina)

    If the cluster is healthy, failing over to an existing leader is no-op.

  • Create Citus database and extension idempotently (Alexander Kukushkin, Zhao Junwang)

    This allows the post_bootstrap script to create the Citus database and extension when the database needs additional dependencies.

  • Don’t filter our contradictory nofailover tag (Polina Bungina)

    A node with {nofailover: false, failover_priority: 0} could not participate in the leader race. It should have been eligible because nofailover takes precedence.

  • Fixed PyInstaller frozen issue (Sophia Ruan)

    The freeze_support() was called after argparse and as a result, Patroni wasn’t able to start Postgres.

  • Fixed bug in the config generator for patronictl and Citus configuration (Israel Barth Rubio)

    It prevented patronictl and Citus configuration parameters set via environment variables from being written into the generated config.

  • Restore recovery GUCs and some Patroni-managed parameters when joining a running standby (Alexander Kukushkin)

    Patroni was failing to restart Postgres v12 onwards with an error about missing port in one of the internal structures.

  • Fixes around pending_restart flag (Polina Bungina)

    Do not expose pending_restart during custom bootstrap with recovery_target_action = promote. Also omit it when an external change affects hot_standby or wal_log_hints, for example through ALTER SYSTEM.


Version 3.2.1

Released 2023-11-30

Bugfixes

  • Limit accepted values for --format argument in patronictl (Alexander Kukushkin)

    It used to accept any arbitrary string and produce no output if the value wasn’t recognized.

  • Verify that replica nodes received checkpoint LSN on shutdown before releasing the leader key (Alexander Kukushkin)

    Previously, Patroni sometimes used the LSN of the SWITCH record. With archiving enabled, a CHECKPOINT record follows this record. As a result, the former primary sometimes needed pg_rewind. This did not cause data loss.

  • Do a real HTTP request when performing node name uniqueness check (Alexander Kukushkin)

    In containers, traffic can pass through docker-proxy, which listens on the port and accepts connections. This caused false positives in the uniqueness check.

  • Fixed Citus support with Etcd v2 (Alexander Kukushkin)

    Patroni was failing to deploy a new Citus cluster with Etcd v2.

  • Fixed pg_rewind behavior with Postgres v16+ (Alexander Kukushkin)

    The error message format of pg_waldump changed in v16 which caused pg_rewind to be called by Patroni even when it was not necessary.

  • Fixed bug with custom bootstrap (Alexander Kukushkin)

    Patroni was falsely applying --command argument, which is a bootstrap command itself.

  • Fixed the issue with REST API health check endpoints (Sophia Ruan)

    There were chances that after Postgres restart it could return unknown state for Postgres because connections were not properly closed.

  • Cache postgres --describe-config output results (Waynerv)

    These results identify the GUCs available for PostgreSQL configuration validation. The list is not expected to change while Patroni runs.


Version 3.2.0

Released 2023-10-25

Deprecation notice

  • The bootstrap.users support will be removed in version 4.0.0. If you need to create users after deploying a new cluster please use the bootstrap.post_bootstrap hook for that.

Breaking changes

  • Enforce loop_wait + 2*retry_timeout <= ttl rule and hard-code minimal possible values (Alexander Kukushkin)

    The minimum values are loop_wait=2, retry_timeout=3, and ttl=20. Patroni adjusts values below these minimums or values that violate the rule. It writes a warning to its logs.

New features

  • Failover priority (Mark Pekala)

    With the help of tags.failover_priority it’s now possible to make a node more preferred during the leader race. More details in the documentation (ref tags).

  • Implemented patroni --generate-config [--dsn DSN] and patroni --generate-sample-config (Polina Bungina)

    It allows to generate a config file for the running PostgreSQL cluster or a sample config file for the new Patroni cluster.

  • Use a dedicated connection to Postgres for Patroni REST API (Alexander Kukushkin)

    It helps to avoid blocking the main heartbeat loop if the system is under stress.

  • Enrich some endpoints with the name of the node (sskserk)

    For the monitoring endpoint name is added next to the scope and for metrics endpoint the name is added to tags.

  • Ensure strict failover/switchover difference (Polina Bungina)

    Be more precise in log messages and allow failing over to an asynchronous node in a healthy synchronous cluster.

  • Make permanent physical replication slots behave similarly to permanent logical slots (Alexander Kukushkin)

    Create permanent physical replication slots on all nodes eligible to become leader. On standby nodes, use pg_replication_slot_advance() to advance the slots’ restart_lsn.

  • Add capability of specifying namespace through --dcs argument in patronictl (Israel Barth Rubio)

    It could be handy if patronictl is used without a configuration file.

  • Add support for additional parameters in custom bootstrap configuration (Israel Barth Rubio)

    Previously it was only possible to add custom arguments to the command and now one could list them as a mapping.

Improvements

  • Set citus.local_hostname GUC to the same value which is used by Patroni to connect to the Postgres (Alexander Kukushkin)

    There are cases when Citus wants to have a connection to the local Postgres. By default it uses localhost, which is not always available.

Bugfixes

  • Ignore synchronous_mode setting in a standby cluster (Polina Bungina)

    Postgres doesn’t support cascading synchronous replication and not ignoring synchronous_mode was breaking a switchover in a standby cluster.

  • Handle SIGCHLD for on_reload callback (Alexander Kukushkin)

    Not doing so results in a zombie process, which is reaped only when the next on_reload is executed.

  • Handle AuthOldRevision error when working with Etcd v3 (Alexander Kukushkin, Kenny Do)

    The error is raised if Etcd is configured to use JWT and when the user database in Etcd is updated.


Version 3.1.2

Released 2023-09-26

Bugfixes

  • Fixed bug with wal_keep_size checks (Alexander Kukushkin)

    The wal_keep_size GUC normally has a unit. Patroni failed to cast its value to int. As a result, it did not write the bootstrap.dcs value to the /config key.

  • Detect and resolve inconsistencies between /sync key and synchronous_standby_names (Alexander Kukushkin)

    Patroni normally updates /sync and synchronous_standby_names in a specific order. A bug or a manual reset of synchronous_standby_names could make this state inconsistent. Failover to an asynchronous node was then possible.

  • Read GUC’s values when joining running Postgres (Alexander Kukushkin)

    When restarted in pause, Patroni removed synchronous_standby_names from postgresql.conf. Patroni now reads GUC values when it joins a running Postgres instance. This resolves the issue and helps prevent similar issues.

  • Silenced annoying warnings when checking for node uniqueness (Alexander Kukushkin)

    WARNING messages are produced by urllib3 if Patroni is quickly restarted.


Version 3.1.1

Released 2023-09-20

Bugfixes

  • Reset failsafe state on promote (ChenChangAo)

    A switchover or failover could occur shortly after failsafe mode started. The new primary then demoted itself when failsafe mode became inactive.

  • Silence useless warnings in patronictl (Alexander Kukushkin)

    patronictl could show incorrect warnings about global configuration values. This occurred when it used the same patroni.yaml file as Patroni and could access PGDATA.

  • Explicitly enable synchronous mode for a corner case (Alexander Kukushkin)

    Synchronous mode effectively was never activated if there are no replicas streaming from the primary.

  • Fixed bug with 0 integer values validation (Israel Barth Rubio)

    In most cases, it didn’t cause any issues, just warnings.

  • Don’t return logical slots for standby cluster (Alexander Kukushkin)

    Patroni can’t create logical replication slots in the standby cluster, thus they should be ignored if they are defined in the global configuration.

  • Avoid showing docstring in patronictl --help output (Israel Barth Rubio)

    The click module needs to get a special hint for that.

  • Fixed bug with kubernetes.standby_leader_label_value (Alexander Kukushkin)

    This feature effectively never worked.

  • Returned cluster system identifier to the patronictl list output (Polina Bungina)

    Citus support introduced this problem. Citus requires a hidden system identifier because the coordinator and each worker have different identifiers.

  • Override write_leader_optime method in Kubernetes implementation (Alexander Kukushkin)

    The method is supposed to write shutdown LSN to the leader Endpoint/ConfigMap when there are no healthy replicas available to become the new primary.

  • Don’t start stopped postgres in pause (Alexander Kukushkin)

    Due to a race condition, Patroni was falsely assuming that the standby should be restarted because some recovery parameters (primary_conninfo or similar) were changed.

  • Fixed bug in patronictl query command (Israel Barth Rubio)

    It didn’t work when only -m argument was provided or when none of -r or -m were provided.

  • Properly treat integer parameters that are used in the command line to start postgres (Polina Bungina)

    String values were not cast to integers. This caused incorrect max_prepared_transactions calculations based on max_connections for Citus clusters.

  • Don’t rely on pg_stat_wal_receiver when deciding on pg_rewind (Alexander Kukushkin)

    The received_tli value from pg_stat_wal_receiver could be ahead of the actual replayed timeline. The timeline from DENTIFY_SYSTEM through a replication connection is always correct.


Version 3.1.0

Released 2023-08-03

Breaking changes

  • Changed semantic of restapi.keyfile and restapi.certfile (Alexander Kukushkin)

    Previously, Patroni used restapi.keyfile and restapi.certfile as fallback client certificates when the corresponding ctl parameters were absent.

Warning

If restapi.verify_client is required, client certificate validation is enabled. You must also supply valid client certificates in ctl.certfile, ctl.keyfile, and ctl.keyfile_password. Otherwise, Patroni will not work correctly.

New features

  • Make Pod role label configurable (Waynerv)

    Set label values with kubernetes.leader_label_value, kubernetes.follower_label_value, and kubernetes.standby_leader_label_value. This supports the planned change from the master role to primary. See the feature and migration steps.

Improvements

  • Various improvements of patroni --validate-config (Alexander Kukushkin)

    Improved parameter validation for different DCS, bootstrap.dcs , ctl, restapi, and watchdog sections.

  • Start Postgres not in recovery if it crashed during recovery while Patroni is running (Alexander Kukushkin)

    It may reduce recovery time and will help to prevent unnecessary timeline increments.

  • Avoid unnecessary updates of /status key (Alexander Kukushkin)

    Without permanent logical slots, Patroni previously updated /status on every heartbeat loop. It did so even when the primary LSN did not advance.

  • Don’t allow stale primary to win the leader race (Alexander Kukushkin)

    Patroni can stop responding for a long time because of insufficient resources. Before acquiring the leader lock, it now checks whether another node promoted Postgres.

  • Implemented visibility of certain PostgreSQL parameters validation (Alexander Kukushkin, Feike Steenbergen)

    Patroni used a suitable default when validation failed for max_connections, max_wal_senders, max_prepared_transactions, max_locks_per_transaction, max_replication_slots, or max_worker_processes. It now also shows a warning.

  • Set permissions for files and directories created in PGDATA (Alexander Kukushkin)

    Patroni previously created files with owner read/write permissions only. This broke backup tools that ran as another user and depended on group read permissions. Patroni now uses the permissions on PGDATA to set permissions for files and directories that it creates inside PGDATA.

Bugfixes

  • Run archive_command through shell (Waynerv)

    Patroni can archive WAL segments before single-user crash recovery or before pg_rewind. Previously, archive_command did not work with shell operators such as &&.

  • Fixed “on switchover” shutdown checks (Polina Bungina)

    It was possible that specified candidate is still streaming and didn’t received shut down checking but the leader key was removed because some other nodes were healthy.

  • Fixed “is primary” check (Alexander Kukushkin)

    During the leader race replicas were not able to recognize that Postgres on the old leader is still running as a primary.

  • Fixed patronictl list (Alexander Kukushkin)

    The Cluster name field was missing in tsv, json, and yaml output formats.

  • Fixed pg_rewind behaviour after pause (Alexander Kukushkin)

    Under certain conditions, Patroni wasn’t able to join the false primary back to the cluster with pg_rewind after coming out of maintenance mode.

  • Fixed bug in Etcd v3 implementation (Alexander Kukushkin)

    Invalidate internal KV cache if key update performed using create_revision/mod_revision field due to revision mismatch.

  • Fixed behaviour of replicas in standby cluster in pause (Alexander Kukushkin)

    When the leader key expires replicas in standby cluster will not follow the remote node but keep primary_conninfo as it is.


Version 3.0.4

Released 2023-07-13

New features

  • Make the replication status of standby nodes visible (Alexander Kukushkin)

    For PostgreSQL 9.6+, Patroni reports streaming when a standby streams from another node. It reports in archive recovery when no replication connection exists and restore_command is set. The state appears in DCS member keys, the REST API, and patronictl list output.

Improvements

  • Improved error messages with Etcd v3 (Alexander Kukushkin)

    When Etcd v3 cluster isn’t accessible Patroni was reporting that it can’t access /v2 endpoints.

  • Use quorum read in patronictl if it is possible (Alexander Kukushkin)

    Etcd or Consul clusters could become read-only without patronictl reporting a problem. It now fails with an error.

  • Prevent splitbrain from duplicate names in configuration (Mark Pekala)

    At startup, Patroni checks whether DCS has a registered node with the same name. It tries to query that node’s REST API. If the API is accessible, Patroni exits with an error. This helps protect against configuration mistakes.

  • Start Postgres not in recovery if it crashed while Patroni is running (Alexander Kukushkin)

    It may reduce recovery time and will help from unnecessary timeline increments.

Bugfixes

  • REST API SSL certificate were not reloaded upon receiving a SIGHUP (Israel Barth Rubio)

    Regression was introduced in 3.0.3.

  • Fixed integer GUCs validation for parameters like max_connections (Feike Steenbergen)

    Patroni didn’t like quoted numeric values. Regression was introduced in 3.0.3.

  • Fix issue with synchronous_mode (Alexander Kukushkin)

    Execute txid_current() with synchronous_commit=off so it doesn’t accidentally wait for absent synchronous standbys when synchronous_mode_strict is enabled.


Version 3.0.3

Released 2023-06-22

New features

  • Compatibility with PostgreSQL 16 beta1 (Alexander Kukushkin)

    Extended GUC’s validator rules.

  • Make PostgreSQL GUC’s validator extensible (Israel Barth Rubio)

    Validator rules are loaded from YAML files located in patroni/postgresql/available_parameters/ directory. Files are ordered in alphabetical order and applied one after another. It makes possible to have custom validators for non-standard Postgres distributions.

  • Added restapi.request_queue_size option (Andrey Zhidenkov, Aleksei Sukhov)

    Sets request queue size for TCP socket used by Patroni REST API. Once the queue is full, further requests get a “Connection denied” error. The default value is 5.

  • Call initdb directly when initializing a new cluster (Matt Baker)

    Previously it was called via pg_ctl, what required a special quoting of parameters passed to initdb.

  • Added before stop hook (Le Duane)

    The hook could be configured via postgresql.before_stop and is executed right before pg_ctl stop. The exit code doesn’t impact shutdown process.

  • Added support for custom Postgres binary names (Israel Barth Rubio, Polina Bungina)

    A custom Postgres distribution can use different binary names from the community distribution. Configure these names with postgresql.bin_name.* and the PATRONI_POSTGRESQL_BIN_* environment variables.

Improvements

  • Various improvements of patroni --validate-config (Polina Bungina)

    • Make bootstrap.initdb optional. It is only required for new clusters, but patroni --validate-config was complaining if it was missing in the config.
    • Don’t error out when postgresql.bin_dir is empty or not set. Try to first find Postgres binaries in the default PATH instead.
    • Make postgresql.authentication.rewind section optional. If it is missing, Patroni is using the superuser.
  • Improved error reporting in patronictl (Israel Barth Rubio)

    The \n symbol was rendered as it is, instead of the actual newline symbol.

Bugfixes

  • Fixed issue in Citus support (Alexander Kukushkin)

    During switchover, the promoted worker calls the coordinator REST API. If this call failed, the Citus group remained blocked indefinitely.

  • Allow etcd3 URL in --dcs-url option of patronictl (Israel Barth Rubio)

    If users attempted to pass a etcd3 URL through --dcs-url option of patronictl they would face an exception.


Version 3.0.2

Released 2023-03-24

Warning

Version 3.0.2 dropped support of Python older than 3.6.

New features

  • Added sync standby replica status to /metrics endpoint (Thomas von Dein, Alexander Kukushkin)

    Before were only reporting primary/standby_leader/replica.

  • User-friendly handling of PAGER in patronictl (Israel Barth Rubio)

    It makes pager configurable via PAGER environment variable, which overrides default less and more.

  • Make K8s retriable HTTP status code configurable (Alexander Kukushkin)

    On some managed platforms it is possible to get status code 401 Unauthorized, which sometimes gets resolved after a few retries.

Improvements

  • Set hot_standby to off during custom bootstrap only if recovery_target_action is set to promote (Alexander Kukushkin)

    It was necessary to make recovery_target_action=pause work correctly.

  • Don’t allow on_reload callback to kill other callbacks (Alexander Kukushkin)

    on_start/on_stop/on_role_change are usually used to add/remove Virtual IP and on_reload should not interfere with them.

  • Switched to IMDSFetcher in aws callback example script (Polina Bungina)

    The IMDSv2 requires a token to work with and the IMDSFetcher handles it transparently.

Bugfixes

  • Fixed patronictl switchover on Citus cluster running on Kubernetes (Lukáš Lalinský)

    It didn’t work for namespaces different from default.

  • Don’t write to PGDATA if major version is not known (Alexander Kukushkin)

    PGDATA could be empty immediately after startup, for example before storage was mounted. Patroni then inferred an incorrect PostgreSQL version. It created recovery.conf even when the actual major version was v10+.

  • Fixed bug with Citus metadata after coordinator failover (Alexander Kukushkin)

    The citus_set_coordinator_host() call doesn’t cause metadata sync and the change was invisible on worker nodes. The issue is solved by switching to citus_update_node().

  • Use etcd hosts listed in the config file as a fallback when all etcd nodes “failed” (Alexander Kukushkin)

    Patroni follows etcd topology changes. If all nodes become unreachable, it retries with the configured nodes and the last known topology.


Version 3.0.1

Released 2023-02-16

Bugfixes

  • Pass proper role name to an on_role_change callback script’. (Alexander Kukushkin, Polina Bungina)

    Patroni used to erroneously pass promoted role to an on_role_change callback script on promotion. The passed role name changed back to master. This regression was introduced in 3.0.0.


Version 3.0.0

Released 2023-01-30

This version adds integration with Citus and makes it possible to survive temporary DCS outages without demoting primary.

Warning
  • Version 3.0.0 is the last release supporting Python 2.7. Upcoming release will drop support of Python versions older than 3.7.

  • The RAFT support is deprecated. We will do our best to maintain it, but take neither guarantee nor responsibility for possible issues.

  • This version is the first step in getting rid of the “master”, in favor of “primary”. Upgrading to the next major release will work reliably only if you run at least 3.0.0.

New features

  • DCS failsafe mode (Alexander Kukushkin, Polina Bungina)

    If the feature is enabled it will allow Patroni cluster to survive temporary DCS outages. You can find more details in the documentation.

  • Citus support (Alexander Kukushkin, Polina Bungina, Jelte Fennema)

    Patroni enables easy deployment and management of Citus clusters with HA. Please check here page for more information.

Improvements

  • Suppress recurring errors when dropping unknown but active replication slots (Michael Banck)

    Patroni will still write these logs, but only in DEBUG.

  • Run only one monitoring query per HA loop (Alexander Kukushkin)

    It wasn’t the case if synchronous replication is enabled.

  • Keep only latest failed data directory (William Albertus Dembo)

    After bootstrap failure, Patroni previously renamed the $PGDATA folder with a timestamp suffix. It now uses .failed. If that folder already exists, Patroni removes it before renaming.

  • Improved check of synchronous replication connections (Alexander Kukushkin)

    A new host in synchronous_standby_names must catch up with the primary before Patroni marks it synchronous in DCS. It must also report pg_stat_replication.sync_state = 'sync'.

Removed functionality

  • Remove patronictl scaffold (Alexander Kukushkin)

    The only reason for having it was a hacky way of running standby clusters.


Version 2.1.7

Released 2023-01-04

Bugfixes

  • Fixed little incompatibilities with legacy python modules (Alexander Kukushkin)

    They prevented from building/running Patroni on Debian buster/Ubuntu bionic.


Version 2.1.6

Released 2022-12-30

Improvements

  • Fix annoying exceptions on ssl socket shutdown (Alexander Kukushkin)

    The HAProxy is closing connections as soon as it got the HTTP Status code leaving no time for Patroni to properly shutdown SSL connection.

  • Adjust example Dockerfile for arm64 (Polina Bungina)

    Remove explicit amd64 and x86_64, don’t remove libnss_files.so.*.

Security improvements

  • Enforce search_path=pg_catalog for non-replication connections (Alexander Kukushkin)

    Patroni depends heavily on superuser connections. A user-defined function or operator in public could match a pg_catalog object’s name and signature to attack these connections. To protect them, Patroni enforces search_path=pg_catalog for all connections except replication connections.

  • Prevent passwords from being recorded in pg_stat_statements (Feike Steenbergen)

    It is achieved by setting pg_stat_statements.track_utility=off when creating users.

Bugfixes

  • Declare proxy_address as optional (Denis Laxalde)

    As it is effectively a non-required option.

  • Improve behaviour of the insecure option (Alexander Kukushkin)

    Ctl’s insecure option didn’t work properly when client certificates were used for REST API requests.

  • Take watchdog configuration from bootstrap.dcs when the new cluster is bootstrapped (Matt Baker)

    Patroni used to initially configure watchdog with defaults when bootstrapping a new cluster rather than taking configuration used to bootstrap the DCS.

  • Fix the way file extensions are treated while finding executables in WIN32 (Martín Marqués)

    Only add .exe to a file name if it has no extension yet.

  • Fix Consul TTL setup (Alexander Kukushkin)

    Patroni set ttl/2.0 on the HTTPClient but did not multiply the current value by 2 in the class property. The Consul TTL was therefore incorrect by a factor of two.

Removed functionality

  • Remove patronictl configure (Polina Bungina)

    There is no more need for a separate patronictl config creation.


Version 2.1.5

Released 2022-11-28

This version enhances compatibility with PostgreSQL 15 and declares Etcd v3 support as production ready. The Patroni on Raft remains in Beta.

New features

  • Improve patroni --validate-config (Denis Laxalde)

    Exit with code 1 if config is invalid and print errors to stderr.

  • Don’t drop replication slots in pause (Alexander Kukushkin)

    Patroni is automatically creating/removing physical replication slots when members are joining/leaving the cluster. In pause slots will no longer be removed.

  • Support the HEAD request method for monitoring endpoints (Robert Cutajar)

    If used instead of GET Patroni will return only the HTTP Status Code.

  • Support behave tests on Windows (Alexander Kukushkin)

    Emulate graceful Patroni shutdown (SIGTERM) on Windows by introduce the new REST API endpoint POST /sigterm.

  • Introduce postgresql.proxy_address (Alexander Kukushkin)

    It will be written to the member key in DCS as the proxy_url and could be used/useful for service discovery.

Stability improvements

  • Call pg_replication_slot_advance() from a thread (Alexander Kukushkin)

    On busy clusters with many logical replication slots, pg_replication_slot_advance() delayed the main HA loop. This could cause the member key to expire.

  • Archive possibly missing WALs before calling pg_rewind on the old primary (Polina Bungina)

    After a long primary outage, WAL files could be absent from both the archive and the new primary. pg_rewind could remove these files from the old primary. The old primary then could not start as a standby. Archiving ready WAL files reduces this risk and improves continuous archiving.

  • Ignore 403 errors when trying to create Kubernetes Service (Nick Hudson, Polina Bungina)

    Patroni was spamming logs by unsuccessful attempts to create the service, which in fact could already exist.

  • Improve liveness probe (Alexander Kukushkin)

    The liveness probe fails if the heartbeat loop exceeds ttl on the primary or 2\*ttl on a replica. This allows its use as an alternative to watchdog on Kubernetes.

  • Make sure only sync node tries to grab the lock when switchover (Alexander Kukushkin, Polina Bungina)

    Previously, an up-to-date asynchronous member had a small chance of becoming leader during a manual switchover without a specified target.

  • Avoid cloning while bootstrap is running (Ants Aasma)

    Do not allow a create replica method that does not require a leader to be triggered while the cluster bootstrap is running.

  • Compatibility with kazoo-2.9.0 (Alexander Kukushkin)

    Depending on the Python version, SequentialThreadingHandler.select() can raise TypeError or IOError when select() uses a closed socket.

  • Explicitly shut down SSL connection before socket shutdown (Alexander Kukushkin)

    Not doing it resulted in unexpected eof while reading errors with OpenSSL 3.0.

  • Compatibility with prettytable\>=2.2.0 (Alexander Kukushkin)

    Due to the internal API changes the cluster name header was shown on the incorrect line.

Bugfixes

  • Handle expired token for Etcd lease_grant (monsterxx03)

    In case of error get the new token and retry request.

  • Fix bug in the GET /read-only-sync endpoint (Alexander Kukushkin)

    It was introduced in previous release and effectively never worked.

  • Handle the case when data dir storage disappeared (Alexander Kukushkin)

    Patroni periodically checks that PGDATA exists and is not empty. A storage failure could make os.listdir() raise OSError, which broke the heartbeat loop.

  • Apply master_stop_timeout when waiting for user backends to close (Alexander Kukushkin)

    Something that looks like user backend could be in fact a background worker (e.g., Citus Maintenance Daemon) that is failing to stop.

  • Accept *:<port> for postgresql.listen (Denis Laxalde)

    The patroni --validate-config was complaining about it being invalid.

  • Timeouts fixes in Raft (Alexander Kukushkin)

    When Patroni or patronictl are starting they try to get Raft cluster topology from known members. These calls were made without proper timeouts.

  • Forcefully update consul service if token was changed (John A. Lotoski)

    Not doing so results in errors “rpc error making call: rpc error making call: ACL not found”.


Version 2.1.4

Released 2022-06-01

New features

  • Improve pg_rewind behavior on typical Debian/Ubuntu systems (Gunnar “Nick” Bluth)

    On Postgres setups that keep postgresql.conf outside of the data directory (e.g. Ubuntu/Debian packages), pg_rewind --restore-target-wal fails to figure out the value of the restore_command.

  • Allow setting TLSServerName on Consul service checks (Michael Gmelin)

    Useful when checks are performed by IP and the Consul node_name is not a FQDN.

  • Added ppc64le support in watchdog (Jean-Michel Scheiwiler)

    And fixed watchdog support on some non-x86 platforms.

  • Switched aws.py callback from boto to boto3 (Alexander Kukushkin)

boto 2.x is abandoned since 2018 and fails with python 3.9.

  • Periodically refresh service account token on K8s (Haitao Li)

    Since Kubernetes v1.21 service account tokens expire in 1 hour.

  • Added /read-only-sync monitoring endpoint (Dennis4b)

    It is similar to the /read-only but includes only synchronous replicas.

Stability improvements

  • Don’t copy the logical replication slot to a replica if there is a configuration mismatch in the logical decoding setup with the primary (Alexander Kukushkin)

    A replica no longer copies a logical replication slot if it does not match the plugin or database configuration. Previously, Patroni checked these options only after copying the slot and starting the replica with it. This caused repeated unnecessary restarts.

  • Special handling of recovery configuration parameters for PostgreSQL v12+ (Alexander Kukushkin)

    When starting as a replica, Patroni caches the current recovery parameters instead of querying pg_settings. This lets it update postgresql.conf and restart or reload when the leader address changes.

  • Better handling of IPv6 addresses in the postgresql.listen parameters (Alexander Kukushkin)

    The listen parameter includes a port, so users can put IPv6 addresses in square brackets. Patroni did not correctly remove these brackets from lists with multiple IP addresses.

  • Use replication credentials when performing divergence check only on PostgreSQL v10 and older (Alexander Kukushkin)

    If rewind is enabled, Patroni will again use either superuser or rewind credentials on newer Postgres versions.

Bugfixes

  • Fixed missing import of dateutil.parser (Wesley Mendes)

    Tests weren’t failing only because it was also imported from other modules.

  • Ensure that optime annotation is a string (Sebastian Hasler)

    In certain cases Patroni was trying to pass it as numeric.

  • Better handling of failed pg_rewind attempt (Alexander Kukushkin)

    If the primary becomes unavailable during pg_rewind, $PGDATA will be left in a broken state. Following that, Patroni will remove the data directory even if this is not allowed by the configuration.

  • Don’t remove slots annotations from the leader ConfigMap/Endpoint when PostgreSQL isn’t ready (Alexander Kukushkin)

    If slots value isn’t passed the annotation will keep the current value.

  • Handle concurrency problem with K8s API watchers (Alexander Kukushkin)

    Watchers can become stale under unknown conditions. As a result, attempt_to_acquire_leader() could fail with HTTP status code 409. Patroni now resets watcher connections and restarts the watchers in this case.


Version 2.1.3

Released 2022-02-18

New features

  • Added support for encrypted TLS keys for patronictl (Alexander Kukushkin)

    It could be configured via ctl.keyfile_password or the PATRONI_CTL_KEYFILE_PASSWORD environment variable.

  • Added more metrics to the /metrics endpoint (Alexandre Pereira)

    Specifically, patroni_pending_restart and patroni_is_paused.

  • Make it possible to specify multiple hosts in the standby cluster configuration (Michael Banck)

    A standby cluster that replicates from a Patroni cluster can use client-side failover, available in libpq since PostgreSQL v10. The standby leader’s primary_conninfo and pg_rewind connection strings set target_session_attrs=read-write. The generated pgpass file has one line per host. The standby cluster waits for pg_control updates instead of calling CHECKPOINT on primary cluster nodes.

Stability improvements

  • Compatibility with legacy psycopg2 (Alexander Kukushkin)

    For example, the psycopg2 installed from Ubuntu 18.04 packages doesn’t have the UndefinedFile exception yet.

  • Restart etcd3 watcher if all Etcd nodes don’t respond (Alexander Kukushkin)

    If the watcher is alive the get_cluster() method continues returning stale information even if all Etcd nodes are failing.

  • Don’t remove the leader lock in the standby cluster while paused (Alexander Kukushkin)

    Previously the lock was maintained only by the node that was running as a primary and not a standby leader.

Bugfixes

  • Fixed bug in the standby-leader bootstrap (Alexander Kukushkin)

    Patroni was considering bootstrap as failed if Postgres didn’t start accepting connections after 60 seconds. The bug was introduced in the 2.1.2 release.

  • Fixed bug with failover to a cascading standby (Alexander Kukushkin)

    When figuring out which slots should be created on cascading standby we forgot to take into account that the leader might be absent.

  • Fixed small issues in Postgres config validator (Alexander Kukushkin)

    Integer parameters introduced in PostgreSQL v14 were failing to validate because min and max values were quoted in the validator.py

  • Use replication credentials when checking leader status (Alexander Kukushkin)

    It could be that the remove_data_directory_on_diverged_timelines is set, but there is no rewind_credentials defined and superuser access between nodes is not allowed.

  • Fixed “port in use” error on REST API certificate replacement (Ants Aasma)

    Certificate replacement could race with a concurrent API request. An active request during replacement caused a port-in-use error. Patroni then remained without an active API server.

  • Fixed a bug in cluster bootstrap if passwords contain % characters (Bastien Wirtz)

    Bootstrap executes a DO block with properly quoted parameters. However, cursor.execute() failed when it received an empty parameter list.

  • Fixed the “AttributeError: no attribute ’leader’” exception (Hrvoje Milković)

    It could happen if the synchronous mode is enabled and the DCS content was wiped out.

  • Fix bug in divergence timeline check (Alexander Kukushkin)

    Patroni incorrectly assumed that timelines had diverged. This did not affect pg_rewind. However, it caused reinitialization of the former leader when pg_rewind was disallowed and remove_data_directory_on_diverged_timelines was set.


Version 2.1.2

Released 2021-12-03

New features

  • Compatibility with psycopg>=3.0 (Alexander Kukushkin)

    By default psycopg2 is preferred. psycopg\>=3.0 will be used only if psycopg2 is not available or its version is too old.

  • Add dcs_last_seen field to the REST API (Michael Banck)

    This field notes the last time (as unix epoch) a cluster member has successfully communicated with the DCS. This is useful to identify and/or analyze network partitions.

  • Release the leader lock when pg_controldata reports “shut down” (Alexander Kukushkin)

    A slow or failing archive_command can delay switchover or shutdown. Patroni now removes the leader key when pg_controldata reports PGDATA as cleanly shut down and a replica has received all changes. If no replica meets this condition, Patroni retains the old behavior and continues to update the leader lock.

  • Add sslcrldir connection parameter support (Kostiantyn Nemchenko)

    The new connection parameter was introduced in the PostgreSQL v14.

  • Allow setting ACLs for ZNodes in Zookeeper (Alwyn Davis)

    Introduce a new configuration option zookeeper.set_acls so that Kazoo will apply a default ACL for each ZNode that it creates.

Stability improvements

  • Delay the next attempt of recovery till next HA loop (Alexander Kukushkin)

    If Postgres crashed due to out of disk space (for example) and fails to start because of that Patroni is too eagerly trying to recover it flooding logs.

  • Add log before demoting, which can take some time (Michael Banck)

    It can take some time for the demote to finish and it might not be obvious from looking at the logs what exactly is going on.

  • Improve “I am” status messages (Michael Banck)

    no action. I am a secondary ({0}) vs no action. I am ({0}), a secondary

  • Cast to int wal_keep_segments when converting to wal_keep_size (Jorge Solórzano)

    Global dynamic configuration can specify wal_keep_segments as a string. Python multiplied that string instead of its numeric value. For example, wal_keep_segments: "100" became 100100100100100100100100100100100100100100100100MB.

  • Allow switchover only to sync nodes when synchronous replication is enabled (Alexander Kukushkin)

    In addition to that do the leader race only against known synchronous nodes.

  • Use cached role as a fallback when Postgres is slow (Alexander Kukushkin)

    Postgres can become so slow that a monitoring query takes more than a few seconds. Patroni did not correctly handle the resulting statement_timeout exception. It could fail to demote Postgres on time after leader key expiration or update failure. Patroni now uses the cached role after this exception to determine whether Postgres is primary.

  • Avoid unnecessary updates of the member ZNode (Alexander Kukushkin)

    If no values have changed in the members data, the update should not happen.

  • Optimize checkpoint after promote (Alexander Kukushkin)

    Avoid doing CHECKPOINT if the latest timeline is already stored in pg_control. It helps to avoid unnecessary CHECKPOINT right after initializing the new cluster with initdb.

  • Prefer members without nofailover when picking sync nodes (Alexander Kukushkin)

    Previously, Patroni selected synchronous nodes only by replication lag. A node with nofailover had the same chance of selection as any other node. This was confusing and dangerous because primary failure could then prevent automatic failover.

  • Remove duplicate hosts from the etcd machine cache (Michael Banck)

    An etcd cluster can advertise incorrectly configured client URLs. Patroni now removes duplicate hosts from its cache.

Bugfixes

  • Skip temporary replication slots while doing slot management (Alexander Kukushkin)

    From v10, pg_basebackup creates a temporary replication slot for WAL streaming. Patroni tried to drop this slot because its name was unknown. Patroni now excludes all temporary slots when querying pg_stat_replication_slots.

  • Ensure pg_replication_slot_advance() doesn’t timeout (Alexander Kukushkin)

    Patroni used the default statement_timeout for this call. After failure, the call was very unlikely to recover. This increased pg_wal size and caused pg_catalog bloat.

  • The /status wasn’t updated on demote (Alexander Kukushkin)

    After demoting PostgreSQL the old leader updates the last LSN in DCS. Starting from 2.1.0 the new /status key was introduced, but the optime was still written to the /optime/leader.

  • Handle DCS exceptions when demoting (Alexander Kukushkin)

    Patroni demotes the master after a leader lock update fails. If DCS then becomes completely unavailable, get_cluster() can raise an exception. Incorrect handling left Postgres stopped until DCS recovered.

  • The use_unix_socket_repl didn’t work is some cases (Alexander Kukushkin)

    Specifically, if postgresql.unix_socket_directories is not set. In this case Patroni is supposed to use the default value from libpq.

  • Fix a few issues with Patroni REST API (Alexander Kukushkin)

    An undefined clusters_unlocked sometimes caused exceptions in GET /metrics. Error handling also assumed that connect_address always contained two elements. IPv6 addresses can contain more elements.

  • Wait for newly promoted node to finish recovery before deciding to rewind (Alexander Kukushkin)

    It could take some time before the actual promote happens and the new timeline is created. Without waiting replicas could come to the conclusion that rewind isn’t required.

  • Handle missing timelines in a history file when deciding to rewind (Alexander Kukushkin)

    If the current replica timeline is missing in the history file on the primary the replica was falsely assuming that rewind isn’t required.


Version 2.1.1

Released 2021-08-19

New features

  • Support for ETCD SRV name suffix (David Pavlicek)

    Etcd allows to differentiate between multiple Etcd clusters under the same domain and from now on Patroni also supports it.

  • Enrich history with the new leader (huiyalin525)

    It adds the new column to the patronictl history output.

  • Make the CA bundle configurable for in-cluster Kubernetes config (Aron Parsons)

    By default Patroni is using /var/run/secrets/kubernetes.io/serviceaccount/ca.crt and this new feature allows specifying the custom kubernetes.cacert.

  • Support dynamically registering/deregistering as a Consul service and changing tags (Tommy Li)

    Previously it required Patroni restart.

Bugfixes

  • Avoid unnecessary reload of REST API (Alexander Kukushkin)

    The previous release added a feature of reloading REST API certificates if changed on disk. Unfortunately, the reload was happening unconditionally right after the start.

  • Don’t resolve cluster members when etcd.use_proxies is set (Alexander Kukushkin)

    At startup, Patroni queries the Etcd member list to check cluster health. It also resolved member hostnames. This was unnecessary through a proxy and caused unnecessary warnings.

  • Skip rows with NULL values in the pg_stat_replication (Alexander Kukushkin)

    It seems that the pg_stat_replication view could contain NULL values in the replay_lsn, flush_lsn, or write_lsn fields even when state = 'streaming'.


Version 2.1.0

Released 2021-07-06

This version adds PostgreSQL v14 compatibility and preserves logical replication slots across failover and switchover. It adds REST API allowlists and reduces normal logs to one line per heartbeat.

New features

  • Compatibility with PostgreSQL v14 (Alexander Kukushkin)

    Unpause WAL replay if Patroni is not in a “pause” mode itself. It could be “paused” due to the change of certain parameters like for example max_connections on the primary.

  • Failover logical slots (Alexander Kukushkin)

    Logical replication slots can now survive failover and switchover on PostgreSQL v11+. Patroni copies the slot from primary to replica with a restart. It then advances the slot with pg_replication_slot_advance(). Thus, the slot exists before failover and no events should be lost. Some events can be delivered more than once.

  • Implemented allowlist for Patroni REST API (Alexander Kukushkin)

    If configured, only IP’s that matching rules would be allowed to call unsafe endpoints. In addition to that, it is possible to automatically include IP’s of members of the cluster to the list.

  • Added support of replication connections via unix socket (Mohamad El-Rifai)

    Previously Patroni was always using TCP for replication connection what could cause some issues with SSL verification. Using unix sockets allows exempt replication user from SSL verification.

  • Health check on user-defined tags (Arman Jafari Tehrani)

    You can specify any number of custom tags with the predefined tags:. These appear in patronictl list and the REST API. Custom tags can now be used in health checks.

  • Added Prometheus /metrics endpoint (Mark Mercado, Michael Banck)

    The endpoint exposing the same metrics as /patroni.

  • Reduced chattiness of Patroni logs (Alexander Kukushkin)

    When everything goes normal, only one line will be written for every run of HA loop.

Breaking changes

  • The old permanent logical replication slots feature will no longer work with PostgreSQL v10 and older (Alexander Kukushkin)

    The strategy of creating the logical slots after performing a promotion can’t guaranty that no logical events are lost and therefore disabled.

  • The /leader endpoint always returns 200 if the node holds the lock (Alexander Kukushkin)

    Previously, standby cluster promotion required changes to load-balancer health checks. These changes were inconvenient and easy to forget. The /leader endpoint now returns 200 whether the cluster is normal or a standby_cluster.

Improvements in Raft support

  • Reliable support of Raft traffic encryption (Alexander Kukushkin)

    Due to the different issues in the PySyncObj the encryption support was very unstable

  • Handle DNS issues in Raft implementation (Alexander Kukushkin)

    self_addr and partner_addrs can use DNS names instead of IP addresses. PySyncObj previously resolved these names only when creating the object. This caused problems when a node returned with a different IP address.

Stability improvements

  • Compatibility with psycopg2-2.9+ (Alexander Kukushkin)

    In psycopg2 the autocommit = True is ignored in the with connection block, which breaks replication protocol connections.

  • Fix excessive HA loop runs with Zookeeper (Alexander Kukushkin)

    Update of member ZNodes was causing a chain reaction and resulted in running the HA loops multiple times in a row.

  • Reload if REST API certificate is changed on disk (Michael Todorovic)

    If the REST API certificate file was updated in place Patroni didn’t perform a reload.

  • Don’t create pgpass dir if kerberos auth is used (Kostiantyn Nemchenko)

    Kerberos and password authentication are mutually exclusive.

  • Fixed little issues with custom bootstrap (Alexander Kukushkin)

    Start Postgres with hot_standby=off only when we do a PITR and restart it after PITR is done.

Bugfixes

  • Compatibility with kazoo-2.7+ (Alexander Kukushkin)

    Patroni handles retries itself. It depends on the old kazoo behavior that immediately discards Zookeeper requests when no connection is available.

  • Explicitly request the version of Etcd v3 cluster when it is known that we are connecting via proxy (Alexander Kukushkin)

    Patroni connects to Etcd v3 through gPRC-gateway. The cluster version determines the endpoint: /v3, /v3beta, or /v3alpha. Previously, Patroni resolved the version only during topology discovery. Connections through a proxy did not perform that discovery.


Version 2.0.2

Released 2021-02-22

New features

  • Ability to ignore externally managed replication slots (James Coleman)

    Patroni tries to remove unknown replication slots. Some slots need external management. You can now configure slots that Patroni must retain.

  • Added support for cipher suite limitation for REST API (Gunnar “Nick” Bluth)

    It could be configured via restapi.ciphers or the PATRONI_RESTAPI_CIPHERS environment variable.

  • Added support for encrypted TLS keys for REST API (Jonathan S. Katz)

    It could be configured via restapi.keyfile_password or the PATRONI_RESTAPI_KEYFILE_PASSWORD environment variable.

  • Constant time comparison of REST API authentication credentials (Alex Brasetvik)

    Use hmac.compare_digest() instead of ==, which is vulnerable to timing attack.

  • Choose synchronous nodes based on replication lag (Krishna Sarabu)

    If the replication lag on the synchronous node starts exceeding the configured threshold it could be demoted to asynchronous and/or replaced by the other node. Behaviour is controlled with maximum_lag_on_syncnode.

Stability improvements

  • Start postgres with hot_standby = off when doing custom bootstrap (Igor Yanchenko)

    During custom bootstrap, Patroni restores the basebackup, starts Postgres, and waits for recovery. Some standby parameters cannot be smaller than their primary values. If a value restored from WAL exceeds the configured value, Postgres panics and stops. Custom bootstrap now runs without hot_standby mode to avoid this problem.

  • Warn the user if the required watchdog is not healthy (Nicolas Thauvin)

    When the watchdog device is not writable or missing in required mode, the member cannot be promoted. Added a warning to show the user where to search for this misconfiguration.

  • Better verbosity for single-user mode recovery (Alexander Kukushkin)

    After an unclean PostgreSQL shutdown, Patroni can perform crash recovery in single-user mode. Recovery failures, such as insufficient disk space, previously did not expose their errors.

  • Added compatibility with python-consul2 module (Alexander Kukushkin, Wilfried Roset)

    python-consul has not been maintained for several years. A fork provides new features and bug fixes.

  • Don’t use bypass_api_service when running patronictl (Alexander Kukushkin)

    A K8s pod outside the default namespace might lack permission to query the kubernetes endpoint. Patroni then warns and ignores bypass_api_service. This warning was unnecessary for patronictl.

  • Create raft.data_dir if it doesn’t exists or make sure that it is writable (Mark Mercado)

    Improves user-friendliness and usability.

Bugfixes

  • Don’t interrupt restart or promote if lost leader lock in pause (Alexander Kukushkin)

    In pause it is allowed to run postgres as primary without lock.

  • Fixed issue with shutdown_request() in the REST API (Nicolas Limage)

    Patroni overrides several HTTPServer methods to improve SSL handling and delay the handshake until the thread starts. It previously omitted shutdown_request().

  • Fixed issue with sleep time when using Zookeeper (Alexander Kukushkin)

    There were chances that Patroni was sleeping up to twice longer between running HA code.

  • Fixed invalid os.symlink() calls when moving data directory after failed bootstrap (Andrew L’Ecuyer)

    After bootstrap failure, Patroni renames the data directory, pg_wal, and all tablespaces. It updates symlinks to keep the filesystem consistent. Symlink creation failed because the src and dst arguments were reversed.

  • Fixed bug in the post_bootstrap() method (Alexander Kukushkin)

    If the superuser password wasn’t configured Patroni was failing to call the post_init script and therefore the whole bootstrap was failing.

  • Fixed an issues with pg_rewind in the standby cluster (Alexander Kukushkin)

    If the superuser name is different from Postgres, the pg_rewind in the standby cluster was failing because the connection string didn’t contain the database name.

  • Exit only if authentication with Etcd v3 explicitly failed (Alexander Kukushkin)

    At startup, Patroni discovers the Etcd topology and authenticates if necessary. Authentication against an inaccessible server previously caused failure. Patroni now retries with the next node.

  • Handle case with psutil cmdline() returning empty list (Alexander Kukushkin)

    Zombie processes are still postmasters children, but they don’t have cmdline()

  • Treat PATRONI_KUBERNETES_USE_ENDPOINTS environment variable as boolean (Alexander Kukushkin)

    Not doing so was making impossible disabling kubernetes.use_endpoints via environment.

  • Improve handling of concurrent endpoint update errors (Alexander Kukushkin)

    Patroni will explicitly query the current endpoint object, verify that the current pod still holds the leader lock and repeat the update.


Version 2.0.1

Released 2020-10-01

New features

  • Use more as pager in patronictl edit-config if less is not available (Pavel Golub)

    On Windows it would be the more.com. In addition to that, cdiff was changed to ydiff in requirements.txt, but patronictl still supports both for compatibility.

  • Added support of raft bind_addr and password (Alexander Kukushkin)

    raft.bind_addr might be useful when running behind NAT. raft.password enables traffic encryption (requires the cryptography module).

  • Added sslpassword connection parameter support (Kostiantyn Nemchenko)

    The connection parameter was introduced in PostgreSQL 13.

Stability improvements

  • Changed the behavior in pause (Alexander Kukushkin)

    1. Patroni will not call the bootstrap method if the PGDATA directory is missing/empty.
    2. Patroni will not exit on sysid mismatch in pause, only log a warning.
    3. In pause mode, a node accepting writes will not try to acquire the leader key if its sysid differs from the initialize key.
  • Apply master_start_timeout when executing crash recovery (Alexander Kukushkin)

    If Postgres crashed on the leader node, Patroni does a crash-recovery by starting Postgres in single-user mode. During the crash-recovery the leader lock is being updated. If the crash-recovery didn’t finish in master_start_timeout seconds, Patroni will stop it forcefully and release the leader lock.

  • Removed the secure extra from the urllib3 requirements (Alexander Kukushkin)

    The only reason for adding it there was the ipaddress dependency for python 2.7.

Bugfixes

  • Fixed a bug in the Kubernetes.update_leader() (Alexander Kukushkin)

    An unhandled exception was preventing demoting the primary when the update of the leader object failed.

  • Fixed hanging patronictl when RAFT is being used (Alexander Kukushkin)

    When using patronictl with Patroni config, self_addr should be added to the partner_addrs.

  • Fixed bug in get_guc_value() (Alexander Kukushkin)

    Patroni was failing to get the value of restore_command on PostgreSQL 12, therefore fetching missing WALs for pg_rewind didn’t work.


Version 2.0.0

Released 2020-09-02

This version improves PostgreSQL 13 compatibility and pg_rewind handling. It adds multiple synchronous standbys, Etcd v3, and pure RAFT operation without Etcd, Consul, or Zookeeper. It also supports an optional pre_promote fencing script.

PostgreSQL 13 support

  • Don’t fire on_reload when promoting to standby_leader on PostgreSQL 13+ (Alexander Kukushkin)

    When promoting to standby_leader we change primary_conninfo, update the role and reload Postgres. Since on_role_change and on_reload effectively duplicate each other, Patroni will call only on_role_change.

  • Added support for gssencmode and channel_binding connection parameters (Alexander Kukushkin)

    PostgreSQL 12 introduced gssencmode and 13 channel_binding connection parameters and now they can be used if defined in the postgresql.authentication section.

  • Handle renaming of wal_keep_segments to wal_keep_size (Alexander Kukushkin)

    In case of misconfiguration (wal_keep_segments on 13 and wal_keep_size on older versions) Patroni will automatically adjust the configuration.

  • Use pg_rewind with --restore-target-wal on 13 if possible (Alexander Kukushkin)

    On PostgreSQL 13 Patroni checks if restore_command is configured and tells pg_rewind to use it.

New features

  • BETABETA

    Implemented support of Patroni on pure RAFT (Alexander Kukushkin)

    Patroni can run without dependencies such as Etcd, Consul, or Zookeeper. HA requires three Patroni nodes, or two Patroni nodes and one patroni_raft_controller node. See the documentation.

  • BETABETA

    Implemented support for Etcd v3 protocol via gPRC-gateway (Alexander Kukushkin)

    Etcd 3.0 was released more than four years before this release. Etcd 3.4 disables v2 by default, and future versions might remove v2. Patroni now supports Etcd v3. To use it, explicitly create an etcd3 section in the Patroni configuration file.

  • Supporting multiple synchronous standbys (Krishna Sarabu)

    It allows running a cluster with more than one synchronous replicas. The maximum number of synchronous replicas is controlled by the new parameter synchronous_node_count. It is set to 1 by default and has no effect when the synchronous_mode is set to off.

  • Added possibility to call the pre_promote script (Sergey Dudoladov)

    Unlike callbacks, the pre_promote script is called synchronously after acquiring the leader lock, but before promoting Postgres. If the script fails or exits with a non-zero exitcode, the current node will release the leader lock.

  • Added support for configuration directories (Floris van Nee)

    YAML files in the directory loaded and applied in alphabetical order.

  • Advanced validation of PostgreSQL parameters (Alexander Kukushkin)

    The current PostgreSQL version might not support the parameter, or its value might be incorrect. Patroni will remove the parameter or try to correct its value.

  • Wake up the main thread when the forced checkpoint after promote completed (Alexander Kukushkin)

    Replicas wait for checkpoint information in the leader’s DCS member key. Patroni normally updates this key once per HA loop. Without waking the main thread, replicas could wait up to loop_wait extra seconds.

  • Use of pg_stat_wal_receiver view on 9.6+ (Alexander Kukushkin)

    The view contains up-to-date values of primary_conninfo and primary_slot_name, while the contents of recovery.conf could be stale.

  • Improved handing of IPv6 addresses in the Patroni config file (Mateusz Kowalski)

    The IPv6 address is supposed to be enclosed into square brackets, but Patroni was expecting to get it plain. Now both formats are supported.

  • Added Consul service_tags configuration parameter (Robert Edström)

    They are useful for dynamic service discovery, for example by load balancers.

  • Implemented SSL support for Zookeeper (Kostiantyn Nemchenko)

    It requires kazoo>=2.6.0.

  • Implemented no_params option for custom bootstrap method (Kostiantyn Nemchenko)

    It allows calling wal-g, pgBackRest and other backup tools without wrapping them into shell scripts.

  • Move WAL and tablespaces after a failed init (Feike Steenbergen)

    During reinit, Patroni already removed PGDATA, the symlinked WAL directory, and tablespaces. The move_data_directory() method now also renames the WAL directory and tablespaces. It updates their symlinks in PGDATA.

Improved in pg_rewind support

  • Improved timeline divergence check (Alexander Kukushkin)

    Rewind is unnecessary if the replica replay location is not ahead of the switchpoint. It is also unnecessary if the former primary’s checkpoint record ends at the switchpoint. Patroni uses pg_waldump output to find the end of the checkpoint record.

  • Try to fetch missing WAL if pg_rewind complains about it (Alexander Kukushkin)

    A WAL segment required by pg_rewind can be absent from pg_wal. Then pg_rewind cannot find the checkpoint before timeline divergence. From PostgreSQL 13, pg_rewind can fetch missing WALs with restore_command. For older versions, Patroni parses errors from a failed rewind and calls restore_command to fetch the missing WAL.

  • Detect a new timeline in the standby cluster and trigger rewind/reinitialize if necessary (Alexander Kukushkin)

    The standby_cluster is decoupled from the primary cluster and therefore doesn’t immediately know about leader elections and timeline switches. In order to detect the fact, the standby_leader periodically checks for new history files in pg_wal.

  • Shorten and beautify history log output (Alexander Kukushkin)

    Patroni can log the primary history file while deciding whether pg_rewind is necessary. This file grows with every failover or switchover, and most lines eventually become irrelevant to the check. Patroni now shows only 3 lines before the current replica timeline and 2 lines after it.

Improvements on K8s

  • Get rid of kubernetes python module (Alexander Kukushkin)

    The official python kubernetes client contains a lot of auto-generated code and therefore very heavy. Patroni uses only a small fraction of K8s API endpoints and implementing support for them wasn’t hard.

  • Make it possible to bypass the kubernetes service (Alexander Kukushkin)

    On K8s, Patroni normally contacts the API through the kubernetes service. KUBERNETES_SERVICE_HOST supplies its address. The kubernetes service uses kube-proxy, which routes traffic through a userspace program or iptables, depending on configuration. Direct connections to K8s master nodes permit a better retry strategy. They reduce the risk of Postgres demotion during K8s master upgrades.

  • Sync HA loops of all pods of a Patroni cluster (Alexander Kukushkin)

    Not doing so was increasing failure detection time from ttl to ttl + loop_wait.

  • Populate references and nodename in the subsets addresses on K8s (Alexander Kukushkin)

    Some load-balancers are relying on this information.

  • Fix possible race conditions in the update_leader() (Alexander Kukushkin)

    The concurrent update of the leader configmap or endpoint happening outside of Patroni might cause the update_leader() call to fail. In this case Patroni rechecks that the current node is still owning the leader lock and repeats the update.

  • Explicitly disallow patching non-existent config (Alexander Kukushkin)

    Outside kubernetes, PATCH on nonexistent configuration fails because cluster.config is None. Kubernetes instead created the config annotation. This prevented Patroni from writing bootstrap configuration after bootstrap completed.

  • Fix bug in pause (Alexander Kukushkin)

    Replicas were removing primary_conninfo and restarting Postgres when the leader key was absent, but they should do nothing.

Improvements in REST API

  • Defer TLS handshake until worker thread has started (Alexander Kukushkin, Ben Harris)

    If the TLS handshake was done in the API thread and the client-side didn’t send any data, the API thread was blocked (risking DoS).

  • Check basic-auth independently from client certificate in REST API (Alexander Kukushkin)

    Previously only the client certificate was validated. Doing two checks independently is an absolutely valid use-case.

  • Write double CRLF after HTTP headers of the OPTIONS request (Sergey Burladyan)

    HAProxy was happy with a single CRLF, while Consul health-check complained about broken connection and unexpected EOF.

  • GET /cluster was showing stale members info for Zookeeper (Alexander Kukushkin)

    The endpoint used Patroni’s internal cluster view. This did not affect Patroni itself. External responses, however, need current information, especially replication lag.

  • Fixed health-checks for standby cluster (Alexander Kukushkin)

    The GET /standby-leader for a master and GET /master for a standby_leader were incorrectly responding with 200.

  • Implemented DELETE /switchover (Alexander Kukushkin)

    The REST API call deletes the scheduled switchover.

  • Created /readiness and /liveness endpoints (Alexander Kukushkin)

    They could be useful to eliminate “unhealthy” pods from subsets addresses when the K8s service is used with label selectors.

  • Enhanced GET /replica and GET /async REST API health-checks (Krishna Sarabu, Alexander Kukushkin)

    Checks support the optional ?lag=<max-lag> argument. They return 200 only when lag is below the supplied value. Leader WAL position information updates only every loop_wait seconds.

  • Added support for user defined HTTP headers in the REST API response (Yogesh Sharma)

    This feature might be useful if requests are made from a browser.

Improvements in patronictl

  • Don’t try to call non-existing leader in patronictl pause (Alexander Kukushkin)

    While pausing a cluster without a leader on K8s, patronictl was showing warnings that member “None” could not be accessed.

  • Handle the case when member conn_url is missing (Alexander Kukushkin)

    On K8s it is possible that the pod doesn’t have the necessary annotations because Patroni is not yet running. It was making patronictl to fail.

  • Added ability to print ASCII cluster topology (Maxim Fedotov, Alexander Kukushkin)

    It is very useful to get overview of the cluster with cascading replication.

  • Implement patronictl flush switchover (Alexander Kukushkin)

    Before that patronictl flush only supported cancelling scheduled restarts.

Bugfixes

  • Attribute error during bootstrap of the cluster with existing PGDATA (Krishna Sarabu)

    When trying to create/update the /history key, Patroni was accessing the ClusterConfig object which wasn’t created in DCS yet.

  • Improved exception handling in Consul (Alexander Kukushkin)

    Unhandled exception in the touch_member() method caused the whole Patroni process to crash.

  • Enforce synchronous_commit=local for the post_init script (Alexander Kukushkin)

    Patroni already enforced this setting when creating replication and rewind users, but omitted it for post_init. Bootstrap in synchronous_mode could not finish unless the script set it itself.

  • Increased maxsize in the Consul pool manager (ponvenkates)

    With the default size=1 some warnings were generated.

  • Patroni was wrongly reporting Postgres as running (Alexander Kukushkin)

    The state wasn’t updated when for example Postgres crashed due to an out-of-disk error.

  • Put * into pgpass instead of missing or empty values (Alexander Kukushkin)

    If for example the standby_cluster.port is not specified, the pgpass file was incorrectly generated.

  • Skip physical replication slot creation on the leader node with special characters (Krishna Sarabu)

    Patroni appeared to be creating a dormant slot (when slots defined) for the leader node when the name contained special chars such as ‘-’ (for e.g. “abc-us-1”).

  • Avoid removing non-existent pg_hba.conf in the custom bootstrap (Krishna Sarabu)

    Patroni was failing if pg_hba.conf happened to be located outside of the pgdata dir after custom bootstrap.


Version 1.6.5

Released 2020-08-23

New features

  • Master stop timeout (Krishna Sarabu)

    master_stop_timeout limits how many seconds Patroni can wait for Postgres to stop. It applies only with synchronous_mode enabled and a value greater than 0. Patroni sends SIGKILL to postmaster if shutdown exceeds this limit. Choose the value according to your durability and availability requirements. An unset or non-positive value has no effect.

  • Don’t create permanent physical slot with name of the primary (Alexander Kukushkin)

    The primary can recycle WAL segments while a replica is down. Static clusters with fixed node names and counts can now avoid this problem. List all node names in slots. The primary then retains each slot while its node is down and absent from DCS.

  • First draft of Config Validator (Igor Yanchenko)

    Use patroni --validate-config patroni.yaml in order to validate Patroni configuration.

  • Possibility to configure max length of timelines history (Krishna Sarabu)

    Patroni stores failover and switchover history in the DCS /history key. This key grows over time, although usually only recent entries are useful. max_timelines_history sets the maximum number of history items retained in DCS.

  • Kazoo 2.7.0 compatibility (Danyal Prout)

    Some non-public methods in Kazoo changed their signatures, but Patroni was relying on them.

Improvements in patronictl

  • Show member tags (Kostiantyn Nemchenko, Alexander Kukushkin)

    Tags are configured individually for every node and there was no easy way to get an overview of them

  • Improve members output (Alexander Kukushkin)

    The redundant cluster name won’t be shown anymore on every line, only in the table header.

$ patronictl list
+ Cluster: batman (6813309862653668387) +---------+----+-----------+---------------------+
|    Member   |      Host      |  Role  |  State  | TL | Lag in MB | Tags                |
+-------------+----------------+--------+---------+----+-----------+---------------------+
| postgresql0 | 127.0.0.1:5432 | Leader | running |  3 |           | clonefrom: true     |
|             |                |        |         |    |           | noloadbalance: true |
|             |                |        |         |    |           | nosync: true        |
+-------------+----------------+--------+---------+----+-----------+---------------------+
| postgresql1 | 127.0.0.1:5433 |        | running |  3 |       0.0 |                     |
+-------------+----------------+--------+---------+----+-----------+---------------------+
  • Fail if a config file is specified explicitly but not found (Kaarel Moppel)

    Previously patronictl was only reporting a DEBUG message.

  • Solved the problem of not initialized K8s pod breaking patronictl (Alexander Kukushkin)

    Patroni uses pod annotations on K8s. A starting or stopping pod can lack valid annotations. This previously caused patronictl to raise an exception.

Stability improvements

  • Apply 1 second backoff if LIST call to K8s API server failed (Alexander Kukushkin)

    It is mostly necessary to avoid flooding logs, but also helps to prevent starvation of the main thread.

  • Retry if the retry-after HTTP header is returned by K8s API (Alexander Kukushkin)

    If the K8s API server is overwhelmed with requests it might ask to retry.

  • Scrub KUBERNETES_ environment from the postmaster (Feike Steenbergen)

    PostgreSQL does not require KUBERNETES_ environment variables. Exposing them to postmaster also exposes them to backends and regular database users, for example through pl/perl.

  • Clean up tablespaces on reinitialize (Krishna Sarabu)

    During reinit, Patroni was removing only PGDATA and leaving user-defined tablespace directories. This is causing Patroni to loop in reinit. The previous workaround for the problem was implementing the custom bootstrap script.

  • Explicitly execute CHECKPOINT after promote happened (Alexander Kukushkin)

    It helps to reduce the time before the new primary is usable for pg_rewind.

  • Smart refresh of Etcd members (Alexander Kukushkin)

    If a request fails on every Etcd member, Patroni rechecks A or SRV records for changed IP addresses or hosts before retrying.

  • Skip missing values from pg_controldata (Feike Steenbergen)

    Values are missing when trying to use binaries of a version that doesn’t match PGDATA. Patroni will try to start Postgres anyway, and Postgres will complain that the major version doesn’t match and abort with an error.

Bugfixes

  • Disable SSL verification for Consul when required (Julien Riou)

    Starting from a certain version of urllib3, the cert_reqs must be explicitly set to ssl.CERT_NONE in order to effectively disable SSL verification.

  • Avoid opening replication connection on every cycle of HA loop (Alexander Kukushkin)

    Regression was introduced in 1.6.4.

  • Call on_role_change callback on failed primary (Alexander Kukushkin)

    In certain cases it could lead to the virtual IP remaining attached to the old primary. Regression was introduced in 1.4.5.

  • Reset rewind state if postgres started after successful pg_rewind (Alexander Kukushkin)

    As a result of this bug Patroni was starting up manually shut down postgres in the pause mode.

  • Convert recovery_min_apply_delay to ms when checking recovery.conf

    Patroni was indefinitely restarting replica if recovery_min_apply_delay was configured on PostgreSQL older than 12.

  • PyInstaller compatibility (Alexander Kukushkin)

    PyInstaller freezes (packages) Python applications into stand-alone executables. The compatibility was broken when we switched to the spawn method instead of fork for multiprocessing.


Version 1.6.4

Released 2020-01-27

New features

  • Implemented --wait option for patronictl reinit (Igor Yanchenko)

    Patronictl will wait for reinit to finish is the --wait option is used.

  • Further improvements of Windows support (Igor Yanchenko, Alexander Kukushkin)

    1. All shell scripts which are used for integration testing are rewritten in python
    2. The pg_ctl kill will be used to stop postgres on non posix systems
    3. Don’t try to use unix-domain sockets

Stability improvements

  • Make sure unix_socket_directories and stats_temp_directory exist (Igor Yanchenko)

    Upon the start of Patroni and Postgres make sure that unix_socket_directories and stats_temp_directory exist or try to create them. Patroni will exit if failed to create them.

  • Make sure postgresql.pgpass is located in the place where Patroni has write access (Igor Yanchenko)

    In case if it doesn’t have a write access Patroni will exit with exception.

  • Disable Consul serfHealth check by default (Kostiantyn Nemchenko)

    Even minor network problems can make serfHealth fail and invalidate every session associated with the node. The leader key then disappears much earlier than ttl. This causes unnecessary replica restarts and possibly primary demotion.

  • Configure tcp keepalives for connections to K8s API (Alexander Kukushkin)

    In case if we get nothing from the socket after TTL seconds it can be considered dead.

  • Avoid logging of passwords on user creation (Alexander Kukushkin)

    PostgreSQL can log a rejected password, or log it when logging is verbose or unconfigured. Before creating or updating users, Patroni sets safe values for log_statement, log_min_duration_statement, and log_min_error_statement.

Bugfixes

  • Use restore_command from the standby_cluster config on cascading replicas (Alexander Kukushkin)

    The standby_leader was already doing it from the beginning the feature existed. Not doing the same on replicas might prevent them from catching up with standby leader.

  • Update timeline reported by the standby cluster (Alexander Kukushkin)

    In case of timeline switch the standby cluster was correctly replicating from the primary but patronictl was reporting the old timeline.

  • Allow certain recovery parameters be defined in the custom_conf (Alexander Kukushkin)

    During replica recovery validation, Patroni can skip archive_cleanup_command, promote_trigger_file, recovery_end_command, recovery_min_apply_delay, and restore_command. This applies when they are absent from Patroni configuration and defined in files other than postgresql.auto.conf or postgresql.conf.

  • Improve handling of postgresql parameters with period in its name (Alexander Kukushkin)

    Such parameters could be defined by extensions where the unit is not necessarily a string. Changing the value might require a restart (for example pg_stat_statements.max).

  • Improve exception handling during shutdown (Alexander Kukushkin)

    During shutdown Patroni is trying to update its status in the DCS. If the DCS is inaccessible an exception might be raised. Lack of exception handling was preventing logger thread from stopping.


Version 1.6.3

Released 2019-12-05

Bugfixes

  • Don’t expose password when running pg_rewind (Alexander Kukushkin)

    Bug was introduced in the #1301

  • Apply connection parameters specified in the postgresql.authentication to pg_basebackup and custom replica creation methods (Alexander Kukushkin)

    They were relying on url-like connection string and therefore parameters never applied.


Version 1.6.2

Released 2019-12-05

New features

  • Implemented patroni --version (Igor Yanchenko)

    It prints the current version of Patroni and exits.

  • Set the user-agent http header for all http requests (Alexander Kukushkin)

    Patroni is communicating with Consul, Etcd, and Kubernetes API via the http protocol. Having a specifically crafted user-agent (example: Patroni/1.6.2 Python/3.6.8 Linux) might be useful for debugging and monitoring.

  • Make it possible to configure log level for exception tracebacks (Igor Yanchenko)

    If you set log.traceback_level=DEBUG the tracebacks will be visible only when log.level=DEBUG. The default behavior remains the same.

Stability improvements

  • Avoid importing all DCS modules when searching for the module required by the config file (Alexander Kukushkin)

    Patroni now imports only the DCS modules required by its configuration, for example Zookeeper without Etcd, Consul, or Kubernetes. This reduces memory use and removes unnecessary INFO messages such as Failed to import smth.

  • Removed python requests module from explicit requirements (Alexander Kukushkin)

    It wasn’t used for anything critical, but causing a lot of problems when the new version of urllib3 is released.

  • Improve handling of etcd.hosts written as a comma-separated string instead of YAML array (Igor Yanchenko)

    Previously it was failing when written in format host1:port1, host2:port2 (the space character after the comma).

Usability improvements

  • Don’t force users to choose members from an empty list in patronictl (Igor Yanchenko)

    If the user provides a wrong cluster name, we will raise an exception rather than ask to choose a member from an empty list.

  • Make the error message more helpful if the REST API cannot bind (Igor Yanchenko)

    For an inexperienced user it might be hard to figure out what is wrong from the Python stacktrace.

Bugfixes

  • Fix calculation of wal_buffers (Alexander Kukushkin)

    The base unit has been changed from 8 kB blocks to bytes in PostgreSQL 11.

  • Use passfile in primary_conninfo only on PostgreSQL 10+ (Alexander Kukushkin)

    On older versions there is no guarantee that passfile will work, unless the latest version of libpq is installed.


Version 1.6.1

Released 2019-11-15

New features

  • Added PATRONICTL_CONFIG_FILE environment variable (msvechla)

    It allows configuring the --config-file argument for patronictl from the environment.

  • Implement patronictl history (Alexander Kukushkin)

    It shows the history of failovers/switchovers.

  • Pass -c statement_timeout=0 in PGOPTIONS when doing pg_rewind (Alexander Kukushkin)

    It protects from the case when statement_timeout on the server is set to some small value and one of the statements executed by pg_rewind is canceled.

  • Allow lower values for PostgreSQL configuration (Soulou)

    Patroni didn’t allow some of the PostgreSQL configuration parameters be set smaller than some hardcoded values. Now the minimal allowed values are smaller, default values have not been changed.

  • Allow for certificate-based authentication (Jonathan S. Katz)

    This feature enables certificate-based authentication for superuser, replication, rewind accounts and allows the user to specify the sslmode they wish to connect with.

  • Use the passfile in the primary_conninfo instead of password (Alexander Kukushkin)

    It allows to avoid setting 600 permissions on postgresql.conf

  • Perform pg_ctl reload regardless of config changes (Alexander Kukushkin)

    Some configuration files are outside Patroni control. A REST API reload or SIGHUP to Patroni is expected to reload Postgres too. Previously, Postgres did not reload unless Patroni’s postgresql section changed.

  • Compare all recovery parameters, not only primary_conninfo (Alexander Kukushkin)

    Previously the check_recovery_conf() method was only checking whether primary_conninfo has changed, never taking into account all other recovery parameters.

  • Make it possible to apply some recovery parameters without restart (Alexander Kukushkin)

    Starting from PostgreSQL 12 the following recovery parameters could be changed without restart: archive_cleanup_command, promote_trigger_file, recovery_end_command, and recovery_min_apply_delay. In future Postgres releases this list will be extended and Patroni will support it automatically.

  • Make it possible to change use_slots online (Alexander Kukushkin)

    Previously it required restarting Patroni and removing slots manually.

  • Remove only PATRONI_ prefixed environment variables when starting up Postgres (Cody Coons)

    It will solve a lot of problems with running different Foreign Data Wrappers.

Stability improvements

  • Use LIST + WATCH when working with K8s API (Alexander Kukushkin)

    It allows to efficiently receive object changes (pods, endpoints/configmaps) and makes less stress on K8s master nodes.

  • Improve the workflow when PGDATA is not empty during bootstrap (Alexander Kukushkin)

    Like initdb, Patroni now treats PGDATA as empty if it contains only lost+found and .dotfiles. If PGDATA is nonempty but pg_controldata reports it invalid, Patroni reports an error and exits.

  • Avoid calling expensive os.listdir() on every HA loop (Alexander Kukushkin)

    Under IO load, os.listdir() can take seconds or minutes and delay the Patroni HA loop. Missing updates could even make the leader key expire. Patroni now checks for global/pg_control in PGDATA, which is a less expensive check.

  • Some improvements in logging infrastructure (Alexander Kukushkin)

    Previously there was a possibility to loose the last few log lines on shutdown because the logging thread was a daemon thread.

  • Use spawn multiprocessing start method on python 3.4+ (Maciej Kowalczyk)

    Python has a known issue when threads and multiprocessing interact. The recommended workaround replaces fork with spawn. Otherwise, the Postmaster startup process could hang. Patroni would then report INFO: restarting after failure in progress indefinitely, although Postgres was running.

Improvements in REST API

  • Make it possible to check client certificates in the REST API (Alexander Kukushkin)

    If the verify_client is set to required, Patroni will check client certificates for all REST API calls. When it is set to optional, client certificates are checked for all unsafe REST API endpoints.

  • Return the response code 503 for the GET /replica health check request if Postgres is not running (Alexander Anikin)

    Postgres might spend significant time in recovery before it starts accepting client connections.

  • Implement /history and /cluster endpoints (Alexander Kukushkin)

    The /history endpoint shows the content of the history key in DCS. The /cluster endpoint shows all cluster members and some service info like pending and scheduled restarts or switchovers.

Improvements in Etcd support

  • Retry on Etcd RAFT internal error (Alexander Kukushkin)

    When the Etcd node is being shut down, it sends response code=300, data='etcdserver: server stopped', which was causing Patroni to demote the primary.

  • Don’t give up on Etcd request retry too early (Alexander Kukushkin)

    When there were some network problems, Patroni was quickly exhausting the list of Etcd nodes and giving up without using the whole retry_timeout, potentially resulting in demoting the primary.

Bugfixes

  • Disable synchronous_commit when granting execute permissions to the pg_rewind user (kremius)

    If the bootstrap is done with synchronous_mode_strict: true the GRANT EXECUTE statement was waiting indefinitely due to the non-synchronous nodes being available.

  • Fix memory leak on python 3.7 (Alexander Kukushkin)

    Patroni is using ThreadingMixIn to process REST API requests and python 3.7 made threads spawn for every request non-daemon by default.

  • Fix race conditions in asynchronous actions (Alexander Kukushkin)

    There was a chance that patronictl reinit --force could be overwritten by the attempt to recover stopped Postgres. This ended up in a situation when Patroni was trying to start Postgres while basebackup was running.

  • Fix race condition in postmaster_start_time() method (Alexander Kukushkin)

    If the method is executed from the REST API thread, it requires a separate cursor object to be created.

  • Fix the problem of not promoting the sync standby that had a name containing upper case letters (Alexander Kukushkin)

    We converted the name to the lower case because Postgres was doing the same while comparing the application_name with the value in synchronous_standby_names.

  • Kill all children along with the callback process before starting the new one (Alexander Kukushkin)

    Not doing so makes it hard to implement callbacks in bash and eventually can lead to the situation when two callbacks are running at the same time.

  • Fix ‘start failed’ issue (Alexander Kukushkin)

    Under certain conditions the Postgres state might be set to ‘start failed’ despite Postgres being up and running.


Version 1.6.0

Released 2019-08-05

This version adds compatibility with PostgreSQL 12, makes is possible to run pg_rewind without superuser on PostgreSQL 11 and newer, and enables IPv6 support.

New features

  • Psycopg2 was removed from requirements and must be installed independently (Alexander Kukushkin)

    From 2.8.0, psycopg2 has two packages: psycopg2 and psycopg2-binary. Both can install to the same filesystem location. To reduce dependency conflicts, users must choose how to install it. See the available installation options.

  • Compatibility with PostgreSQL 12 (Alexander Kukushkin)

    PostgreSQL 12 removes recovery.conf and converts its parameters to GUC settings. Patroni removes all standby and recovery parameters from postgresql.auto.conf to prevent overrides such as ALTER SYSTEM SET primary_conninfo. Patroni configuration remains backward compatible. For example, restore_command can still be set under postgresql.recovery_conf.restore_command. Patroni writes it to postgresql.conf for PostgreSQL 12.

  • Make it possible to use pg_rewind without superuser on PostgreSQL 11 and newer (Alexander Kukushkin)

    Set username and password in postgresql.authentication.rewind in the Patroni configuration. For an existing cluster, manually create the user and GRANT EXECUTE permission on the required functions. See the PostgreSQL documentation.

  • Do a smart comparison of actual and desired primary_conninfo values on replicas (Alexander Kukushkin)

    It might help to avoid replica restart when you are converting an already existing primary-standby cluster to one managed by Patroni

  • IPv6 support (Alexander Kukushkin)

    There were two major issues. Patroni REST API service was listening only on 0.0.0.0 and IPv6 IP addresses used in the api_url and conn_url were not properly quoted.

  • Kerberos support (Ajith Vilas, Alexander Kukushkin)

    It makes possible using Kerberos authentication between Postgres nodes instead of defining passwords in Patroni configuration file

  • Manage pg_ident.conf (Alexander Kukushkin)

    If configuration or DCS defines postgresql.pg_ident, Patroni writes its value to pg_ident.conf, as it does for pg_hba.conf. If postgresql.parameters.ident_file is set, Patroni assumes external management of pg_ident and does not update the file.

Improvements in REST API

  • Added /health endpoint (Wilfried Roset)

    It will return an HTTP status code only if PostgreSQL is running

  • Added /read-only and /read-write endpoints (Julien Riou)

    The /read-only endpoint enables reads balanced across replicas and the primary. The /read-write endpoint is an alias for /primary, /leader and /master.

  • Use SSLContext to wrap the REST API socket (Julien Riou)

    Usage of ssl.wrap_socket() is deprecated and was still allowing soon-to-be-deprecated protocols like TLS 1.1.

Logging improvements

  • Two-step logging (Alexander Kukushkin)

    Patroni first writes log messages to an in-memory queue. A separate thread asynchronously writes them to stderr or a file. The maximum queue size is configurable. At the limit, Patroni discards logs to avoid blocking the HA loop.

  • Enable debug logging for GET/OPTIONS API calls together with latency (Jan Tomsa)

    It will help with debugging of health-checks performed by HAProxy, Consul or other tooling that decides which node is the primary/replica.

  • Log exceptions caught in Retry (Daniel Kucera)

    Log the final exception when either the number of attempts or the timeout were reached. It will hopefully help to debug some issues when communication to DCS fails.

Improvements in patronictl

  • Enhance dialogues for scheduled switchover and restart (Rafia Sabih)

    Previously dialogues did not take into account scheduled actions and therefore were misleading.

  • Check if config file exists (Wilfried Roset)

    Be verbose about configuration file when the given filename does not exists, instead of ignoring silently (which can lead to misunderstanding).

  • Add fallback value for EDITOR (Wilfried Roset)

    When the EDITOR environment variable was not defined, patronictl edit-config was failing with PatroniCtlException. The new strategy is to try editor and than vi, which should be available on most systems.

Improvements in Consul support

  • Allow to specify Consul consistency mode (Jan Tomsa)

    You can read more about consistency mode here.

  • Reload Consul config on SIGHUP (Cameron Daniel Kucera, Alexander Kukushkin)

    It is especially useful when somebody is changing the value of token.

Bugfixes

  • Fix corner case in switchover/failover (Sharoon Thomas)

    The variable scheduled_at may be undefined if REST API is not accessible and we are using DCS as a fallback.

  • Open trust to localhost in pg_hba.conf during custom bootstrap (Alexander Kukushkin)

    Previously it was open only to unix_socket, which was causing a lot of errors: FATAL: no pg_hba.conf entry for replication connection from host "127.0.0.1", user "replicator"

  • Consider synchronous node as healthy even when the former leader is ahead (Alexander Kukushkin)

    When the primary loses DCS access, it restarts Postgres in read-only mode. Other nodes might still reach the old primary through REST API. If its reported WAL position was ahead, the synchronous standby previously refused to promote.

  • Standby cluster bugfixes (Alexander Kukushkin)

    Make it possible to bootstrap a replica in a standby cluster when the standby_leader is not accessible and a few other minor fixes.


Version 1.5.6

Released 2019-08-03

New features

  • Support work with etcd cluster via set of proxies (Alexander Kukushkin)

    It might happen that etcd cluster is not accessible directly but via set of proxies. In this case Patroni will not perform etcd topology discovery but just round-robin via proxy hosts. Behavior is controlled by etcd.use_proxies.

  • Changed callbacks behavior when role on the node is changed (Alexander Kukushkin)

    Patroni now calls on_role_change instead of on_restart when master or standby_leader changes to replica. This also applies when replica changes to standby_leader.

  • Change the way how we start postgres (Alexander Kukushkin)

    Use multiprocessing.Process instead of executing itself and multiprocessing.Pipe to transmit the postmaster pid to the Patroni process. Before that we were using pipes, what was leaving postmaster process with stdin closed.

Bug fixes

  • Fix role returned by REST API for the standby leader (Alexander Kukushkin)

    It was incorrectly returning replica instead of standby_leader

  • Wait for callback end if it could not be killed (Julien Tachoires)

    Patroni doesn’t have enough privileges to terminate the callback script running under sudo what was cancelling the new callback. If the running script could not be killed, Patroni will wait until it finishes and then run the next callback.

  • Reduce lock time taken by dcs.get_cluster method (Alexander Kukushkin)

    Due to the lock being held DCS slowness was affecting the REST API health checks causing false positives.

  • Improve cleaning of PGDATA when pg_wal/`pg_xlog` is a symlink (Julien Tachoires)

    In this case Patroni will explicitly remove files from the target directory.

  • Remove unnecessary usage of os.path.relpath (Ants Aasma)

    It depends on being able to resolve the working directory, what will fail if Patroni is started in a directory that is later unlinked from the filesystem.

  • Do not enforce ssl version when communicating with Etcd (Alexander Kukushkin)

    For an unknown reason, Debian and Ubuntu did not use the latest python3-etcd package. Their package enforced TLSv1, which Etcd v3 did not support. This release solved the problem in Patroni.


Version 1.5.5

Released 2019-02-15

This version introduces the possibility of automatic reinit of the former master, improves patronictl list output and fixes a number of bugs.

New features

  • Add support of PATRONI_ETCD_PROTOCOL, PATRONI_ETCD_USERNAME and PATRONI_ETCD_PASSWORD environment variables (Étienne M)

    Before it was possible to configure them only in the config file or as a part of PATRONI_ETCD_URL, which is not always convenient.

  • Make it possible to automatically reinit the former master (Alexander Kukushkin)

    If pg_rewind is disabled or unavailable, diverged timelines can prevent the former master from starting as a replica. Recovery requires removal of the data directory and reinitialization. Set postgresql.remove_data_directory_on_diverged_timelines to make Patroni do this automatically.

  • Show information about timelines in patronictl list (Alexander Kukushkin)

    It helps to detect stale replicas. In addition to that, Host will include ‘:{port}’ if the port value isn’t default or there is more than one member running on the same host.

  • Create a headless service associated with the $SCOPE-config endpoint (Alexander Kukushkin)

    The “config” endpoint stores cluster-wide Patroni and Postgres configuration, history, and the initialize key. A Kubernetes master restart or upgrade removes endpoints without services. The headless service prevents removal of this endpoint.

Bug fixes

  • Adjust the read timeout for the leader watch blocking query (Alexander Kukushkin)

    Consul adds a small random delay to a blocking query timeout to spread concurrent request wakeups. This can add up to wait / 16 to the maximum duration. Patroni adds the greater of wait / 15 and 1 second to its read timeout.

  • Always use replication=1 when connecting via replication protocol to the postgres (Alexander Kukushkin)

    Starting from Postgres 10 the line in the pg_hba.conf with database=replication doesn’t accept connections with the parameter replication=database.

  • Don’t write primary_conninfo into recovery.conf for wal-only standby cluster (Alexander Kukushkin)

    Despite not having neither host nor port defined in the standby_cluster config, Patroni was putting the primary_conninfo into the recovery.conf, which is useless and generating a lot of errors.


Version 1.5.4

Released 2019-01-15

This version implements flexible logging and fixes a number of bugs.

New features

  • Improvements in logging infrastructure (Alexander Kukushkin, Lucas Capistrant, Alexander Anikin)

    Logging can now be configured in the Patroni configuration file as well as through environment variables. To apply changes at runtime, update configuration and reload, or send SIGHUP to Patroni. The default destination remains stderr. Patroni can now write to a file and rotate it at a configured size. Custom date formats and per-module Python log levels are also supported.

  • Make it possible to take into account the current timeline during leader elections (Alexander Kukushkin)

    A node can consider itself healthiest while it is not on the latest known timeline. To prevent promotion of such nodes, set check_timeline to true. The default behavior is unchanged.

  • Relaxed requirements on superuser credentials

    Libpq allows opening connections without explicitly specifying neither username nor password. Depending on situation it relies either on pgpass file or trust authentication method in pg_hba.conf. Since pg_rewind is also using libpq, it will work the same way.

  • Implemented possibility to configure Consul Service registration and check interval via environment variables (Alexander Kukushkin)

    Registration of service in Consul was added in the 1.5.0, but so far it was only possible to turn it on via patroni.yaml.

Stability Improvements

  • Set archive_mode to off during the custom bootstrap (Alexander Kukushkin)

    We want to avoid archiving wals and history files until the cluster is fully functional. It really helps if the custom bootstrap involves pg_upgrade.

  • Apply five seconds backoff when loading global config on start (Alexander Kukushkin)

    It helps to avoid hammering DCS when Patroni just starting up.

  • Reduce amount of error messages generated on shutdown (Alexander Kukushkin)

    They were harmless but rather annoying and sometimes scary.

  • Explicitly secure rw perms for recovery.conf at creation time (Lucas Capistrant)

    We don’t want anybody except patroni/postgres user reading this file, because it contains replication user and password.

  • Redirect HTTPServer exceptions to logger (Julien Riou)

    By default, such exceptions were logged on standard output messing with regular logs.

Bug fixes

  • Removed stderr pipe to stdout on pg_ctl process (Cody Coons)

    Inheriting stderr from Patroni makes all Postgres and Patroni logs visible together. Container tools such as docker logs and kubectl can consume these logs. This also fixes postmaster PID detection when Postgres writes warnings to stderr.

  • Set Consul service check deregister timeout in Go time format (Pavel Kirillov)

    Without explicitly mentioned time unit registration was failing.

  • Relax checks of standby_cluster cluster configuration (Dmitry Dolgov, Alexander Kukushkin)

    It was accepting only strings as valid values and therefore it was not possible to specify the port as integer and create_replica_methods as a list.


Version 1.5.3

Released 2018-12-03

Compatibility and bugfix release.

  • Improve stability when running with python3 against zookeeper (Alexander Kukushkin)

    Change of loop_wait was causing Patroni to disconnect from zookeeper and never reconnect back.

  • Fix broken compatibility with postgres 9.3 (Alexander Kukushkin)

    When opening a replication connection we should specify replication=1, because 9.3 does not understand replication=‘database’

  • Make sure we refresh Consul session at least once per HA loop and improve handling of consul sessions exceptions (Alexander Kukushkin)

    Restart of local consul agent invalidates all sessions related to the node. Not calling session refresh on time and not doing proper handling of session errors was causing demote of the primary.


Version 1.5.2

Released 2018-11-26

Compatibility and bugfix release.

  • Compatibility with kazoo-2.6.0 (Alexander Kukushkin)

    In order to make sure that requests are performed with an appropriate timeout, Patroni redefines create_connection method from python-kazoo module. The last release of kazoo slightly changed the way how create_connection method is called.

  • Fix Patroni crash when Consul cluster loses the leader (Alexander Kukushkin)

    The crash was happening due to incorrect implementation of touch_member method, it should return boolean and not raise any exceptions.


Version 1.5.1

Released 2018-11-01

This version implements support of permanent replication slots, adds support of pgBackRest and fixes number of bugs.

New features

  • Permanent replication slots (Alexander Kukushkin)

    Permanent replication slots survive failover and switchover. After promotion, Patroni creates the configured slots on the new primary. Configure them with patronictl edit-config, or set initial configuration in bootstrap.dcs.

  • Add pgbackrest support (Yogesh Sharma)

    pgBackrest can restore into an existing $PGDATA folder. It skips files unchanged since the last backup, which speeds up restore. The new keep_data parameter supports this feature. See replica creation method for examples.

Bug fixes


Version 1.5.0

Released 2018-09-20

This version enables standby mode for a Patroni HA cluster. It introduces experimental Windows support. It also adds a configuration parameter to register the PostgreSQL service in Consul.

New features

  • Standby cluster (Dmitry Dolgov)

    One or more Patroni nodes can form a standby cluster alongside the primary cluster, for example in another datacenter. All its PostgreSQL nodes are replicas. One replica elects itself to replicate directly from the remote master. The others replicate from that node through cascading replication. See the description and examples.

  • Register Services in Consul (Pavel Kirillov, Alexander Kukushkin)

    If register_service parameter in the consul configuration is enabled, the node will register a service with the name scope and the tag master, replica or standby-leader.

  • Experimental Windows support (Pavel Golub)

    Patroni can now run on Windows. This support is new and has received less real-world testing than Linux support. Feedback is welcome.

Improvements in patronictl

  • Add patronictl -k/–insecure flag and support for restapi cert (Wilfried Roset)

    Previously, patronictl could not verify self-signed REST API certificates, and verification could not be disabled. You can now configure patronictl to skip certificate verification. Alternatively, supply CA and client certificates in the ctl: configuration section.

  • Exclude members with nofailover tag from patronictl switchover/failover output (Alexander Anikin)

    Previously, those members were incorrectly proposed as candidates when performing interactive switchover or failover via patronictl.

Stability improvements

  • Avoid parsing non-key-value output lines of pg_controldata (Alexander Anikin)

    pg_controldata sometimes outputs lines without a colon. Patroni failed to parse these lines, which hid the original problem. Such lines often occur in warnings before the regular output, for example when the binary and data directory major versions differ.

  • Add member name to the error message during the leader election (Jan Mussler)

    During the leader election, Patroni connects to all known members of the cluster and requests their status. Such status is written to the Patroni log and includes the name of the member. Previously, if the member was not accessible, the error message did not indicate its name, containing only the URL.

  • Immediately reserve the WAL position upon creation of the replication slot (Alexander Kukushkin)

    From 9.6, pg_create_physical_replication_slot accepts the boolean immediately_reserve parameter. Its default is false. With this value, the slot reserves WAL only after the first client connection. Required segments could disappear between slot creation and that connection.

  • Fix bug in strict synchronous replication (Alexander Kukushkin)

    With synchronous_mode_strict: true, Patroni sometimes puts \* in synchronous_standby_names. This changes most replication connections to potential. Patroni previously considered only async connections and could not select a synchronous candidate.


Version 1.4.6

Released 2018-08-14

Bug fixes and stability improvements

This release fixes the Patroni API /master endpoint returning 200 for a non-master node. This reporting error did not cause split-brain. However, it could direct clients to a read-only node.

  • Reset is_leader status on demote (Alexander Kukushkin, Oleksii Kliukin)

    Make sure demoted cluster member stops responding with code 200 on the /master API call.

  • Add new “cluster_unlocked” field to the API output (Dmitry Dolgov)

    This field indicates whether the cluster has the master running. It can be used when it is not possible to query any other node but one of the replicas.


Version 1.4.5

Released 2018-08-03

New features

  • Improve logging when applying new postgres configuration (Don Seiler)

    Patroni logs changed parameter names and values.

  • Python 3.7 compatibility (Christoph Berg)

    async is a reserved keyword in python3.7

  • Set state to “stopped” in the DCS when a member is shut down (Tony Sorrentino)

    This shows the member state as “stopped” in “patronictl list” command.

  • Improve the message logged when stale postmaster.pid matches a running process (Ants Aasma)

    The previous one was beyond confusing.

  • Implement patronictl reload functionality (Don Seiler)

    Before that it was only possible to reload configuration by either calling REST API or by sending SIGHUP signal to the Patroni process.

  • Take and apply some parameters from controldata when starting as a replica (Alexander Kukushkin)

    Global max_connections and other parameter values can be lower than the values used by the primary. Previously, this prevented replica startup and required manual correction. Patroni now reads and applies values from pg_controldata, starts Postgres, and sets pending_restart.

  • If set, use LD_LIBRARY_PATH when starting postgres (Chris Fraser)

    When starting up Postgres, Patroni was passing along PATH, LC_ALL and LANG env vars if they are set. Now it is doing the same with LD_LIBRARY_PATH. It should help if somebody installed PostgreSQL to non-standard place.

  • Rename create_replica_method to create_replica_methods (Dmitry Dolgov)

    To make it clear that it’s actually an array. The old name is still supported for backward compatibility.

Bug fixes and stability improvements

  • Fix condition for the replica start due to pg_rewind in paused state (Oleksii Kliukin)

    Avoid starting the replica that had already executed pg_rewind before.

  • Respond 200 to the master health-check only if update_lock has been successful (Alexander Kukushkin)

    Prevent Patroni from reporting itself a master on the former (demoted) master if DCS is partitioned.

  • Fix compatibility with the new consul module (Alexander Kukushkin)

    Starting from v1.1.0 python-consul changed internal API and started using list instead of dict to pass query parameters.

  • Catch exceptions from Patroni REST API thread during shutdown (Alexander Kukushkin)

    Those uncaught exceptions kept PostgreSQL running at shutdown.

  • Do crash recovery only when Postgres runs as the master (Alexander Kukushkin)

    Require pg_controldata to report ‘in production’ or ‘shutting down’ or ‘in crash recovery’. In all other cases no crash recovery is necessary.

  • Improve handling of configuration errors (Henning Jacobs, Alexander Kukushkin)

    Many parameters, including restapi.listen, can change at runtime through configuration updates and SIGHUP. Invalid values previously caused unclear exceptions in the restapi thread. This fix improves those errors.


Version 1.4.4

Released 2018-05-22

Stability improvements

  • Fix race condition in poll_failover_result (Alexander Kukushkin)

    This did not directly affect failover or switchover. Rarely, poll_failover_result reported success as soon as the former leader released its lock. It then showed ‘Failed over to “None”’ instead of ‘Failed over to “desired-node”’.

  • Treat Postgres parameter names as case insensitive (Alexander Kukushkin)

    Most Postgres parameter names use snake_case. The exceptions are DateStyle, IntervalStyle, and TimeZone. Postgres accepts other letter cases, for example timezone = ‘some/tzn’. Patroni previously failed to find these names case-insensitively in pg_settings and ignored them.

  • Abort start if attaching to running postgres and cluster not initialized (Alexander Kukushkin)

    Patroni can attach itself to an already running Postgres instance. It is imperative to start running Patroni on the master node before getting to the replicas.

  • Fix behavior of patronictl scaffold (Alexander Kukushkin)

    Pass a dict object to touch_member instead of a JSON-encoded string; the DCS implementation will take care of encoding it.

  • Don’t demote master if failed to update leader key in pause (Alexander Kukushkin)

    During maintenance a DCS may start failing write requests while continuing to responds to read ones. In that case, Patroni used to put the Postgres master node to a read-only mode after failing to update the leader lock in DCS.

  • Sync replication slots when Patroni notices a new postmaster process (Alexander Kukushkin)

    If Postgres has been restarted, Patroni has to make sure that list of replication slots matches its expectations.

  • Verify sysid and sync replication slots after coming out of pause (Alexander Kukushkin)

    The data directory can be completely replaced during maintenance mode. Afterward, Patroni must verify that Database system identifier still belongs to the cluster. It must also synchronize replication slots with its expected configuration.

  • Fix a possible failure to start not running Postgres on a data directory with postmaster lock file present (Alexander Kukushkin)

    Detect reuse of PID from the postmaster lock file. More likely to hit such problem if you run Patroni and Postgres in the docker container.

  • Improve protection of DCS being accidentally wiped (Alexander Kukushkin)

    Patroni can prevent failover after accidental DCS deletion and restore its keys. Previously, deleting /config disabled pause mode for 1 HA loop cycle.

  • Do not exit when encountering invalid system ID (Oleksii Kliukin)

    Do not exit when the cluster system ID is empty or the one that doesn’t pass the validation check. In that case, the cluster most likely needs a reinit; mention it in the result message. Avoid terminating Patroni, as otherwise reinit cannot happen.

Compatibility with Kubernetes 1.10+

  • Added check for empty subsets (Cody Coons)

    Kubernetes 1.10.0+ started returning Endpoints.subsets set to None instead of \[\].

Bootstrap improvements

  • Make deleting recovery.conf optional (Brad Nicholson)

    If bootstrap.<custom_bootstrap_method_name>.keep_existing_recovery_conf is defined and set to True, Patroni will not remove the existing recovery.conf file. This is useful when bootstrapping from a backup with tools like pgBackRest that generate the appropriate recovery.conf for you.

  • Allow options to the basebackup built-in method (Oleksii Kliukin)

    Configure built-in basebackup options in the basebackup section, as with custom replica creation methods. pg_basebackup accepts both --key=value and --key. Therefore, the section accepts a dictionary of key-value pairs or a list of one-element dictionaries and keys without values. See replica creation method for examples.


Version 1.4.3

Released 2018-03-05

Improvements in logging

  • Make log level configurable from environment variables (Andy Newton, Keyvan Hedayati)

    PATRONI_LOGLEVEL sets the general log level. PATRONI_REQUESTS_LOGLEVEL sets the level for all HTTP requests, including Kubernetes API calls. See the docs for Python logging <https://docs.python.org/3.6/library/logging.html#levels> for available levels.

Stability improvements and bug fixes

  • Don’t rediscover etcd cluster topology when watch timed out (Alexander Kukushkin)

    If configuration listed only one inaccessible etcd host, Patroni repeatedly tried and failed to discover cluster topology. It should instead switch to the next available node.

  • Write content of bootstrap.pg_hba into a pg_hba.conf after custom bootstrap (Alexander Kukushkin)

    Now it behaves similarly to the usual bootstrap with initdb

  • Single user mode was waiting for user input and never finish (Alexander Kukushkin)

    Regression was introduced in https://github.com/patroni/patroni/pull/576


Version 1.4.2

Released 2018-01-30

Improvements in patronictl

  • Rename scheduled failover to scheduled switchover (Alexander Kukushkin)

    Failover and switchover functions were separated in version 1.4, but patronictl list was still reporting Scheduled failover instead of Scheduled switchover.

  • Show information about pending restarts (Alexander Kukushkin)

    Some configuration changes require a Postgres restart. Patroni already indicated this in REST API responses and node status in DCS. Previously, there was no easy way to display it.

  • Make show-config to work with cluster_name from config file (Alexander Kukushkin)

    It works similar to the patronictl edit-config

Stability improvements

  • Avoid calling pg_controldata during bootstrap (Alexander Kukushkin)

    During initdb or custom bootstrap there is a time window when pgdata is not empty but pg_controldata has not been written yet. In such case pg_controldata call was failing with error messages.

  • Handle exceptions raised from psutil (Alexander Kukushkin)

    cmdline is read and parsed every time when cmdline() method is called. It could happen that the process being examined has already disappeared, in that case NoSuchProcess is raised.

Kubernetes support improvements

  • Don’t swallow errors from k8s API (Alexander Kukushkin)

    A call to Kubernetes API could fail for a different number of reasons. In some cases such call should be retried, in some other cases we should log the error message and the exception stack trace. The change here will help debug Kubernetes permission issues.

  • Update Kubernetes example Dockerfile to install Patroni from the master branch (Maciej Szulik)

    Before that it was using feature/k8s, which became outdated.

  • Add proper RBAC to run patroni on k8s (Maciej Szulik)

    Add a Service account for the cluster pods. Add a Role with only the required permissions and a rolebinding that connects the Service account to the Role.


Version 1.4.1

Released 2018-01-17

Fixes in patronictl

  • Don’t show current leader in suggested list of members to failover to. (Alexander Kukushkin)

    patronictl failover could still work when there is leader in the cluster and it should be excluded from the list of member where it is possible to failover to.

  • Make patronictl switchover compatible with the old Patroni api (Alexander Kukushkin)

    In case if POST /switchover REST API call has failed with status code 501 it will do it once again, but to /failover endpoint.


Version 1.4

Released 2018-01-10

This version adds support for using Kubernetes as a DCS, allowing to run Patroni as a cloud-native agent in Kubernetes without any additional deployments of Etcd, Zookeeper or Consul.

Upgrade notice

Installing Patroni with pip no longer installs optional dependencies automatically. These include Etcd, Zookeper, Consul, Kubernetes, and AWS libraries. List the required dependencies explicitly, for example pip install patroni\[etcd,kubernetes\].

Kubernetes support

Implement Kubernetes-based DCS. The endpoints meta-data is used in order to store the configuration and the leader key. The meta-data field inside the pods definition is used to store the member-related data. In addition to using Endpoints, Patroni supports ConfigMaps. You can find more information about this feature in the Kubernetes chapter of the documentation

Stability improvements

  • Factor out postmaster process into a separate object (Ants Aasma)

    This object identifies postmaster by PID and start time. It simplifies detection and handling of external Postgres restarts or removal of its directory.

  • Minimize the amount of SELECT’s issued by Patroni on every loop of HA cycle (Alexander Kukushkin)

    On every iteration of HA loop Patroni needs to know recovery status and absolute wal position. From now on Patroni will run only single SELECT to get this information instead of two on the replica and three on the master.

  • Remove leader key on shutdown only when we have the lock (Ants Aasma)

    Unconditional removal was generating unnecessary and misleading exceptions.

Improvements in patronictl

  • Add version command to patronictl (Ants Aasma)

    It will show the version of installed Patroni and versions of running Patroni instances (if the cluster name is specified).

  • Make optional specifying cluster_name argument for some of patronictl commands (Alexander Kukushkin, Ants Aasma)

    It will work if patronictl is using usual Patroni configuration file with the scope defined.

  • Show information about scheduled switchover and maintenance mode (Alexander Kukushkin)

    Before that it was possible to get this information only from Patroni logs or directly from DCS.

  • Improve patronictl reinit (Alexander Kukushkin)

    Sometimes patronictl reinit refused to run while Patroni was busy, for example while starting Postgres. patronictl could not cancel these long-running actions. The only workaround was dangerous manual removal of the data directory. reinit now forcefully cancels such actions before it proceeds.

  • Implement --wait flag in patronictl pause and patronictl resume (Alexander Kukushkin)

    It will make patronictl wait until the requested action is acknowledged by all nodes in the cluster. Such behaviour is achieved by exposing the pause flag for every node in DCS and via the REST API.

  • Rename patronictl failover into patronictl switchover (Alexander Kukushkin)

    The previous failover was actually only capable of doing a switchover; it refused to proceed in a cluster without the leader.

  • Alter the behavior of patronictl failover (Alexander Kukushkin)

    It will work even if there is no leader, but in that case you will have to explicitly specify a node which should become the new leader.

Expose information about timeline and history

  • Expose current timeline in DCS and via API (Alexander Kukushkin)

    Store information about the current timeline for each member of the cluster. This information is accessible via the API and is stored in the DCS

  • Store promotion history in the /history key in DCS (Alexander Kukushkin)

    In addition, store the timeline history enriched with the timestamp of the corresponding promotion in the /history key in DCS and update it with each promote.

Add endpoints for getting synchronous and asynchronous replicas

  • Add new /sync and /async endpoints (Alexander Kukushkin, Oleksii Kliukin)

Those endpoints (also accessible as /synchronous and /asynchronous) return 200 only for synchronous and asynchronous replicas correspondingly (excluding those marked as noloadbalance).

Allow multiple hosts for Etcd

  • Add a new hosts parameter to Etcd configuration (Alexander Kukushkin)

    This parameter contains the initial hosts for discovering the running etcd cluster members. If all discovered hosts become unavailable, Patroni returns to the initial hosts list.


Version 1.3.6

Released 2017-11-10

Stability improvements

  • Verify process start time when checking if postgres is running. (Ants Aasma)

    After a crash, a stale postmaster.pid can match a new process with the same PID. This caused a false positive in is_running() and subsequent incorrect behavior.

  • Shutdown postgresql before bootstrap when we lost data directory (ainlolcat)

    After forced removal of the master data directory, Postgres can remain alive temporarily. It can prevent the replacement replica from starting or replicating. Patroni now caches postmaster PID and start time. It terminates the old postmaster if it still runs after data directory removal.

  • Perform crash recovery in a single user mode if postgres master dies (Alexander Kukushkin)

    It is unsafe to start immediately as a standby and not possible to run pg_rewind if postgres hasn’t been shut down cleanly. The single user crash recovery only kicks in if pg_rewind is enabled or there is no master at the moment.

Consul improvements

  • Make it possible to provide datacenter configuration for Consul (Vilius Okockis, Alexander Kukushkin)

    Before that Patroni was always communicating with datacenter of the host it runs on.

  • Always send a token in X-Consul-Token http header (Alexander Kukushkin)

    Patroni now always sends consul.token in the X-Consul-Token HTTP header. python-consul follows the Consul REST API, whose session API rejects tokens in query parameters. The X-Consul-Token header still works.

  • Adjust session TTL if supplied value is smaller than the minimum possible (Stas Fomin, Alexander Kukushkin)

    A configured TTL can be below the Consul minimum. Consul then cannot create a session. Without a session, Patroni cannot create member or leader keys in the Consul KV store, leaving the cluster unhealthy.

Other improvements

  • Define custom log format via environment variable PATRONI_LOGFORMAT (Stas Fomin)

    Allow disabling timestamps and other similar fields in Patroni logs if they are already added by the system logger (usually when Patroni runs as a service).


Version 1.3.5

Released 2017-10-12

Bugfix

  • Set role to ‘uninitialized’ if data directory was removed (Alexander Kukushkin)

    If the node was running as a master it was preventing from failover.

Stability improvement

  • Try to run postmaster in a single-user mode if we tried and failed to start postgres (Alexander Kukushkin)

    This usually occurs after termination of a master and timeline divergence. With restore_command in recovery.conf, Postgres is very likely to abort startup without changing controldata. This prevents pg_rewind, which requires a clean shutdown.

Consul improvements

  • Make it possible to specify health checks when creating session (Alexander Kukushkin)

    If not specified, Consul will use “serfHealth”. On the one hand, this allows fast detection of an isolated master; on the other hand, it makes it impossible for Patroni to tolerate short network lags.

Bugfix

  • Fix watchdog on Python 3 (Ants Aasma)

    The code misunderstood ioctl(). With mutable=False, fcntl.ioctl() returns the argument buffer. This accidentally worked in Python2 because int-to-str comparisons did not raise errors. ioctl errors raise IOError in Python2 and OSError in Python3.


Version 1.3.4

Released 2017-09-08

Different Consul improvements

  • Pass the consul token as a header (Andrew Colin Kissa)

    Headers are now the preferred way to pass the token to the consul API.

  • Advanced configuration for Consul (Alexander Kukushkin)

    possibility to specify scheme, token, client and ca certificates details.

  • compatibility with python-consul-0.7.1 and above (Alexander Kukushkin)

    new python-consul module has changed signature of some methods

  • “Could not take out TTL lock” message was never logged (Alexander Kukushkin)

    Not a critical bug, but lack of proper logging complicates investigation in case of problems.

Quote synchronous_standby_names using quote_ident

  • When writing synchronous_standby_names into the postgresql.conf its value must be quoted (Alexander Kukushkin)

    If it is not quoted properly, PostgreSQL will effectively disable synchronous replication and continue to work.

Different bugfixes around pause state, mostly related to watchdog (Alexander Kukushkin)

  • Do not send keepalives if watchdog is not active
  • Avoid activating watchdog in a pause mode
  • Set correct postgres state in pause mode
  • Do not try to run queries from API if postgres is stopped

Version 1.3.3

Released 2017-08-04

Bugfixes

  • synchronous replication was disabled shortly after promotion even when synchronous_mode_strict was turned on (Alexander Kukushkin)
  • create empty pg_ident.conf file if it is missing after restoring from the backup (Alexander Kukushkin)
  • open access in pg_hba.conf to all databases, not only postgres (Franco Bellagamba)

Version 1.3.2

Released 2017-07-31

Bugfix

  • patronictl edit-config didn’t work with ZooKeeper (Alexander Kukushkin)

Version 1.3.1

Released 2017-07-28

Bugfix

  • failover via API was broken due to change in _MemberStatus (Alexander Kukushkin)

Version 1.3

Released 2017-07-27

Version 1.3 adds custom bootstrap possibility, significantly improves support for pg_rewind, enhances the synchronous mode support, adds configuration editing to patronictl and implements watchdog support on Linux. In addition, this is the first version to work correctly with PostgreSQL 10.

Upgrade notice

There are no known compatibility issues with this Patroni version. Version 1.2 configuration should work unchanged. Install the new packages, then restart Patroni; this also restarts PostgreSQL. Alternatively, enter pause mode before restarting Patroni on all cluster nodes. In pause mode, Patroni does not try to stop or start PostgreSQL. Resume the cluster afterward.

Custom bootstrap

  • Make the process of bootstrapping the cluster configurable (Alexander Kukushkin)

    Allow custom bootstrap scripts instead of initdb when initializing the very first node in the cluster. The bootstrap command receives the name of the cluster and the path to the data directory. The resulting cluster can be configured to perform recovery, making it possible to bootstrap from a backup and do point in time recovery. Refer to the documentation page for more detailed description of this feature.

Smarter pg_rewind support

  • Decide on whether to run pg_rewind by looking at the timeline differences from the current master (Alexander Kukushkin)

    Previously, Patroni triggered pg_rewind when starting a former master or handling other nodes during a switchover to a designated node. It also triggered pg_rewind when a replica had the nofailover tag. In each case, a replica might be ahead of the new master. These rules sometimes ran pg_rewind unnecessarily or missed a necessary rewind. Patroni now compares master and replica WAL positions through the streaming replication protocol to decide reliably whether rewind is required.

Synchronous replication mode strict

  • Enhance synchronous replication support by adding the strict mode (James Sewell, Alexander Kukushkin)

    With synchronous_mode, Patroni normally disables synchronous replication when no replicas are attached, keeping the master writable. With synchronous_mode_strict, it retains synchronous replication and blocks client writes when no replicas exist. Synchronous mode already prevents data loss from automatic failover. Strict mode also ensures that each write is stored durably on two nodes, or blocked when the cluster has only one node.

Configuration editing with patronictl

  • Add configuration editing to patronictl (Ants Aasma, Alexander Kukushkin)

    Add the ability to patronictl of editing dynamic cluster configuration stored in DCS. Support either specifying the parameter/values from the command-line, invoking the $EDITOR, or applying configuration from the yaml file.

Linux watchdog support

  • Implement watchdog support for Linux (Ants Aasma)

    The Linux software watchdog reboots a node when Patroni stops or does not respond, for example under high load. Configure the device and mode in the watchdog section. The default device is /dev/watchdog; modes are on, automatic, and off. See the watchdog documentation.

Add support for PostgreSQL 10

  • Patroni is compatible with all beta versions of PostgreSQL 10 released so far and we expect it to be compatible with the PostgreSQL 10 when it will be released.

PostgreSQL-related minor improvements

  • Define pg_hba.conf via the Patroni configuration file or the dynamic configuration in DCS (Alexander Kukushkin)

    Define pg_hba.conf content in the postgresql section’s pg_hba subsection. Defining it once in DCS simplifies management across nodes. It replaces manual edits and configuration reloads on each node.

    When defined, the contents of this section will replace the current pg_hba.conf completely. Patroni ignores it if hba_file PostgreSQL parameter is set.

  • Support connecting via a UNIX socket to the local PostgreSQL cluster (Alexander Kukushkin)

    Set use_unix_socket to true in the postgresql section to connect locally through a UNIX socket. If unix_socket_directories is nonempty, Patroni uses its first value. If it is undefined, Patroni assumes its default and omits host from the PostgreSQL connection string.

  • Support change of superuser and replication credentials on reload (Alexander Kukushkin)

  • Support storing of configuration files outside of PostgreSQL data directory (@jouir)

    Add the new configuration postgresql configuration directive config_dir. It defaults to the data directory and must be writable by Patroni.

Bug fixes and stability improvements

  • Handle EtcdEventIndexCleared and EtcdWatcherCleared exceptions (Alexander Kukushkin)

    Faster recovery when the watch operation is ended by Etcd by avoiding useless retries.

  • Remove error spinning on Etcd failure and reduce log spam (Ants Aasma)

    Avoid immediate retrying and emitting stack traces in the log on the second and subsequent Etcd connection failures.

  • Export locale variables when forking PostgreSQL processes (Oleksii Kliukin)

    Avoid the postmaster became multithreaded during startup fatal error on non-English locales for PostgreSQL built with NLS.

  • Extra checks when dropping the replication slot (Alexander Kukushkin)

    In some cases Patroni is prevented from dropping the replication slot by the WAL sender.

  • Truncate the replication slot name to 63 (NAMEDATALEN - 1) characters to comply with PostgreSQL naming rules (Nick Scott)

  • Fix a race condition resulting in extra connections being opened to the PostgreSQL cluster from Patroni (Alexander Kukushkin)

  • Release the leader key when the node restarts with an empty data directory (Alex Kerney)

  • Set asynchronous executor busy when running bootstrap without a leader (Alexander Kukushkin)

    Without this busy state, Patroni continued normal operations during bootstrap by a method that did not require a leader. This could cause errors claiming that the node belonged to another cluster.

  • Improve WAL-E replica creation method (Joar Wandborg, Alexander Kukushkin).

    • Use csv.DictReader when parsing WAL-E base backup, accepting ISO dates with space-delimited date and time.
    • Support fetching current WAL position from the replica to estimate the amount of WAL to restore. Previously, the code used to call system information functions that were available only on the master node.

Version 1.2

Released 2016-12-13

This version improves synchronous replication, startup reliability, and failover reliability. It adds PostgreSQL 9.6 support and fixes bugs. Documentation, including release notes, has moved to Patroni documentation.

Synchronous replication

  • Add synchronous replication support. (Ants Aasma)

    The new synchronous_mode setting makes Patroni manage synchronous_standby_names and enable synchronous replication when healthy standbys exist. Automatic failover then selects only a standby that replicated synchronously at master failure. No user-visible transaction is lost in this case. See the feature documentation for behavior and implementation details.

Reliability improvements

  • Do not try to update the leader position stored in the leader optime key when PostgreSQL is not 100% healthy. Demote immediately when the update of the leader key failed. (Alexander Kukushkin)

  • Exclude unhealthy nodes from the list of targets to clone the new replica from. (Alexander Kukushkin)

  • Implement retry and timeout strategy for Consul similar to how it is done for Etcd. (Alexander Kukushkin)

  • Make --dcs and --config-file apply to all options in patronictl. (Alexander Kukushkin)

  • Write all postgres parameters into postgresql.conf. (Alexander Kukushkin)

    It allows starting PostgreSQL configured by Patroni with just pg_ctl.

  • Avoid exceptions when there are no users in the config. (Kirill Pushkin)

  • Allow pausing an unhealthy cluster. Before this fix, patronictl would bail out if the node it tries to execute pause on is unhealthy. (Alexander Kukushkin)

  • Improve the leader watch functionality. (Alexander Kukushkin)

    Previously, replicas always watched the leader key until timeout or a key change. They now watch only when PostgreSQL is running. They do not watch while it is stopped, starting, or restarting.

  • Avoid running into race conditions when handling SIGCHILD as a PID 1. (Alexander Kukushkin)

    In Docker containers, one Patroni process both started children and handled their SIGCHILD signals. This could cause a race. Patroni now uses fork/exec and leaves the original PID 1 process to handle child signals.

  • Fix WAL-E restore. (Oleksii Kliukin)

    Previously, WAL-E restore used no_master to bypass the master check. Patroni therefore always preferred WAL restore to pg_basebackup. The original no_master meaning is restored: Patroni can select WAL-E when the master is not running. It checks this through the connection string passed to the method. This change also improves retries and handles other minor issues.

  • Implement asynchronous DNS resolver cache. (Alexander Kukushkin)

    Avoid failing when DNS is temporary unavailable (for instance, due to an excessive traffic received by the node).

  • Implement starting state and master start timeout. (Ants Aasma, Alexander Kukushkin)

    Previously, pg_ctl assumed PostgreSQL was running after a timeout, even when it was not. The resulting race could cause failover, crash recovery, or failover during recovery with a missed rewind. The new master_start_timeout parameter and starting HA state address this. With master_start_timeout set to 0, a master crash triggers immediate failover if a candidate exists. Otherwise, Patroni tries to start the master, waits for the timeout, and then fails over if possible. Manual failover requests remain valid before the timeout expires.

    Introduce the timeout parameter to the restart API endpoint and patronictl. When it is set and restart takes longer than the timeout, PostgreSQL is considered unhealthy and the other nodes becomes eligible to take the leader lock.

  • Fix pg_rewind behavior in a pause mode. (Ants Aasma)

    In pause mode, avoid a restart when rewind is required but unavailable, for example when pg_rewind is absent. If rewind configuration omits superuser authentication, use libpq defaults for superuser, including the OS user.

  • Serialize callback execution. Kill the previous callback of the same type when the new one is about to run. Fix the issue of spawning zombie processes when running callbacks. (Alexander Kukushkin)

  • Avoid promoting a former master when the leader key is set in DCS but update to this leader key fails. (Alexander Kukushkin)

    A partition can isolate the current master with a minority of DCS nodes. This change prevents it from keeping its role. It applies to Etcd and other DCSs that allow “inconsistent reads”.

Miscellaneous

  • Add post_init configuration option on bootstrap. (Alejandro Martínez)

    Patroni will call the script argument of this option right after running initdb and starting up PostgreSQL for a new cluster. The script receives a connection URL with superuser and sets PGPASSFILE to point to the .pgpass file containing the password. If the script fails, Patroni initialization fails as well. It is useful for adding new users or creating extensions in the new cluster.

  • Implement PostgreSQL 9.6 support. (Alexander Kukushkin)

    Use wal_level = replica as a synonym for hot_standby, avoiding pending_restart flag when it changes from one to another. (Alexander Kukushkin)

Documentation improvements

  • Add a Patroni main loop workflow diagram. (Alejandro Martínez, Alexander Kukushkin)

  • Improve README, adding the Helm chart and links to release notes. (Lauri Apple)

  • Move Patroni documentation to Read the Docs. The up-to-date documentation is available at Patroni documentation. (Oleksii Kliukin)

    Makes the documentation easily viewable from different devices (including smartphones) and searchable.

  • Move the package to the semantic versioning. (Oleksii Kliukin)

    Patroni will follow the major.minor.patch version schema to avoid releasing the new minor version on small but critical bugfixes. We will only publish the release notes for the minor version, which will include all patches.


Version 1.1

Released 2016-09-07

This release adds pause mode and improves maintenance with scheduled and conditional restarts. It also improves Etcd and Zookeeper connection reliability and extends patronictl.

Upgrade notice

When upgrading from releases below 1.0 read about changing of credentials and configuration format at 1.0 release notes.

Pause mode

  • Introduce pause mode to temporary detach Patroni from managing PostgreSQL instance (Murat Kabilov, Alexander Kukushkin, Oleksii Kliukin).

    Previously, one had to send SIGKILL signal to Patroni to stop it without terminating PostgreSQL. The new pause mode detaches Patroni from PostgreSQL cluster-wide without terminating Patroni. It is similar to the maintenance mode in Pacemaker. Patroni is still responsible for updating member and leader keys in DCS, but it will not start, stop or restart PostgreSQL server in the process. There are a few exceptions, for instance, manual failovers, reinitializes and restarts are still allowed. You can read a detailed description of this feature.

In addition, patronictl supports new pause and resume commands to toggle the pause mode.

Scheduled and conditional restarts

  • Add conditions to the restart API command (Oleksii Kliukin)

    Restart requests can now have conditions. These can require a master or replica role, a PostgreSQL version, or pending configuration changes that need a restart.

  • Add scheduled restarts (Oleksii Kliukin)

    You can schedule one future restart per node and clear it when no longer needed. Scheduled restarts can also have conditions. For example, schedule a nighttime minor upgrade that restarts only outdated PostgreSQL instances. Administration scripts do not need PostgreSQL-specific logic for this.

  • Add support for conditional and scheduled restarts to patronictl (Murat Kabilov).

    patronictl restart supports several new options. There is also patronictl flush command to clean the scheduled actions.

Robust DCS interaction

  • Set Kazoo timeouts depending on the loop_wait (Alexander Kukushkin)

    Originally, ping_timeout and connect_timeout values were calculated from the negotiated session timeout. Patroni loop_wait was not taken into account. As a result, a single retry could take more time than the session timeout, forcing Patroni to release the lock and demote.

    This change set ping and connect timeouts to half of loop_wait. It accelerated connection problem detection. It also left enough time to retry the connection before losing the lock.

  • Update Etcd topology only after original request succeed (Alexander Kukushkin)

    Update the client’s Etcd topology after the original request succeeds. During discovery, set retry timeouts according to the known Etcd node count. This prioritizes request results over an updated node list.

    Both changes make Patroni connections to DCS more robust in the face of network issues.

Patronictl, monitoring and configuration

  • Return information about streaming replicas via the API (Feike Steenbergen)

Previously, there was no reliable way to query Patroni about PostgreSQL instances that fail to stream changes (for instance, due to connection issues). This change exposes the contents of pg_stat_replication via the /patroni endpoint.

  • Add patronictl scaffold command (Oleksii Kliukin)

    This command creates an Etcd cluster structure with a user-specified sysid and leader. Leader and member keys are persistent. It supports master-less configurations where Patroni replicas follow an external master that does not use Patroni. Later, remove the leader key to promote a Patroni node and replace the original master with a Patroni HA cluster.

  • Add configuration option bin_dir to locate PostgreSQL binaries (Ants Aasma)

    It is useful to be able to specify the location of PostgreSQL binaries explicitly when Linux distros that support installing multiple PostgreSQL versions at the same time.

  • Allow configuration file path to be overridden using custom_conf of (Alejandro Martínez)

    Allows for custom configuration file paths, which will be unmanaged by Patroni, details.

Bug fixes and code improvements

  • Make Patroni compatible with new version schema in PostgreSQL 10 and above (Feike Steenbergen)

    Make sure that Patroni understand 2-digits version numbers when doing conditional restarts based on the PostgreSQL version.

  • Use pkgutil to find DCS modules (Alexander Kukushkin)

    Use the dedicated python module instead of traversing directories manually in order to find DCS modules.

  • Always call on_start callback when starting Patroni (Alexander Kukushkin)

    Previously, Patroni did not call callbacks when joining a running node with the correct role. Callbacks often configure client routing, so this could leave the node unregistered. Patroni now calls on_start even when joining a running node.

  • Do not drop active replication slots (Murat Kabilov, Oleksii Kliukin)

    Avoid dropping active physical replication slots on master. PostgreSQL cannot drop such slots anyway. This change makes possible to run non-Patroni managed replicas/consumers on the master.

  • Close Patroni connections during start of the PostgreSQL instance (Alexander Kukushkin)

    Forces Patroni to close all former connections when PostgreSQL node is started. Avoids the trap of reusing former connections if postmaster was killed with SIGKILL.

  • Replace invalid characters when constructing slot names from member names (Ants Aasma)

    Make sure that standby names that do not comply with the slot naming rules don’t cause the slot creation and standby startup to fail. Replace the dashes in the slot names with underscores and all other characters not allowed in slot names with their unicode codepoints.


Version 1.0

Released 2016-07-05

This release introduces the global dynamic configuration that allows dynamic changes of the PostgreSQL and Patroni configuration parameters for the entire HA cluster. It also delivers numerous bugfixes.

Upgrade notice

When upgrading from v0.90 or below, always upgrade all replicas before the master. Since we don’t store replication credentials in DCS anymore, an old replica won’t be able to connect to the new master.

Dynamic Configuration

  • Implement the dynamic global configuration (Alexander Kukushkin)

    The new /config REST API endpoint supplies global PostgreSQL and Patroni settings for the master and all replicas. These settings reside in DCS. Many can change without disrupting PostgreSQL or Patroni. Values that require a PostgreSQL restart set the API-visible “pending restart” flag. Issue the restart manually through the API.

    Patroni SIGHUP or POST to /reload will make it re-read the configuration file.

    See the Patroni configuration for the details on which parameters can be changed and the order of processing difference configuration sources.

    The configuration file format has changed since v0.90. Old configuration files remain compatible, but bootstrap parameters require the new format. Use the dynamic configuration documentation page to update them.

More flexible configuration*

  • Make postgresql configuration and database name Patroni connects to configurable (Misja Hoebe)

    Introduce database and config_base_name configuration parameters. Among others, it makes possible to run Patroni with PipelineDB and other PostgreSQL forks.

  • Implement possibility to configure some Patroni configuration parameters via environment (Alexander Kukushkin)

    Environment settings include scope, node name, namespace, and secrets. They simplify operation in dynamic environments such as Kubernetes. See the supported environment variables.

  • Update the built-in Patroni docker container to take advantage of environment-based configuration (Feike Steenbergen).

  • Add Zookeeper support to Patroni docker image (Alexander Kukushkin)

  • Split the Zookeeper and Exhibitor configuration options (Alexander Kukushkin)

  • Make patronictl reuse the code from Patroni to read configuration (Alexander Kukushkin)

    This allows patronictl to take advantage of environment-based configuration.

  • Set application name to node name in primary_conninfo (Alexander Kukushkin)

    This simplifies identification and configuration of synchronous replication for a given node.

Stability, security and usability improvements

  • Reset sysid and do not call pg_controldata when restore of backup in progress (Alexander Kukushkin)

    This change reduces the amount of noise generated by Patroni API health checks during the lengthy initialization of this node from the backup.

  • Fix a bunch of pg_rewind corner-cases (Alexander Kukushkin)

    Avoid running pg_rewind if the source cluster is not the master.

    In addition, avoid removing the data directory on an unsuccessful rewind, unless the new parameter remove_data_directory_on_rewind_failure is set to true. By default it is false.

  • Remove passwords from the replication connection string in DCS (Alexander Kukushkin)

    Previously, Patroni always used the replication credentials from the Postgres URL in DCS. That is now changed to take the credentials from the patroni configuration. The secrets (replication username and password) and no longer exposed in DCS.

  • Fix the asynchronous machinery around the demote call (Alexander Kukushkin)

    Demote now runs totally asynchronously without blocking the DCS interactions.

  • Make patronictl always send the authorization header if it is configured (Alexander Kukushkin)

    This allows patronictl to issue “protected” requests, i.e. restart or reinitialize, when Patroni is configured to require authorization on those.

  • Handle the SystemExit exception correctly (Alexander Kukushkin)

    Avoids the issues of Patroni not stopping properly when receiving the SIGTERM

  • Sample haproxy templates for confd (Alexander Kukushkin)

    Generates and dynamically changes haproxy configuration from the patroni state in the DCS using confide

  • Improve and restructure the documentation to make it more friendly to the new users (Lauri Apple)

  • API must report role=master during pg_ctl stop (Alexander Kukushkin)

    Makes the callback calls more reliable, particularly in the cluster stop case. In addition, introduce the pg_ctl_timeout option to set the timeout for the start, stop and restart calls via the pg_ctl.

  • Fix the retry logic in etcd (Alexander Kukushkin)

    Make retries more predictable and robust.

  • Make Zookeeper code more resilient against short network hiccups (Alexander Kukushkin)

    Reduce the connection timeouts to make Zookeeper connection attempts more frequent.


Version 0.90

Released 2016-04-27

This releases adds support for Consul, includes a new noloadbalance tag, changes the behavior of the clonefrom tag, improves pg_rewind handling and improves patronictl control program.

Consul support

  • Implement Consul support (Alexander Kukushkin)

    Patroni runs against Consul, in addition to Etcd and Zookeeper. the connection parameters can be configured in the YAML file.

New and improved tags

  • Implement noloadbalance tag (Alexander Kukushkin)

    This tag makes Patroni always return that the replica is not available to the load balancer.

  • Change the implementation of the clonefrom tag (Alexander Kukushkin)

    Previously, clonefrom required a node name and forced the tagged replica to clone from that node. It is now boolean. With true, the tagged replica becomes a source candidate for other replicas. When multiple candidates exist, replicas choose one randomly.

Stability and security improvements

  • Numerous reliability improvements (Alexander Kukushkin)

    Removes some spurious error messages, improves the stability of the failover, addresses some corner cases with reading data from DCS, shutdown, demote and reattaching of the former leader.

  • Improve systems script to avoid killing Patroni children on stop (Jan Keirse, Alexander Kukushkin)

    Previously, systemd sent PostgreSQL a shutdown signal when stopping Patroni. Patroni also sent a shutdown request, so PostgreSQL received smart shutdown followed by fast shutdown. Replicas disconnected too early, and the former master could not rejoin after demotion. Jan implemented the fix after Alexander’s research.

  • Eliminate some cases where the former master was unable to call pg_rewind before rejoining as a replica (Oleksii Kliukin)

    Previously, Patroni called pg_rewind only after a former master crashed. It now runs pg_rewind for the former master whenever the tool is available. This handles master shutdown before replicas receive the latest changes, for example during smart shutdown.

  • Numerous improvements to unit- and acceptance- tests, in particular, enable support for Zookeeper and Consul (Alexander Kukushkin).

  • Make Travis CI faster and implement support for running tests against Zookeeper (Exhibitor) and Consul (Alexander Kukushkin)

    Both unit and acceptance tests run automatically against Etcd, Zookeeper and Consul on each commit or pull-request.

  • Clear environment variables before calling PostgreSQL commands from Patroni (Feike Steenbergen)

    This prevents a possibility of reading system environment variables by connecting to the PostgreSQL cluster managed by Patroni.

Configuration and control changes

  • Unify patronictl and Patroni configuration (Feike Steenbergen)

    patronictl can use the same configuration file as Patroni itself.

  • Enable Patroni to read the configuration from the environment variables (Oleksii Kliukin)

    This simplifies generating configuration for Patroni automatically, or merging a single configuration from different sources.

  • Include database system identifier in the information returned by the API (Feike Steenbergen)

  • Implement delete_cluster for all available DCSs (Alexander Kukushkin)

    Enables support for DCSs other than Etcd in patronictl.


Version 0.80

Released 2016-03-14

This release adds cascading replication and scheduled failovers. Older Patroni versions, particularly 0.78, can run with this version during migration. Cascading replication and scheduled failover features require Patroni 0.80 or later.

Cascading replication

  • Add support for the replicatefrom and clonefrom tags for the patroni node (Oleksii Kliukin).

The tag replicatefrom allows a replica to use an arbitrary node a source, not necessary the master. The clonefrom does the same for the initial backup. Together, they enable Patroni to fully support cascading replication.

  • Add support for running replication methods to initialize the replica even without a running replication connection (Oleksii Kliukin).

This is useful in order to create replicas from the snapshots stored on S3 or FTP. A replication method that does not require a running replication connection should supply no_master: true in the yaml configuration. Those scripts will still be called in order if the replication connection is present.

Patronictl, API and DCS improvements

  • Implement scheduled failovers (Feike Steenbergen).

    Failovers can be scheduled to happen at a certain time in the future, using either patronictl, or API calls.

  • Add support for dbuser and password parameters in patronictl (Feike Steenbergen).

  • Add PostgreSQL version to the health check output (Feike Steenbergen).

  • Improve Zookeeper support in patronictl (Oleksandr Shulgin)

  • Migrate to python-etcd 0.43 (Alexander Kukushkin)

Configuration

  • Add a sample systems configuration script for Patroni (Jan Keirse).
  • Fix the problem of Patroni ignoring the superuser name specified in the configuration file for DB connections (Alexander Kukushkin).
  • Fix the handling of CTRL-C by creating a separate session ID and process group for the postmaster launched by Patroni (Alexander Kukushkin).

Tests

  • Add acceptance tests with behave in order to check real-world scenarios of running Patroni (Alexander Kukushkin, Oleksii Kliukin).

    The tests can be launched manually using the behave command. They are also launched automatically for pull requests and after commits.

    Release notes for some older versions can be found on project’s github page.

20 - Contributing guidelines

Contribution workflow, support channels, and development guidelines.

Source: https://patroni.readthedocs.io/en/latest/contributing_guidelines.html


Chatting

For questions, interactive troubleshooting, or discussion with other users, join #patroni on PostgreSQL Slack.


Reporting bugs

Before you report a bug, reproduce it with the latest Patroni version. Check the Issues Tracker for an existing report.


Running tests

Requirements for running behave tests:

  1. Install PostgreSQL packages, including contrib modules.
  2. Add PostgreSQL binaries to PATH. For example, use PATH=/usr/lib/postgresql/11/bin:\$PATH python -m behave.
  3. For external DCS tests, install the relevant packages, such as Etcd, Consul, or Zookeeper. Run their services on localhost and the default port, with unencrypted, unprotected connections. For Etcd and Consul, the behave suite can start the services if their binaries are in PATH.

Install dependencies:

# You may want to use Virtualenv or specify pip3.
pip install -r requirements.txt
pip install -r requirements.dev.txt

After you install the dependencies, run the test suites:

# You may want to use Virtualenv or specify python3.

# Run flake8 to check syntax and formatting:
python setup.py flake8

# Run the pytest suite in tests/:
python setup.py test

# Moreover, you may want to run tests in different scopes for debugging purposes,
# the -s option include print output during test execution.
# Tests in pytest typically follow the pattern: FILEPATH::CLASSNAME::TESTNAME.
pytest -s tests/test_api.py
pytest -s tests/test_api.py::TestRestApiHandler
pytest -s tests/test_api.py::TestRestApiHandler::test_do_GET

# Run the behave (https://behave.readthedocs.io/en/latest/) test suite in features/;
# modify DCS as desired (raft has no dependencies so is the easiest to start with):
DCS=raft python -m behave

Testing with tox

Tox tests require one dependency in addition to Python:

pip install tox>=4

For behave tests, also install Docker.

The environments in tox.ini run these tasks:

  • lint: Python code lint with flake8
  • test: unit tests for all available python interpreters with pytest, generates XML reports or HTML reports if a TTY is detected
  • dep: detect package dependency conflicts using pipdeptree
  • type: static type checking with pyright
  • black: code formatting with black
  • docker-build: build docker image used for the behave env
  • docker-cmd: run arbitrary command with the above image
  • docker-behave-etcd: run tox for behave tests with above image
  • py*behave: run behave with available python interpreters (without docker, although this is what is called inside docker containers)
  • docs: build docs with sphinx

Running tox

Run the default environments (dep, lint, test, and docs):

tox

The test envs can be run with the label `test`:

tox -m test

The behave docker tests can be run with the label `behave`:

tox -m behave

Similarly, docs has the label docs.

All other envs can be run with their respective env names:

tox -e lint
tox -e py39-test-lin

Use factors to select some environments. For example, run all Python 3.10 environments:

tox -f py310

This is equivalent to running all the envs listed below:

$ tox -l -f py310
py310-test-lin
py310-test-mac
py310-test-win
py310-type-lin
py310-type-mac
py310-type-win
py310-behave-etcd-lin
py310-behave-etcd-win
py310-behave-etcd-mac

With tox >=v4, list all configured environment combinations:

tox l

With an active terminal, the test and docs environments try to open their HTML output after completion. This helps developers who run them locally. They use open on Mac and xdg-open on Linux. To use another command, set OPEN_CMD to its name or path. A failure to open the output does not fail the test run. To disable this behavior, set OPEN_CMD to the : no-op command.

OPEN_CMD=: tox -m docs

Behave tests

The -m behave tests build Docker images for PG_MAJOR versions 11 through 16, then run all behave tests. This can take a long time. You may limit tests to one Postgres version, feature set, or group of steps.

To select a Postgres version, specify the full dependent image build environment name, then the behave environment name. For Postgres 14, use:

tox -e pg14-docker-build,pg14-docker-behave-etcd-lin

To test one feature, pass positional arguments to behave. This example tests the watchdog feature with all Postgres versions:

tox -m behave -- features/watchdog.feature

You can combine the version and feature selections.


Contributing a pull request

  1. Fork the repository. Develop and test your changes.
  2. Update the user documentation.
  3. Submit a pull request that clearly describes the purpose of the changes. Link an existing issue if necessary.

The maintainers will review your pull request as soon as possible.