0

How can we implement a Facebook like status message system in mongodb (using mongoose), where whenever any given user posts his status it gets broadcasted on all his friends timeline.

It doesn't have to be real-time, there will be a refresh button to get the latest statuses.

here is what I have come up with:

Plan A:

status(collection)
    id, user_id(reference), status_msg

Benefit: faster write speed

Plan B:

status(collection)
    id, user_id(reference), status_msg, friends_list[sub-document]

Benefit: faster read speed

With plan A, I'll have to loop through all the friends a user has in his friends list and then fetch all the status. I'll have to do this every time (page refresh/ new login) for every single friend.

With Plan B, I'll only have to fetch the statuses which has the current user in the friends_list.

I would like to know your opinion and suggestion on this ?

Is there any better way of approaching this problem ?

I would also like to know how I can use rabbitMQ here to increase the efficiency and lower the unnecessary db i/o .

CBroe
  • 91,630
  • 14
  • 92
  • 150
ArrC
  • 203
  • 1
  • 3
  • 11

1 Answers1

0

Assuming that each user will likely have several friends, and these friends refresh their timeline several times a day, you can assume that reading will happen much more frequently than writing. That means from a pure performance standpoint you would optimize for read-access, not for write-access, and store the receivers with the message.

However, keep the semantics in mind. What if the friend-list of the author changes after they posted a status message?

  • Do you want the message to disappear from the timelines of any ex-friends?
  • Do you want the message to appear in the timeline of any new friends they make?

When the answers to these questions are yes, you should rather determine the receivers on read than on write.

There is also a third option which might be worth considering: Do not handle messages by sender, handle them by receiver. When someone posts a message, create an individual copy of the message for each of their friends and save them as separate documents. You can then get all messages for a user by querying your messages collection for messages where they are the receiver. The friend/unfriend operation would then need to check for any messages which need to be added/removed. The major drawback of this approach would be that users with a very high number of friends would create a very high write-load when posting something.

Philipp
  • 67,764
  • 9
  • 118
  • 153