如何统计Heroku Postgres数据库连接数及明确连接构成?
Hey there! Let me clarify how Postgres connections work here, since your testing has already given you some clues—let's tie it all together.
First, the core answer to your question: Postgres counts TCP connections from a client to the database server, not user instances of your web app. A "user instance" (someone opening your app in their browser) doesn't directly connect to Postgres—they connect to your Django app, which in turn uses a connection from its pool to talk to the database.
Let's break down your observations:
- Web app "instances" on different devices: Those are browser sessions connecting to your Django server, not direct Postgres connections. Django uses a connection pool (usually via
psycopg2, the Postgres adapter for Python) to reuse connections across requests. The 2 web app connections you saw are likely active/idle connections in your app's pool, not one per user. When a user sends a request, Django grabs an available connection from the pool, uses it, and returns it when done—so multiple users can share the same database connection. - Adminer/pgAdmin showing 2 connections each: Tools like these often open multiple connections for different purposes: one for fetching schema metadata (like listing tables/columns) and another for executing the queries you run. That's why you see 2 entries per tool instead of 1.
- Dataclips: Heroku Dataclips create temporary connections to run your query reports. These connections are usually closed once the report finishes, but occasionally you might see them linger briefly in
pg_stat_activity.
How to confirm this for yourself:
Run this query in Adminer/pgAdmin to get more context about each connection:
select pid, application_name, client_addr, state, query from pg_stat_activity where datname = 'db_name';
- Look at
client_addr: For your Django app connections, this will be the IP of your Heroku dyno(s), not the IP addresses of the users on their devices. That proves users aren't connecting directly to Postgres. application_namemight show something likeDjangofor your app's connections, while Adminer/pgAdmin will have their own names here.
Quick tip for Heroku Hobby/Dev plan (20 connection limit):
Django's default CONN_MAX_AGE setting is 0, which means it closes connections after every request. This can lead to unnecessary connection churn. Set it to a reasonable value (like 60 seconds) in your settings.py:
DATABASES = { 'default': { # ... your other config ... 'CONN_MAX_AGE': 60, } }
This lets Django reuse connections across requests, reducing the number of active connections and keeping you under the 20 limit.
Hope this clears things up! 😊
内容的提问来源于stack exchange,提问作者deepuj1

