Modeling social network connection with RavenDB

Est. reading time: 3 min
RavenDB News

I got an interesting scenario that I thought would make for a good blog post. Given a social network similar to Twitter, how would you deal with the social aspect of it? In other words, how would you model the following relationship between users.

In pretty much all social media platforms, the following relationship is unidirectional. I’m following The Wheel Of Time, but it isn’t following me back. That is a very important aspect for modeling as well as the maximum number of accounts that you can follow. Both Facebook and Twitter will limit the number of accounts that you can follow to 5,000. All of those gives us a pretty good operating environment. To model the following relationship in a social network I’ll use the following option:

In other words, the recommended approach is to store all the accounts that a user follows in a single document. The fact that an account is limited to following a maximum of 5,000 accounts gives us a hard limit on the size of that document (and most accounts will follow far less).

Note that the code above is also pretty much the simplest possible option for how to record the following relationship. In this case, the simplest and best option are one and the same.

Let’s consider what operations we need to apply on the following relationship:

  • Find all the followers of a particular account. from Fellowships where Following[].UserId = $userId
  • Find the number of followers per account: from Fellowships group by Following[].UserId  where Following[].UserId = $userId select count(), Following[].UserId

Finding all the users that a particular user is following is simply loading the document and looking at the Following property, so I’m skipping that.

The key here is that this is going to be simple to build and use, scalable because different users can start following accounts independently from one another and doesn’t require to do anything fancy.

Woah, already finished? 🤯

If you found the article interesting, don’t miss a chance to try our database solution – totally for free!

Try now try now arrow icon