postgres_keepalive
The `postgres_keepalive` directive configures the keepalive settings for PostgreSQL connections in NGINX.
Description
The postgres_keepalive directive is used within the upstream context to manage the longevity and number of persistent connections to a PostgreSQL database server. By configuring this directive, users can optimize resource usage by maintaining a pool of connections to avoid the performance overhead associated with repeatedly establishing connections for each request. The directive accepts multiple parameters, with the most significant being max, which specifies the maximum number of keepalive connections that can be opened per worker process. This limits the number of concurrent connections to safeguard against resource exhaustion. The mode parameter determines how the connections are selected for use: single allows only one connection per request, whereas multi can utilize multiple connections for a given request, optimizing concurrent database operations.
Furthermore, the overflow parameter provides control over how the server should handle requests when the maximum connection limit has been reached. If set to ignore, the server will close a connection after a request if the pool is full, while reject will deny the request with a 503 Service Unavailable response. This directive strengthens the connection handling mechanism, allowing for better scalability and performance when interacting with PostgreSQL databases through NGINX.
Config Example
upstream postgres_backend {
postgres_server 127.0.0.1:5432 dbname=mydb user=myuser password=mypassword;
postgres_keepalive max=15 mode=multi overflow=ignore;
}Make sure to set max according to your server's capacity to avoid connection overload.
If overflow is set to reject, double-check application logic to handle potential 503 responses gracefully.
Adjust mode based on your application needs for parallel database requests to optimize performance.