Erik Hellberg Erik Hellberg - 1 month ago 11
Android Question

How should I handle this situation in FireBase where two users go for same Database key

I´m saving items called

Street
using the FireBase
push
and get a list of
Street
items with auto generated ids right. Lets say each
Street
have a node like
"path" : "unique value"
. Let´s say two users are about to insert a new
Street
that has the same
"path" : "unique value"
.

What is an appropriate way to eliminate this from happening? It´s like a web-shop where user puts an item in the basket, and the system behind now have to reserve this item until user buy it.

Should I create a separate FireBase root like "reserved_streets" and let user add his reserved
Street
along with user.id until he buy it? Maybe have a Servlet instance running removing entries that are 10 min old.

The
Street
list can be very big, maybe 100 millions in rar cases

Answer

The typical way to prevent duplicate values in the Firebase Database is to convert those values into keys.

So if you current model is (next time, please share such a minimal snippet in your question please):

streets: {
  "-K1234567": {
    path: "unique path"
  },
  "-K1234568": {
    path: "unique path 2"
  }
}

You would add an additional structure (or change the existing structure) that uses the paths as keys:

pathsToStreets: {
  "unique path": "-K1234567",
  "unique path 2": "-K1234568"
}

With this structure there is guaranteed to be only one street for a path and you can use security rules that the path can't be overwritten.