Video in progress

How do you set the timeouts at the application, connection pool and PostgreSQL levels so they fit together?

Timeouts should shrink from the outside in: HTTP > transaction > statement > lock. Otherwise a query the client has given up on keeps running in the database. A short connectionTimeout in Hikari, and in the database statement_timeout and lock_timeout per role.

📖 Answer

A typical problem: the gateway returns a 504 after 10 seconds, but the query runs in the database for 3 minutes. The user clicks again, and now there are two heavy queries. Under load, that's a self-amplifying disaster.

The layers I set (with example values):

Layer Setting Value
Gateway/client request timeout 10 s
Spring @Transactional(timeout = 8) 8 s
Hikari connectionTimeout 2 s
PostgreSQL statement_timeout 5 s
PostgreSQL lock_timeout 2 s
PostgreSQL idle_in_transaction_session_timeout 30 s
JDBC socketTimeout 30 s (if the network hangs)

Setting it per role is convenient, since the application, reports and migrations connect with different roles:

ALTER ROLE app_api      SET statement_timeout = '5s';
ALTER ROLE app_reports  SET statement_timeout = '10min';
ALTER ROLE app_migrator SET lock_timeout = '3s';

Subtle points:

  • Keep Hikari's connectionTimeout short: if the pool isn't free, returning an error quickly (and opening the circuit breaker) is better than an endless queue.
  • socketTimeout must be bigger than statement_timeout, otherwise JDBC drops the connection while the server keeps executing the query.
  • Don't SET statement_timeout at the session level behind PgBouncer: use the role or SET LOCAL.
  • A query canceled by a timeout returns 57014. I count it separately in metrics, and it's the best source for a list of slow queries.