4

Is there a way to set a timeout in django for db transactions or for db queries executed via django's ORM?

A sample use-case:
Heroku limits django web requests to 30sec, after which Heroku terminates the request without allowing django to gracefully roll-back any transactions which have not yet returned. This can leave outstanding transactions open on databases such as postgres. You could configure a timeout in the database, but that would also limit non-web-related queries such as maintenance scripts analytics etc. In this case setting a timeout through django (or via the middleware) would be preferable.

Community
  • 1
  • 1
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359

1 Answers1

1

Yes, this is possible.

For postgres clients there is a configuration parameter called statement_timeout. Good thing: it can be set through environment variables.

That means if you set PGOPTIONS to --statement-timeout=28s in your heroku settings for this app, the statement will fail after 28s.

To keep in mind: this setting then will be used for all dyno types, not only your webservers.

If you want to fix this, you can add the config to your Procfile (with python example):

web: PGOPTIONS=--statement-timeout=28s waitress-serve myapp.wsgi:application
worker: PGOPTIONS= worker.py 

Then only connections from your webserver will have this statement timeout.

Denis Cornehl
  • 4,104
  • 1
  • 20
  • 24