5

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)

fekioh
  • 894
  • 2
  • 9
  • 22

1 Answers1

2

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.

Cpt. Pineapple
  • 139
  • 2
  • 11
  • I have had to resort to this as well but as you mention it's not ideal for performance due to having to open new DB connections on every request. From following some issues on the Django issue tracker it seems this was a regression I think I saw in 4.x they are working on resolving. – Marty May 31 '23 at 14:14