Forums

time.sleep() for Django-based chat app.

Hello,

I'm making a Django-based chat app, and I'm trying to make a sort of long polling. Do you think it would be a good idea (in terms of efficiency) to use the time.sleep() method when server receives a request? My plan is to do something like this, in order to minimize the number of requests:

        for _ in range(5):
            messages = Message.objects.new_messages()
            if messages.count() > 0:
                return JsonResponse({
                    "messages": messages,
                })
            else:
                time.sleep(5)

        return JsonResponse({
            "messages": [],
        })

I'm worried this could freeze the whole app, especially when several people will be using it.

Yes, that would definitely freeze the whole app in a free account -- with paid accounts, it might not freeze things, but it would definitely make things worse.

The way websites work on PythonAnywhere is that new requests come in to a queue, and then your worker processes pull requests off the queue, process them, and return the response, then move on to the next item in the queue. Free accounts just have one worker process, so if you sleep inside that process it will block and not move on to the next item until the sleep is complete. Paid accounts can have multiple processes (the exact number depends on the account settings), so there could be other processes handling requests while one slept -- but, of course, if all of the worker processes were sleeping because they were all handling this view, then things would still lock up.

If your goal is to slow things down so that people accessing the site don't "hammer" it with excessive requests, I'd suggest doing two things:

  • Code your front-end so that it doesn't make too many requests -- that is, put the sleep there.
  • Use some kind of rate-limiting so that people who somehow bypass the front-end (maybe by hacking the JS in the web developer console) can't cause problems. We use django-ratelimit -- it's worked pretty well for us.

Thank you very much for your response, it has been very useful. I will definitely take your suggestions.