Redundant PostgreSQL connection in Django


Let’s assume you have a redundant cluster of PostgreSQL servers, eg built with repmgr, and you want your Django application to benefit from this redundancy. As of Django 3.1, this is not really documented, but some easy steps gets you there, if you are using recent versions of PostgreSQL, psycopg2, Django and Python. First of all, you need to setup psycopg2 to access your database. A standard Django settings.py would look like this :

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'yourdb,
        'USER': 'dbuser',
        'PASSWORD': 'dbpassword',
        'HOST': 'dbserver1.example.com',
        'PORT': '5432',
    }
}

Now let’s turn on some cool features like multiple entries in HOST and PORT, plus SSL certificate check :

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'yourdb,
        'USER': 'dbuser',
        'PASSWORD': 'dbpassword',
        'HOST': 'dbserver1.example.com,dbserver2.example.com',
        'PORT': '5432,5432',
        'OPTIONS' = {
            'target_session_attrs': 'read-write',
            'sslmode': 'verify-ca',
            'sslrootcert': '/data/certs/your_chain.pem'
        }
    }
}

You will not find these options in Django 3.1 documentation, but it seems to work fine, with these supplements passed down the chain to psycopg2 and the underlying libpq‘s PQconnectdbParams.

If your database access is read-only (unlikely in most Django applications), set target_session_attrs to ‘any’.