Ratchet multiple servers
Asked Answered
D

1

6

I am using Ratchet (http://socketo.me/) for websockets in my PHP application. I have multiple virtual machines running the application and each of these machines also host the websocket service. Requests are passed to one of these virtual machines through HAProxy. Also currently the user uses the websocket service on the same node it connects for the application.

Now I have a problem with the websocket servers discussing with each other. For example:

  • user1 connects to node1 and user2 connects to node2
  • User1 sends websocket message through websocket to user2
  • User2 never gets this message because he is connected to another node

What are good practices doing this kind of messaging? I have some ideas but not sure what way to go:

  1. Each client connects to each websocket node.
  2. Servers publish the messages to all other nodes as well
  3. Use database to synchronize the messages between nodes

Both 1st and 2nd options are not very scalable if new nodes are attached to the cloud. 3rd option will cause some lag because it is necessary to check if messages from other nodes are in database in loop.

Are there any other options to handle situations like this? Thanks for the answers!

Divaricate answered 12/2, 2015 at 6:12 Comment(0)
A
0

Just a few notes to possibly point people in one possible direction:

  • You can use Redis as a very fast database that implements lists - rpush, llen, lrange. This will handle the synchronization between servers in a surprisingly efficient way.
  • Don't send messages in the onMessage handler directly, but rather put the messages straight into Redis. This way the handler is super fast.
  • Instead of letting Ratchet create its own loop, create one by hand and add a periodic timer on it that polls Redis and sends new messages to clients.
Ambit answered 19/12, 2017 at 23:8 Comment(1)
I would like to know how would you store a connection object into Redis?Ardeha

© 2022 - 2024 — McMap. All rights reserved.