10 Powerful Reasons to Use Firebase as Your Mobile App Backend in 2025

2.76K 0 0 0 0

📘 Chapter 3: Working with Firebase Realtime Database and Firestore

🔍 Overview

Every app needs a place to store and sync data, and Firebase offers two powerful NoSQL cloud database options—Realtime Database and Cloud Firestore. Both provide flexible, scalable data solutions with seamless integration into mobile and web apps. This chapter compares the two, demonstrates how to use them, and helps you decide which to choose for your project.


🧠 Key Concepts

  • Firebase Realtime Database stores data as a single large JSON tree and provides low-latency synchronization.
  • Cloud Firestore organizes data into collections and documents, offering more powerful querying and structure.

🔁 Realtime Database vs. Firestore: Comparison Table

Feature

Realtime Database

Cloud Firestore

Data Structure

JSON tree

Collections & documents

Querying

Limited

Advanced filtering & compound queries

Offline Support

Yes (basic)

Yes (more advanced)

Scaling

Limited (shards needed for large data)

Scales automatically

Pricing Model

Based on bandwidth & data

Based on reads, writes & storage

Real-Time Sync

Excellent

Excellent

Region Replication

No

Yes (multi-region support)

Best Use Case

Chat, live tracking, small apps

Complex apps, data filtering, analytics


🔧 Setting Up Firebase Database Services

🔹 Step 1: Enable the Database in Firebase Console

  • Go to Firebase Console > Database
  • Choose either Realtime Database or Firestore
  • Set rules (test or production)

🔗 Firebase SDK Setup (Java for Android)

groovy

 

dependencies {

    implementation 'com.google.firebase:firebase-database:20.3.0' // Realtime DB

    implementation 'com.google.firebase:firebase-firestore:24.7.0' // Firestore

}


📘 Using Firebase Realtime Database

🔹 Saving Data

java

 

DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("users");

 

User user = new User("Alice", "alice@example.com");

dbRef.push().setValue(user);

🔹 Reading Data

java

 

dbRef.addValueEventListener(new ValueEventListener() {

    @Override

    public void onDataChange(DataSnapshot snapshot) {

        for (DataSnapshot userSnapshot : snapshot.getChildren()) {

            User user = userSnapshot.getValue(User.class);

        }

    }

 

    @Override

    public void onCancelled(DatabaseError error) {

        Log.w("FirebaseDB", "loadPost:onCancelled", error.toException());

    }

});

🔹 Updating Data

java

 

dbRef.child("userId123").child("email").setValue("newemail@example.com");


🔹 Realtime DB Use Case: Chat Application

JSON Tree Example:

json

 

"chats": {

  "room1": {

    "message1": {

      "sender": "John",

      "text": "Hello"

    },

    "message2": {

      "sender": "Jane",

      "text": "Hi!"

    }

  }

}


🔥 Using Cloud Firestore

🔹 Creating and Writing to a Document

java

 

FirebaseFirestore db = FirebaseFirestore.getInstance();

 

Map<String, Object> user = new HashMap<>();

user.put("name", "Bob");

user.put("email", "bob@example.com");

 

db.collection("users").add(user);


🔹 Reading Documents

java

 

db.collection("users").get()

  .addOnSuccessListener(querySnapshot -> {

      for (DocumentSnapshot doc : querySnapshot) {

          Log.d("Firestore", doc.getId() + " => " + doc.getData());

      }

  });


🔹 Updating a Document

java

 

db.collection("users").document("userId123")

  .update("email", "updated@example.com");


🔹 Firestore Use Case: E-Commerce Product Catalog

Firestore Structure Example:

bash

 

users/

  userId123/

    name: "Sara"

    email: "sara@example.com"

products/

  prod001/

    title: "Shoes"

    price: 49.99

orders/

  order789/

    userId: "userId123"

    items: ["prod001", "prod002"]


📊 Querying in Firestore

java

 

db.collection("products")

  .whereEqualTo("category", "shoes")

  .orderBy("price", Query.Direction.ASCENDING)

  .get()

  .addOnSuccessListener(querySnapshot -> {

      for (DocumentSnapshot doc : querySnapshot) {

          Log.d("Product", doc.getId() + " => " + doc.getData());

      }

  });


🔒 Securing Your Data: Firebase Rules

🔹 Realtime DB Rule

json

 

{

  "rules": {

    ".read": "auth != null",

    ".write": "auth != null"

  }

}

🔹 Firestore Rule

js

 

rules_version = '2';

service cloud.firestore {

  match /databases/{database}/documents {

    match /users/{userId} {

      allow read, write: if request.auth.uid == userId;

    }

  }

}


🌐 Offline Support

Both databases support offline capabilities:

  • Realtime Database caches data and syncs when reconnected.
  • Firestore provides better offline querying and local persistence.

java

 

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

Firestore enables it automatically on mobile.


🧩 Choosing Between Realtime DB and Firestore

App Needs

Best Option

Simple JSON storage

Realtime Database

Structured, relational-style data

Firestore

Advanced queries

Firestore

Heavy real-time sync for chat

Realtime Database

Offline-first apps

Firestore

Global-scale production

Firestore


Best Practices

  • Use Firestore for most new apps due to scalability and querying
  • Avoid nesting deeply in Realtime DB (limits query performance)
  • Apply security rules early in development
  • Normalize data in Firestore for easier querying
  • Use pagination and batch writes to optimize performance
  • Monitor reads/writes to control cost (Firestore charges per operation)

🧪 Testing and Debugging

  • Use Firebase Emulator Suite to test database rules and operations locally.
  • Use Firebase Console > Firestore / Realtime DB for real-time monitoring.
  • Apply addOnFailureListener() for every operation to handle errors gracefully.

📌 Conclusion

Both Firebase Realtime Database and Firestore offer real-time, cloud-hosted NoSQL solutions that eliminate the need for traditional backend setup. Firestore is the newer, more structured option with powerful querying and scalability, while Realtime DB remains useful for ultra-fast syncing in simpler apps.

In the next chapter, we’ll explore Firebase Cloud Functions and how to automate server-side tasks and event-driven logic.

Back

FAQs


1. What is Firebase, and how does it help mobile app developers?

Firebase is a Backend-as-a-Service (BaaS) platform by Google that offers a suite of tools like real-time databases, authentication, cloud storage, hosting, and analytics—enabling developers to build fully functional mobile apps without managing servers.

2. Is Firebase suitable for both Android and iOS apps?

Yes, Firebase supports Android, iOS, and even cross-platform frameworks like Flutter and React Native, offering SDKs and libraries that make integration smooth across platforms.

3. What’s the difference between Firebase Realtime Database and Firestore?

Realtime Database is a low-latency JSON-based database ideal for syncing data in real-time. Firestore, on the other hand, is more scalable, supports structured collections/documents, and offers more advanced querying and offline support.

4. Can Firebase handle user authentication securely?

Absolutely. Firebase Authentication supports email/password, phone number, and social logins with built-in security, encrypted data transmission, and session management.

5. Does Firebase offer backend logic processing like a traditional server?

Yes, through Firebase Cloud Functions, you can write server-side logic (like sending notifications, validating data, or processing payments) that runs in response to events—all without managing physical servers.

6. Is Firebase free to use?

Firebase offers a free-tier plan (Spark Plan) which includes many core features. As your usage grows, you can switch to the Blaze Plan (pay-as-you-go), which scales with your app's needs.

7. How scalable is Firebase for large-scale apps?

Firebase is built on Google Cloud infrastructure, making it highly scalable. Cloud Firestore and Cloud Functions scale automatically based on usage, ideal for apps with growing user bases.

8. Can I use Firebase just for some features and not as the entire backend?

Yes, Firebase is modular. You can use only the features you need—like Authentication or Cloud Messaging—without being forced to use the whole stack.