Introducing Dragonfly Cloud! Learn More

Question: How do you configure keepalive settings in postgresql.conf?

Answer

PostgreSQL provides several server-level configuration options for managing connection stability, one of which includes the keepalive settings. These settings are crucial for maintaining persistent connections, especially in environments where network devices might otherwise drop idle connections.

Understanding Keepalive Settings

The primary purpose of TCP keepalive settings is to ensure that the connection between the client and server remains active even when no data is being transmitted. This is particularly useful in preventing disconnections due to router or firewall timeouts.

Configuring Keepalive in postgresql.conf

In PostgreSQL, you can configure keepalive settings using three parameters in the postgresql.conf file:

  1. tcp_keepalives_idle: Determines the amount of time (in seconds) the connection needs to be idle before TCP starts sending keepalive messages.
  2. tcp_keepalives_interval: Sets the interval (in seconds) between individual keepalive probes.
  3. tcp_keepalives_count: Indicates the maximum number of keepalive probes TCP should send before considering the connection dead.

Here's how you might set these parameters:

# in postgresql.conf tcp_keepalives_idle = 300 # 5 minutes tcp_keepalives_interval = 75 # 75 seconds tcp_keepalives_count = 9 # 9 probes

Applying Configuration Changes

After making changes to postgresql.conf, PostgreSQL requires a reload for the new settings to take effect. You can reload the configuration by running the following SQL command from the psql terminal or another SQL interface:

SELECT pg_reload_conf();

This function causes the server to reload its configuration files without interrupting normal operations.

Conclusion

Adjusting the TCP keepalive settings in postgresql.conf is a straightforward way to enhance the resilience of your database connections. The optimal values for these settings can vary based on your specific network environment, so it might require some experimentation to find the best configuration for your use case.

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.