Error connect with Cloud SQL, Cloud Run and Django

I have an application running on Django in Cloud Run that connects to a PostgreSQL database hosted on Cloud SQL. It is currently working and configured as follows:

DATABASES = {'default': env.db()}

DATABASES['default']['OPTIONS'] = {
    'pool': {
        'min_size': 5,
        'max_size': 20
    }
}

This configuration works, but the active connections remain high. When I remove the pool configuration, I end up getting several errors.

2025/04/12 16:24:15 Cloud SQL connection failed. Please see https://cloud.google.com/sql/docs/mysql/connect-run for additional details: failed to get instance: Refresh error: failed to get instance metadata (connection name = "xxx"): googleapi: Error 429: Quota exceeded for quota metric 'Connect Queries' and limit 'Connect Queries per minute per user per region' of service 'sqladmin.googleapis.com' for consumer 'xxx'.

Even after configuring CONN_MAX_AGE, it keeps throwing errors. I’ve tried setting up pgBouncer, but was unsuccessful due to needing permissions that are impossible to access on Cloud SQL. Lastly, I’m running Django in the following way:

WEB_CONCURRENCY=${WEB_CONCURRENCY:-4}
THREADS=${THREADS:-8}

exec /usr/local/bin/gunicorn project.asgi:application \
    --bind "0.0.0.0:$PORT" \
    --workers "$WEB_CONCURRENCY" \
    --worker-class uvicorn.workers.UvicornWorker \
    --threads "$THREADS" \
    --timeout 0

Has anyone ever faced something similar or has a solution for this?

Вернуться на верх