Concurrency and Database Connections in Django | Heroku Dev Center
We use cookies to make interactions with our websites and services easy and meaningful, to better understand how they are used and to tailor advertising. You can read more and make your cookie choices here. By continuing to use this site you are giving us your consent to do this.
Heroku Dev Center
Get Started
DocumentationChangelogMore
Search Dev Center
Log inorSign up
Language Support âș Python âș Working with Django âș Concurrency and Database Connections in Django
Concurrency and Database Connections in Django
Last updated 02 August 2018
Table of Contents
Persistent Connections
Maximum database connections
Calculating required connections
Number of active connections
Bad connections
Limit connections with PgBouncer
When increasing concurrency by using a multi-process web server like Gunicorn, you must be aware of the number of connection your app holds to the database and how many connections the database can accept. Each process requires a different connection to the database. To accommodate this, there are a number of tools for providing a connection pool that can hold several connections at a time.
Persistent Connections
By default, Django will only create a new persistent database connection for every request cycle of your application. This occurs whenever Django attempts to talk to the database through a SQL query.
Constantly opening new connections is an expensive operation, and can be mitigated with the use Djangoâs persistent connections.
Enabling persistent connections is simple. Set CONN_MAX_AGE in your connection settings in settings.py:
DATABASES = {
'default': {
...
'CONN_MAX_AGE': 500
If youâre using the dj-database-url module, this configuration is recommended:
import dj_database_url
DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)
Once configured, everything should work as expected.
Maximum database connections
Heroku provides managed Postgres databases. Different tiered databases have different connection limits. The Starter Tier âDevâ and âBasicâ databases are limited to 20 connections. Production Tier databases (plans Crane and up) have higher limits. Once your database has the maximum number of active connections, it will no longer accept new connections. This will result in connection timeouts from your application and will likely cause exceptions.
When scaling out, it is important to keep in mind how many active connections your application needs. If each dyno allows 5 database connections, you can only scale out to four dynos before you need to provision a more robust database.
Now that you know how to configure your connection pool and how to figure out how many connections your database can handle you will need to calculate the right number of connections that each dyno will need.
Calculating required connections
Assuming that you are not manually creating threads in your application code, you can use your web server settings to guide the number of connections that you need. The Gunicorn web server scales out using multiple processes, if you arenât opening any new threads in your application, each process will take up 1 connection. So if in your config file you have worker_processes set to 3 like this:
heroku config:set WEB_CONCURRENCY=3
then your app will use 3 connections for workers. This means each dyno will require 3 connections. If youâre on a âDevâ plan, you can scale out to 6 dynos which will mean 18 active database connections, out of a maximum of 20. However, it is possible for a connection to get into a bad or unknown state. Due to this we recommend setting the pool of your application to either 1 or 2 to avoid zombie connections from saturating your database. See the âBad connectionâ section below.
The WEB_CONCURRENCY environment variable is automatically set by Heroku, based on the processesâ Dyno size. This feature is intended to be a sane starting point for your application. We recommend knowing the memory requirements of your processes and setting this configuration variable accordingly.
Every application will have different performance characteristics and different requirements. To properly tune the number of threads for your app you will need to load test your app in a production-like or staging environment.
Number of active connections
In production, you can see the number of connections taken up by your application by checking the database.
heroku pg:psql
This will open a connection to your development database. You can then see the number of connections to your postgres database by running:
select count(*) from pg_stat_activity where pid <> pg_backend_pid() and usename = current_user;
Which will return with the number of connections on that database:
count
-------
5
(1 row)
Since connections are opened lazily, youâll need to hit your running application at localhost several times until the count quits going up. To get an accurate count you should run that database query inside of a production database since your development setup may not allow you to generate load required for your app to create new connections.
Bad connections
It is possible for connections to hang, or be placed in a âbadâ state. This means that the connection will be unusable, but remain open. If you are running a multi-process web server such as Gunicorn this could mean that over time a 3 worker dyno which normally consumes 3 database connections could be holding as many as 15 connections (5 default connections per pool times 3 workers). To limit this threat lower the connection pool to 1 or 2.
Limit connections with PgBouncer
You can continue to scale out your applications with additional dynos until you have reached your database connection limits. Before you reach this point it is recommended to limit the number of connections required by each dyno by using the PgBouncer buildpack.
PgBouncer maintains a pool of connections that your database transactions share. This keeps connections to Postgres, that are otherwise open and idle, to a minimum. However, transaction pooling prevents you from using named prepared statements, session advisory locks, listen/notify, or other features that operate on a session level. See the PgBouncer buildpack FAQ for full list of limitations for more information.
heroku buildpacks:add https://github.com/heroku/heroku-buildpack-pgbouncer
Next we need to ensure your application can run so you need to add your language specific buildpack. Since you are using Python it would be:
heroku buildpacks:add heroku/python
Now you must modify your Procfile to start PgBouncer. In your Procfile add the command bin/start-pgbouncer-stunnel to the beginning of your web entry. So if your Procfile was
web: gunicorn hellodjango.wsgi
Will now be:
web: bin/start-pgbouncer-stunnel gunicorn hellodjango.wsgi
Commit the results to git, test on a staging app, and then deploy to production.
When deploying you should see this in the output:
=====> Detected Framework: pgbouncer-stunnel
Keep reading
Working with Django
Feedback
Log in to submit feedback.
Configuring Django Apps for Heroku
INFORMATION & SUPPORT
Getting Started
Documentation
Changelog
Compliance Center
Training & Education
Blog
Podcasts
Support Channels
Status
LANGUAGE REFERENCE
Node.js
Ruby
Java
PHP
Python
Go
Scala
Clojure
OTHER RESOURCES
Careers
Elements
Products
Pricing
Subscribe to our monthly newsletter
do not fill this in
Your email address
RSS
Heroku PodcastsTwitter
FacebookInstagramGithubLinkedIn
HEROKU IS ACOMPANY ©2020 Salesforce.com
heroku.com
Terms of Service
Privacy
Cookies
last updated january 2020