Question: How do you kill a replication connection in PostgreSQL?


Killing a replication connection in PostgreSQL involves identifying and then terminating the specific backend process or processes associated with replication. This can be necessary for various administrative tasks, such as maintenance operations or resolving replication conflicts. Here's how to do it:

Step 1: Identify Replication Connections

First, you need to identify the PID (Process ID) of the replication connections. Use the pg_stat_replication view for this purpose. It provides information about the current replication connections.

SELECT pid, state, application_name FROM pg_stat_replication;

This query will list all active replication processes, including their PIDs, states, and application names (often the name of the replica).

Step 2: Terminate the Replication Connection

Once you've identified the PID of the replication connection you wish to terminate, you can use the pg_terminate_backend() function to kill it.

SELECT pg_terminate_backend(pid) FROM pg_stat_replication WHERE application_name = 'NameOfYourReplica';

Replace 'NameOfYourReplica' with the actual name of your replication application as identified in the first step. This command terminates the replication process associated with the specified application name.


  • Use With Caution: Terminating a replication connection can lead to replication lag or inconsistencies if not managed properly. Always ensure you understand the implications before proceeding.
  • Recovery: After termination, the replica might automatically try to reconnect depending on its configuration. Ensure that you have addressed the underlying issue that required the termination of the replication connection.
  • Permissions: Executing pg_terminate_backend() requires appropriate permissions; specifically, you must be a superuser or have the pg_signal_backend role.

Alternative Method: Using pg_cancel_backend

If you prefer not to immediately kill the process but rather request its cancellation (which allows for a more graceful termination), you can use pg_cancel_backend(pid) in a similar manner. This sends a request to cancel the current query of the backend process but may not terminate the connection if the process is not in a cancelable state.

SELECT pg_cancel_backend(pid) FROM pg_stat_replication WHERE application_name = 'NameOfYourReplica';

In summary, managing replication connections by killing them is a powerful tool but should be used judiciously and with a full understanding of the potential impact on your replication environment.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book
Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.