Skip to content

Idle database connections not reaped #871

Closed

Description

@andrewgodwin

Initially reported in django/daphne#163

I suspect this is due to the lack of calling close_old_connections, as seen in Channels 1 here: https://github.com/django/channels/blob/1.x/channels/signals.py#L10

Activity

  1. andrewgodwin commented on Feb 6, 2018

    @andrewgodwin
    MemberAuthor

    @michaelhays If you want to verify this would fix it, you can try calling close_old_connections yourself at the end of your consumer's method (but likely not in disconnect, as django/daphne#152 will prevent that). I'll look at solving both issues later in the week.

  2. self-assigned this
    on Feb 6, 2018
  3. michaelhays commented on Feb 6, 2018

    @michaelhays

    close_old_connections didn't work for me as I used it. I tried it in a couple of places.

    End of the consumer method:

    # consumers.py
    class ChatbotConsumer(JsonWebsocketConsumer):
        def connect(self):
            self.accept()
    
        def receive_json(self, content):
            # create Chat in scope if one doesn't exist
            if 'chat' not in self.scope:
                chat = Chat.objects.create_chat(self.scope['user'])
                self.scope['chat'] = chat
    
            # process chatbot response, store messages, and send response to client
            response_data = some_func(content['message'])
            self.scope['chat'].add_message(content['message'])
            self.scope['chat'].add_message(response_data)
            self.send_json(response_data)
            close_old_connections()

    End of the model method:

    # models.py
    class Chat(models.Model):
        body = JSONField()
        ...
    
        def add_message(self, message):
            self.body.append(message)
            self.save()
            close_old_connections()

    Setting CONN_MAX_AGE to 0 has helped a bit, in that certain actions like reloading the page removes 2 or 3 of the "COMMIT" idle connections (but, only sometimes?), and occasionally, the idle connections are reaped. But I've yet to notice any rhyme or reason to it.

  4. andrewgodwin commented on Feb 7, 2018

    @andrewgodwin
    MemberAuthor

    Probably need the startup method connected as well. I'll look into it more tomorrow when I have time to work on Channels!

  5. andrewgodwin commented on Feb 7, 2018

    @andrewgodwin
    MemberAuthor

    OK, I have replicated this, and the temporary workaround is calling django.db.close_old_connections right after you do an ORM call, inside the same sync context (calling it anywhere else hides the connections due to thread safety).

    Working on a proper fix now.

  6. andrewgodwin commented on Feb 8, 2018

    @andrewgodwin
    MemberAuthor

    OK, this should be fixed in 6afd423 - any code inside of a SyncConsumer will work fine, and anything you're calling from an async context should use the new channels.db.database_sync_to_async (can either be called with a function or be used as a function/method decorator). You'll also need the latest release of asgiref (2.1.4) to make method decorators work correctly.

    If someone could confirm this fixes it for them, I can close this.

  7. michaelhays commented on Feb 8, 2018

    @michaelhays

    Confirmed to fix the issue for me!

  8. andrewgodwin commented on Feb 8, 2018

    @andrewgodwin
    MemberAuthor

    Great! I'll put this out in a release in the next day or two, depending on what else I land.

  9. LeonidIvanov commented on Mar 1, 2018

    @LeonidIvanov

    Hey, @andrewgodwin ! I'm steel having the same problem. And it's not only about consumer. I was following your tutorial (multichat). I have database_sync_to_async decorator that covers get_room_or_error in chat.utils. The main thing is that every page refresh (not only chat page) creates new database connection! Django + PostgreSQL + Daphne + Heroku

  10. andrewgodwin commented on Mar 1, 2018

    @andrewgodwin
    MemberAuthor

    If you can reduce it to a simple set of code that reliably reproduces the problem, using the latest versions of all of the repositories, then please open a new issue with that code snippet, and steps to replicate locally (I can't debug things that only happen in Heroku)

  11. LeonidIvanov commented on Mar 1, 2018

    @LeonidIvanov

    It's exact same issue as @michaelhays described at django/daphne#163. In my case there is no such issue in local but it is in Heroku.
    And I understand that you can't debug things that only happen in Heroku... But there's no support where I can text with that issue. You have more influence to report them about it as more people who updating from channels 1.0 to 2.0 will suffer this problem...

  12. LeonidIvanov commented on Mar 1, 2018

    @LeonidIvanov

    I just recreated everything on your clear multichat example here and deployed to heroku https://django-channels-2-test.herokuapp.com/ (user: demo, pass: demo) and get same issue. Refresh page 20 times and you'll get

    OperationalError at /
    FATAL:  too many connections for role "jdknihvnjyczlm"
    
  13. 31 remaining items

  14. sagardspeed2 commented on Mar 31, 2020

    @sagardspeed2

    @carltongibson No idea, all I know is that I made that single change and the problem went away.

    which change do you perform so problem went away ?

    I updated the runtime to python 3.8.1

    ok thanks, i also updated runtime to python 3.8.2 and done

  15. Hardeepsingh980 commented on Apr 12, 2020

    @Hardeepsingh980

    I was having this problem with channels and heroku postgres but it seems to have resolved itself when I changed my runtime from 3.6 to 3.8.1. I don't need to use close_old_connections()

    You now what? i was struggling from last two days on this stupid error. I am glad you fixed it. Thanks a lot. I am really happy

  16. SHxKM commented on Apr 12, 2020

    @SHxKM

    I'm happy to see @Paulcappaert's suggestion to switch runtimes helped some here, unfortunately for some of us that's impossible as we may be using other libraries that don't support 3.8 yet. I for one rely on Celery for background processing and cannot really update.

  17. andrewgodwin commented on Apr 12, 2020

    @andrewgodwin
    MemberAuthor

    For what it's worth, merely getting off of 3.6 may be enough - asyncio was a little underbaked in 3.6, and is much better in 3.7, and so most issues just need 3.7, not 3.8.

  18. SHxKM commented on Apr 13, 2020

    @SHxKM

    For what it's worth, merely getting off of 3.6 may be enough - asyncio was a little underbaked in 3.6, and is much better in 3.7, and so most issues just need 3.7, not 3.8.

    OK, just a heads up that from my experience - that's not true. I was (and still am) using Channels 1, and when I upgraded to Python 3.7.2 to enjoy a Celery feature, I also had to upgrade to Channels 2 (all sorts of dependency clashes). That's when I encountered this issue again, and reverted my whole setup so Channels 2 didn't kill my server. I am hoping to give this upgrade another chance soon enough, after multiple failed attempts.

    I'm hosted at Heroku; YMMV.

  19. andrewgodwin commented on Apr 13, 2020

    @andrewgodwin
    MemberAuthor

    Channels 2 versus Channels 1 is a very different conversation given that they use completely different asynchronous styles under the hood.

    Generally, this issue is caused by Django not identifying the connections with threads or coroutines that are already-dead. For Django itself this was fixed in the latest asgiref release, but Channels does not use the Local implementation in there so it doesn't get the same fixes. I also feel like Heroku does something to the Python environment based on a whole slew of Heroku-specific bugs that I used to get, but I have no time to verify that, unfortunately.

  20. SHxKM commented on Apr 13, 2020

    @SHxKM

    Channels 2 versus Channels 1 is a very different conversation given that they use completely different asynchronous styles under the hood.

    Generally, this issue is caused by Django not identifying the connections with threads or coroutines that are already-dead. For Django itself this was fixed in the latest asgiref release, but Channels does not use the Local implementation in there so it doesn't get the same fixes. I also feel like Heroku does something to the Python environment based on a whole slew of Heroku-specific bugs that I used to get, but I have no time to verify that, unfortunately.

    Let me clarify. Maybe I shouldn't have mentioned Channels 1 at all. What I was talking about is Channels 2 on Python 3.7.2, it's why I had to revert back to Channels 1, which is working perfectly fine.

  21. phamhm commented on Apr 23, 2020

    @phamhm

    I'm using Python 3.7.6 on heroku. My main server runs fine on with guinicorn. I observed this issue when I run daphne on my dev server.

    On my dev server, I incorporated Channels 2 + Websocket and daphne into my app and saw this issue whenever I refreshed my page. I changed my app to use AJAX instead and still see this issue. I only have one view function that return JSONresponse for the AJAX call. That AJAX view function was decorated with 'login_required' and a database update. So i did the following:

    Using AJAX + daphne:

    1. comment out the database update in my Ajax function => same issue with multiple ajax calls.
    2. comment out the login_require decorator on my ajax function=> no fatal on multiple ajax calls.

    Using websocket(Channels2) + daphne

    1. 20+ Websocket calls with no database update in WebSocketConsumer=> no fatal
    2. 20+ Websocket calls with database update in WebSocketConsumer => fatal
    3. Refresh the login_required view 20+ times: fatal.

    I looked at the heroku logs and found that in all instances, the fatal occurred when Django was doing session validation. I don't observe this behavior on my main server when I refresh the login_required view 20+ times. My main server uses guinicorn.

    File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/__init__.py", line 58, in _get_user_session_key
    return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
    File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 64, in __getitem__
    return self._session[key]
    

    I believe that Django session management is causing this issue when I use daphne. When either Django View or a WebSocket consummer requires validation, a connection is opened to the DATABASE but it never closes. This behavior is not apparent on the local machine because we don't have the limitation on database connection.

  22. carltongibson commented on Apr 23, 2020

    @carltongibson
    Member

    Hi. Are you able to reproduce on a laptop, or only on Heroku? (That still seems to be the issue...)

  23. phamhm commented on Apr 23, 2020

    @phamhm

    Hi. Are you able to reproduce on a laptop, or only on Heroku? (That still seems to be the issue...)

    I only observe this behavior on heroku. I don't know how to limit database connection on my laptop.

  24. Hardeepsingh980 commented on May 2, 2020

    @Hardeepsingh980

    Hi. Are you able to reproduce on a laptop, or only on Heroku? (That still seems to be the issue...)

    I only observe this behavior on heroku. I don't know how to limit database connection on my laptop.

    Hey i fixed this by changing my heroku runtime to python 3.8. This fixed the issue. So, it is worth trying.

  25. phamhm commented on May 4, 2020

    @phamhm

    Hi. Are you able to reproduce on a laptop, or only on Heroku? (That still seems to be the issue...)

    I only observe this behavior on heroku. I don't know how to limit database connection on my laptop.

    Hey i fixed this by changing my heroku runtime to python 3.8. This fixed the issue. So, it is worth trying.

    I switched to 3.8 and it has fixed my issue. That was very helpful, thank you.

  26. dctalbot commented on Jun 25, 2020

    @dctalbot

    So glad I found this thread. Just chiming in here - the following manifested this behavior:

    Heroku Postgres, Heroku Redis
    Python 3.7.7
    Django 3.0.3
    
    channels==2.4.0
    channels-redis==2.4.2
    daphne==2.5.0
    

    Dropping conn_max_age from the dj_database_url call solves my immediate issue, but this just defaults it to 0 such that connections are never reused.

    I haven't tried upgrading Python yet, but I should do that and report back.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions