Skip Navigation
Show nav
Dev Center
  • Get Started
  • Documentation
  • Changelog
  • Search
  • Get Started
    • Node.js
    • Ruby on Rails
    • Ruby
    • Python
    • Java
    • PHP
    • Go
    • Scala
    • Clojure
    • .NET
  • Documentation
  • Changelog
  • More
    Additional Resources
    • Home
    • Elements
    • Products
    • Pricing
    • Careers
    • Help
    • Status
    • Events
    • Podcasts
    • Compliance Center
    Heroku Blog

    Heroku Blog

    Find out what's new with Heroku on our blog.

    Visit Blog
  • Log inorSign up
Hide categories

Categories

  • Heroku Architecture
    • Compute (Dynos)
      • Dyno Management
      • Dyno Concepts
      • Dyno Behavior
      • Dyno Reference
      • Dyno Troubleshooting
    • Stacks (operating system images)
    • Networking & DNS
    • Platform Policies
    • Platform Principles
  • Developer Tools
    • Command Line
    • Heroku VS Code Extension
  • Deployment
    • Deploying with Git
    • Deploying with Docker
    • Deployment Integrations
  • Continuous Delivery & Integration (Heroku Flow)
    • Continuous Integration
  • Language Support
    • Node.js
      • Working with Node.js
      • Node.js Behavior in Heroku
      • Troubleshooting Node.js Apps
    • Ruby
      • Rails Support
      • Working with Bundler
      • Working with Ruby
      • Ruby Behavior in Heroku
      • Troubleshooting Ruby Apps
    • Python
      • Working with Python
      • Background Jobs in Python
      • Python Behavior in Heroku
      • Working with Django
    • Java
      • Java Behavior in Heroku
      • Working with Java
      • Working with Maven
      • Working with Spring Boot
      • Troubleshooting Java Apps
    • PHP
      • PHP Behavior in Heroku
      • Working with PHP
    • Go
      • Go Dependency Management
    • Scala
    • Clojure
    • .NET
      • Working with .NET
  • Databases & Data Management
    • Heroku Postgres
      • Postgres Basics
      • Postgres Getting Started
      • Postgres Performance
      • Postgres Data Transfer & Preservation
      • Postgres Availability
      • Postgres Special Topics
      • Migrating to Heroku Postgres
    • Heroku Key-Value Store
    • Apache Kafka on Heroku
    • Other Data Stores
  • AI
    • Model Context Protocol
    • Vector Database
    • Heroku Inference
      • Inference Essentials
      • AI Models
      • Inference API
      • Quick Start Guides
    • Working with AI
  • Monitoring & Metrics
    • Logging
  • App Performance
  • Add-ons
    • All Add-ons
  • Collaboration
  • Security
    • App Security
    • Identities & Authentication
      • Single Sign-on (SSO)
    • Private Spaces
      • Infrastructure Networking
    • Compliance
  • Heroku Enterprise
    • Enterprise Accounts
    • Enterprise Teams
    • Heroku Connect (Salesforce sync)
      • Heroku Connect Administration
      • Heroku Connect Reference
      • Heroku Connect Troubleshooting
  • Patterns & Best Practices
  • Extending Heroku
    • Platform API
    • App Webhooks
    • Heroku Labs
    • Building Add-ons
      • Add-on Development Tasks
      • Add-on APIs
      • Add-on Guidelines & Requirements
    • Building CLI Plugins
    • Developing Buildpacks
    • Dev Center
  • Accounts & Billing
  • Troubleshooting & Support
  • Integrating with Salesforce
  • Language Support
  • Python
  • Working with Django
  • Concurrency and Database Connections in Django

Concurrency and Database Connections in Django

English — 日本語に切り替える

Last updated November 29, 2024

Table of Contents

  • Persistent Connections
  • Maximum database connections
  • Calculating required connections
  • Number of active 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': 600

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 Essential-tier databases are limited to 20 and 40 connections. Production Tier databases (plans “Standard 0” 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 you have configured Gunicorn to use 3 worker processes 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. For example, if you’re on an essential-0 or essential-1 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 sensible starting point for your application. We recommend knowing the memory requirements of your processes and setting this configuration variable accordingly.

Read Optimizing Python Application Concurrency for more information on tuning Python applications for maximum throughput.

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.

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 enabling connection pooling either with your database client or using PgBouncer.

With your database client

Some database clients support connection pooling. If you are use the psycopg package with Django enable the database connection pool setting, otherwise see the psycopg connection pools documentation.

With PgBouncer

PgBouncer acts as a proxy between your app and the database and shares database server connections among the app clients.

To learn more, see:

  • PgBouncer Configuration
  • Client-Side Postgres Connection Pooling
  • Server-Side Connection Pooling for Heroku Postgres

Keep reading

  • Working with Django

Feedback

Log in to submit feedback.

Scaling a Django Application with Memcache Configuring Django Apps for Heroku

Information & Support

  • Getting Started
  • Documentation
  • Changelog
  • Compliance Center
  • Training & Education
  • Blog
  • Support Channels
  • Status

Language Reference

  • Node.js
  • Ruby
  • Java
  • PHP
  • Python
  • Go
  • Scala
  • Clojure
  • .NET

Other Resources

  • Careers
  • Elements
  • Products
  • Pricing
  • RSS
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku Blog
    • Heroku News Blog
    • Heroku Engineering Blog
  • Twitter
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku
    • Heroku Status
  • Github
  • LinkedIn
  • © 2025 Salesforce, Inc. All rights reserved. Various trademarks held by their respective owners. Salesforce Tower, 415 Mission Street, 3rd Floor, San Francisco, CA 94105, United States
  • heroku.com
  • Legal
  • Terms of Service
  • Privacy Information
  • Responsible Disclosure
  • Trust
  • Contact
  • Cookie Preferences
  • Your Privacy Choices