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:

# settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ.get('POSTGRES_NAME', ''),
        'USER': os.environ.get('POSTGRES_USER', ''),
        'PASSWORD': os.environ.get('POSTGRES_PASSWORD', ''),
        'HOST': os.environ.get('POSTGRES_HOST', ''),
        'PORT': 5432,
        'OPTIONS': {
            'options': '-c statement_timeout=5000',  # 5 seconds
        },
    }
}

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.