title: MongoDB: How to design twitter-style followers/following relation model in MongoDB?
body: <p>I'm developing an android mobile app which potentially have a lot of users (let's say about 1 million). These user can follow other users (like Twitter). The app syncs the user data via a remote REST backend. The user data itself is persisted in a document oriented database (in my case it's a MongoDB).</p>
  
  <p>Currently I ask myself about the best way to design the user model including its follower and following relations. First thought was to embed the relations within the user document.</p>
  
  <p>Example user document:</p>
  
  <pre><code>{
  "_id":"50fd6bb530043e3c569af288", 
  "name":"Marsha Garcia", 
  "follower"["50fd6bb530043e3c569af287","50fd6bb530043e3c569af289","50fd6bb530043e3c569af28c"],
  "following":["70fd6bb530043e3c569af289","10fd6bb530043e3c569af222","89fd6bb530043e3c569af45o"]
  }
  </code></pre>
  
  <p>The positive thing is that the follow/following relations are already joined with the user. However let's say a user follows about 100.000 or more other users. Then the document size will become very large. If I load this user object via REST service in my mobile app it could take a while. Furthermore in worst case the user document could exceed the MongoDb 16MB document limit.</p>
  
  <p>Therefore my second thought was to model the follower and following relations in a more classic way: An extra document containing the following relations of each user. </p>
  
  <p>Example 'user relation' document:</p>
  
  <pre><code>{
      "_id": 50fe65828de290c0a8a8ea2d"
      "uid": "50fd6bb530043e3c569af288",
      "rel_uid": "50fe65828de290c0a8a8e9a6",
      "type": "FOLLOWING"
  }
  </code></pre>
  
  <p>The positive thing is that the size of each user document will remain constant. The downside is that with lots of users and following relations I could easily get millions of entries in my MongoDB 'user relations' collection. Of course I'm going to set an index on the fields but I'm not quite sure whether this solution will scale very well regarding the use case of an app user asking for his/hers current followers.</p>
  
  <p>I would appreciate any thoughts, experiences about my modeling problem. Perhaps anyone even has a better solution approach.</p>
  
  <p>Thx a lot in advance.</p>