0

First i'd like to add that while this is a Firestore question, im open to hear suggestions about integrating an additional Google service.

The System

I have a chat feature in my application. Since there could be a very decent scale, I decided to have a limit to a chat group. Chat groups are not created by users and should be created automatically by using some sort of an incrementing index (e.g: room_1, room_2, ...., room_n).

The limit on each chat group is 100 users at most. So if I have 100k users online, I'd expect to have 1k groups (aka n=1000).

The Issues

  1. How can I distribute users, upon signing in, to chat groups? (Lets say the strategy is to fill current rooms first, hence the 'bucketing' in the title)
  2. Since users can close the app without pressing "quit" or something, I need the system to know to adjust
Ori Refael
  • 2,888
  • 3
  • 37
  • 68

1 Answers1

0

You can add a counter to the room document and increment/decrement it using by FieldValue.increment, here is an usage example in Javascript:

//when a user enter the room
db.collection('chat_rooms').doc('room_1').update({
    userCount: firebase.firestore.FieldValue.increment(1)
});
//when a user quits the room
db.collection('chat_rooms').doc('room_1').update({
    userCount: firebase.firestore.FieldValue.increment(-1)
});

Since FieldValue.increment() gets the current value of the counter you don't need to worry about racing conditions, which is good given that you expect to have a huge number of user so this will be constantly updated.

You can wrap this arround a check of the room counter and if the room is over the limit of users you set for rooms a new room can start being filled.

For your second question a bit more information is required, but assuming you are using android you can use the onAppBackgrounded function in the example provided in this community answer to call the update that decrements the counter in the chat room document if the app is backgrounded or closed by the user, as part of the "forcing" him out of the room.

Ralemos
  • 5,571
  • 2
  • 9
  • 18