Chad Van De Hey
Chad Van De Hey

Reputation: 2911

Websockets on production chat apps:

As I am beginning to work my way through web-sockets using Python (Django Channels in this case), I am beginning to wonder how companies scale chat applications.

Take this specific problem: User A has a list of "group messages" that they are involved in. User A is capable of receiving notifications from each of the groups. Lets suppose User A has 5 different groups he would like real time notifications for.

  1. Does User A have 5 separate web socket connections? This is easiest, but the bulkiest and surely wont scale (what if we had 20 chats per user). It is quite easy to make a Django Channels "Group" that listens and sends notifications to one specific group of people.

  2. Does User A instead have 1 web socket connection taking all notifications from many different locations? If so, what is User A subscribing to on the backend? In Django Channels, a websocket is made when users subscribe to a "Group". If we wanted one user per "Group', this would seem counter intuitive. In this case, User A is subscribing to their own personal "Group" and other backend services are delivering messages to that specific "Group" based on other logic that is implemented when a message is received from any user using the service.

This is very verbose and text heavy, but it diagrams an interesting problem that has scaled for other companies in the past. I appreciate any information or insight!

(this is a list of the problems that I thought were basically the same (ignoring language and library use)) 1. Websocket multiple Channels vs. One Channel + Server Side handling [GroupChat]

Upvotes: 1

Views: 774

Answers (1)

Farrukh
Farrukh

Reputation: 98

first create a profile model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name=_("user"))
    channel = models.CharField(unique=True, max_length=255, blank=True, null=True, verbose_name=_("channel")) # channel for notify user

then create a message model:

class Message(models.Model):
    to_user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user"))
    from_user = models.ForeignKey(User)
    text = models.TextField(blank=True, null=True)

then use Django signals for sending notify:

@receiver(post_save, sender=Message)
def send_notify(instance, created, **kwargs):
    if created:
        Group('chat-{}'.format(instance.to_user.profile.channel)).send({'text': {'message': 'you have a new message'}})

sorry for my english : ))

Upvotes: 1

Related Questions