Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pgbouncer - closing because: unclean server on every connection

I'm running Django 1.3 with PostgreSQL 9.1/PostGIS 1.5, psycopg2 2.4.2 and pgbouncer 1.4.2.

On every single connection to the database I get a log entry in pgbouncer.log:

2011-11-20 02:15:25.027 29538 LOG S-0x96c2200: app_db/[email protected]:5432 closing because: unclean server (age=0).

I can't find any solution to this problem - anybody have an idea why? I've tried reconfiguring pgbouncer (session/transaction mode, different timeouts etc), but to no avail.

like image 395
Dick Avatar asked Nov 20 '11 02:11

Dick


1 Answers

Ok, I think I've figured this out. The problem lies with a long-standing issue with Django and Psycopg2. Basically, Psycopg2 will automatically issue a BEGIN statement to the DB. However, if Django thinks no data-modification has occurred, it won't issue a COMMIT at the end of a transaction.

There are a few solutions to this problem, look at http://www.slideshare.net/OReillyOSCON/unbreaking-your-django-application for more details. Ideally you turn off automatic commits (by setting autocommit = True in your DB settings, awkward naming convention). This prevents transactions on read-only functions, but also on write functions so you need to manually wrap those functions in a @commit_on_success decorator.

Alternatively, just add the django.middleware.transaction.TransactionMiddleware to your Middleware classes. This will wrap every request in a transaction. This means also unnecessarily wrapping read-only requests in a transaction, but it's a quick-and-dirty solution.

like image 89
Dick Avatar answered Sep 25 '22 02:09

Dick