tango-1
tango-1

Reputation: 350

Avoid race conditions in Firebase Android

I am developing an Android application that provides users reserving restaurants and I am using a real-time database in order to store the necessary information, such as the number of empty tables in the restaurant, and the problematic part it is.

Let's say, we have XYZ restaurant that has just one empty table, and 2 users clicked the reserve button on the android app at the same time and try to reserve the table. If race condition occurs, they will reserve the same table, so the empty table counter will be -1, if both of them get this table.

My question is, how to avoid race conditions in Firebase using real-time database. I have searched about it and I saw that I should use Firebase transactions, with Cloud Firestore. But I am using the Realtime Database.

Is there a way to implement mutex or a kind of mechanism that locks the shared data between clients?

Upvotes: 1

Views: 426

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138969

Regarding:

My question is, how to avoid race conditions in Firebase using Realtime database.

Simply by using transactions:

When working with data that could be corrupted by concurrent modifications, such as incremental counters, you can use a transaction operation.

I see you also added a tag with Cloud Firestore, a database which also has this transaction mechanism.

And regarding:

Let's say, we have XYZ restaurant that has just one empty table, and 2 users clicked the reserve button on the android app at the same time and try to reserve the table. If race condition occurs, they will reserve the same table, so the empty table counter will be -1, if both of them get this table.

That's not gonna happen. If the first user makes the reservation, the second one won't be able to do it.

Upvotes: 3

Related Questions