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.