Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 9 of 10 · Django Performance & Optimization
Interview question

How does Django's connection pooling and CONN_MAX_AGE setting affect performance? Django की कनेक्शन पूलिंग और CONN_MAX_AGE सेटिंग परफॉर्मेंस को कैसे प्रभावित करती है?

Answer

By default, Django opens a new database connection for each request and closes it at the end (CONN_MAX_AGE = 0), which is safe but adds the overhead of a full connection handshake — including authentication and TLS negotiation for remote databases — to every single request.

Setting CONN_MAX_AGE to a positive number of seconds (or None for unlimited) enables persistent connections: a connection is reused across multiple requests as long as it's still valid and hasn't exceeded the max age, avoiding repeated handshake overhead. For high-concurrency deployments, this is often combined with an external connection pooler like PgBouncer in front of PostgreSQL, since Django's built-in persistent connections are per-worker-process, not a true shared pool across all workers.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'CONN_MAX_AGE': 60,
        'CONN_HEALTH_CHECKS': True,
    }
}

डिफ़ॉल्ट रूप से, Django हर रिक्वेस्ट के लिए एक नया डेटाबेस कनेक्शन खोलता है और अंत में इसे बंद कर देता है, जो सुरक्षित है लेकिन हर एक रिक्वेस्ट में एक पूर्ण कनेक्शन हैंडशेक का ओवरहेड जोड़ता है।

CONN_MAX_AGE को एक धनात्मक संख्या पर सेट करना पर्सिस्टेंट कनेक्शन्स को सक्षम करता है। उच्च-कंकरेंसी डिप्लॉयमेंट के लिए, इसे अक्सर PgBouncer जैसे बाहरी कनेक्शन पूलर के साथ जोड़ा जाता है।

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'CONN_MAX_AGE': 60,
        'CONN_HEALTH_CHECKS': True,
    }
}

Was this answer clear?