0

I am looking to implement a 'like' system, and I know because I am under the restriction of a single update per second that I should used a distributed counter to do so. https://firebase.google.com/docs/firestore/solutions/counters

The concept is relatively simple, essentially you just have a bunch of segments (shards) and you tally them all up. What I don't get however, is when you go to increment a counter:

function incrementCounter(db, ref, num_shards) {
    // Select a shard of the counter at random
    const shard_id = Math.floor(Math.random() * num_shards).toString();
    const shard_ref = ref.collection('shards').doc(shard_id);

    // Update count in a transaction
    return db.runTransaction(t => {
        return t.get(shard_ref).then(doc => {
            const new_count = doc.data().count + 1;
            t.update(shard_ref, { count: new_count });
        });
    });
}

This seems to grab a shard to increment at random. I guess the idea is even if you accidentally grab the same two shards it won't have a problem since its being incremented in a transaction, but at that point whats the point of just having one field? I guess its so you can have a faster update and you play a little bit of a probability game. it just feels a little hacky.

jdoej
  • 723
  • 1
  • 6
  • 10
  • It seems like you're asking two different questions here. Please limit yourself to one question/problem per issue that you create here on SO. – Doug Stevenson Dec 29 '17 at 00:05
  • @DougStevenson not really and if I was the questions tied hand in hand, but I just released an updated question – jdoej Dec 29 '17 at 01:30
  • So, your question is "what's the point of just having one field?". Do you have an alternative idea? What's the confusion exactly? – Doug Stevenson Dec 29 '17 at 17:20
  • ah, I guess it didn't word it as well as I thought! sorry. My question is with these shards, don't you run the risk of oh selecting the same shard and not being able to update using the randomizer? I guess the idea is you lower your chances right? if two people are both adding to a field via a transaction.. it might be slower but the correct value would be there eventually – jdoej Dec 29 '17 at 20:23
  • It sounds like you get the idea. – Doug Stevenson Dec 29 '17 at 20:27

0 Answers0