skip to Main Content

I have a list of users which might increment to thousands of records.

I have 2 instances of retrieving specific user data.

The 1st one is retrieving it via the userId(key) as the diagram below:

enter image description here

The code for that is:

 firebaseDatabase.getReference("users")
         .child(userId)
         .get()
         ...

The 2nd one is saving the userId as a field-value, so that I can index it in the rules for better perfomance incase there are too many users. See the picture below

enter image description here

and the code for that would be:

firebaseDatabase.getReference("users")
        .orderByChild("userId")
        .equalTo(theSpecificUserId)
        .get()
        ...

I haven’t used the 2nd version yet, but I created a function that added about over 100k users & I got the error – Firebase -Out of Memory exception causing the app to crash.

Which is the better one for performance & how do you handle scaling of your database while your app is in production?

2

Answers


  1. If you can create a reference that points to a particular user node, then do it. Do not perform a query! Seeing your example, it’s quite simple to create a database reference object that points to the user node, since the key of the node is the UID.

    A query is helpful only when you need to filter and/or order elements in the database. All the operations are considered limitations. If a node has "thousands of records", as you say, will not create problems. But trying to access a node that contains millions, might create. However, accessing an individual user will never create any problems.

    Querying the "users" node only for a subset of its children always requires that the Realtime Database consider each of those thousands of users. If you request a single user out of 1000 users, you’re basically asking Firebase to consider 999 users that you’re definitely not interested in reading them. If you only point to a single user, the other 999 users are not considered in any way.

    If you’re new to NoSQL databases, please note that it’s best to model the data in a way that fits your app use case. That being said, if you need to display, for example, the latest 10 users that joined your app, then store the UID of those latest 10 users in a separate node. Why? Because we are always structuring the database according to the queries that we want to perform.

    Login or Signup to reply.
  2. Add the userId field that you are using for the query to the Realtime Database rules.

    For example

    {
      "rules": {
        ".read": "auth.uid != null",
        ".write": "auth.uid != null",
        "v1": {
                "users": {
                    ".indexOn": "userId"
                }   
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search