0
votes

I have two firebase triggers increaseCount and decreaseCount for onCreate and onDelete events respectively.

Scenario:

When a user likes something on the client a new path is created in the firebase database and the onCreate tigger is tiggered. The count is then incremented like I would expect.

When a user 'unlikes' something on the client a path is removed in the firebase database and the onDelete trigger is fired. The count is then decremented.

Issue:

When the user quickly likes something and then unlikes something, both the requests to create a new path and delete an existing path are sent to firebase at pretty much the same time.

Sometimes the onDelete trigger fires before the onCreate tigger.

I'm really looking for some insight into best practices here or anyones past experiences with a similar situation.

Here's a watered down version of my onCreate and onDelete functions

exports.increaseCount = functions.database.instance(dbInstance).ref('/path/to/existingPath')
.onCreate((snap, context) => {
 ref.transaction(function(count) {
    return (count || 0) + 1;
 }
});

exports.decreaseCount = functions.database.instance(dbInstance).ref('/path/to/newPath').onDelete((change, context) => {
dbRef.transaction(function(count) {
    if(count && (count > 0)){    
        var newCount = count - 1;
        return newCount;
    } else {
        return 0;
    }
 }
});
1

1 Answers

2
votes

This is not really a race condition. You should expect that Cloud Functions triggers may possibly fire out of order. This because different functions may be running on different server instances, and it wouldn't be scalable for all of them to somehow share a sense of event ordering. This means you may have to do some additional checking in your transactions to make sure that your database is in a state that's actionable for the current function invocation.