Prevent long running PostgreSQL queries with statement timeout in Django
In an earlier post, I wrote how to prevent long running MySQL queries in a Django project. Here’s how to prevent runaway queries from consuming excessive resources with PostgreSQL:
The lowercase options
option specifies command-line options to send to the server when starting the connection. The -c
argument allows you to set a run-time parameter, in this case, statement_timeout, which will cancel queries that take more than the specified amount of time.
Note that configuring the timeout in this manner will cause long running queries to be cancelled in all Django contexts, whether the query is executed in a request or when running management commands (e.g. shell
or migrate
).
Alternatively, you can choose to set the query timeout only for requests, to allow longer (analytical) queries outside of the request-response cycle.