Too many db connections (django 4.x / ASGI)

852 Views Asked by At

I have deployed a django app (on ASGI using uvicorn) and getting a lot of OperationalError FATAL: sorry, too many clients already

It seems that this is a known issue #33497 for django 4.x and ASGI, but I cant find anything on it (other than acknowledging it) so far

Is there some way around this, or should I switch to WSGI (or downgrade to 3.2)?

It seems to me that this is a blocking issue for using to ASGI altogether. Shouldn't it be better documented? (unless I missed it)

1

There are 1 best solutions below

1
Cpt. Pineapple On

I encountered this issue and resolved it by setting CONN_MAX_AGE = 0 (which is also the default) in my Django settings.py:

DATABASES = {
    "default": {
        "CONN_MAX_AGE": 0,  #  Use 0 to close database connections at the end of each request
        "ENGINE": "django.db.backends.postgresql",
        "HOST": os.environ.get("POSTGRES_HOST", "db"),
        "NAME": os.environ.get("POSTGRES_DB"),
        "PASSWORD": os.environ.get("POSTGRES_PASSWORD"),
        "PORT": os.environ.get("POSTGRES_PORT", "5432"),
        "USER": os.environ.get("POSTGRES_USER"),
    }
}

There are some downsides to CONN_MAX_AGE = 0 as it essentially turns off persistent connections. There might be better solutions like connection pooling or tweaking the number of worker processes to allow for more efficient use of connections.