aliz_bazar
aliz_bazar

Reputation: 292

Strong consistency with Firebase real-time database

Does Firebase real-time database offer strong consistency?

We are using Firebase real-time database in some cases as a queue:

Scenario 1

  1. Mobile client writes item document to /items
  2. Server A (Cloud Function) listens to /items and calls Server B via POST /processItem/:itemID
  3. Server B fetches items/:item and starts processing
  4. Once processed, Server B writes item.processedAt = <timestamp>

Scenario 1 logic seems to work fine, however, we started wondering if Firebase actually offers strong consistency and whether we can be sure that when Server B fetches items/:itemID from Firebase, the document certainly exists.

Scenario 2

  1. Server A writes item document to /items and waits for the .set() operation to go through.
  2. Server A calls Server B via POST /processItem/:itemID
  3. Server B fetches items/:itemID and starts processing
  4. Once processed, Server B writes item.processedAt = <timestamp>

This potentially is even more "risky" as Server A may call Server B potentially even before child_added event would have fired.

Are both of these scenarios safe?

Upvotes: 1

Views: 1040

Answers (2)

ryanpbrewster
ryanpbrewster

Reputation: 56

Bhavin Panara is correct. Both scenarios are "safe" in the way you've described. Once a write is acknowledged, the Realtime Database guarantees that any subsequent reads will see the result of the acknowledged write. This is also true of a Cloud Function being triggered by a write.

As you've noted, listeners are updated asynchronously, so a client listening to a location may not be updated about a write for some time.

Note that it is still possible to have race conditions even with a strongly consistent database. Consider the following scenario:

Scenario 3

  • Mobile client creates data at /items/item1
  • Server A (Cloud Function) listens to /items and calls Server B via POST /processItem/:itemID
  • Mobile client deletes data at /items/item1
  • Server B receives request from Server A and fetches /items/item1, but the item has been deleted.

In these kinds of scenarios it may be helpful to fall back on transactions.

Upvotes: 2

Bhavin Panara
Bhavin Panara

Reputation: 448

IMHO both of these scenarios can be safe.

Scenario 1 is completely safe. Because cloud function is invoked only when firebase has written the data completely. So, you are definitely safe in scenario 1.

For scenario 2. You can go this way.

  • Server A writes item document to /items
  • Server A waits for the callback of completion from firebase.
  • Server A calls Server B via POST /processItem/:itemID
  • Server B fetches items/:itemID and starts processing
  • Once processed, Server B writes item.processedAt = <timestamp>

Upvotes: 2

Related Questions