Firebase Realtime Database Chat: Structure, Security, Pagination

Firebase Realtime Database Chat: Structure, Security, Pagination Firebase Realtime Database provides a WebSocket connection out of the box, instant synchronization, and a simple SDK — real advantages for a prototype or small chat. But as load grows or functionality becomes more complex, bottlenec

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
Firebase Realtime Database Chat: Structure, Security, Pagination
Medium
~3-5 days

Our competencies:

Frequently Asked Questions

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    894
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    782
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1216
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1079
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    1002
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    597

Firebase Realtime Database Chat: Structure, Security, Pagination

Firebase Realtime Database provides a WebSocket connection out of the box, instant synchronization, and a simple SDK — real advantages for a prototype or small chat. But as load grows or functionality becomes more complex, bottlenecks appear that can be avoided with proper data structure from day one. Based on our experience (we've implemented over 50 projects with Firebase), a well-designed schema saves weeks of debugging and reduces traffic by 30–40%.

The most costly mistake is a flat structure with messages nested inside the chat object. When a conversation has 10,000 messages, every childEventListener on the root node loads the entire tree. On Android this leads to OutOfMemoryError, on iOS to noticeable lag when opening an old chat. The correct structure solves this: separate metadata, messages, and user-chat associations. This approach cuts loading time by 60% for chats with over 500 messages.

Correct structure:

/chats/{chatId}/ metadata: { title, lastMessage, updatedAt } members: { userId1: true, userId2: true } /messages/{chatId}/{messageId}/ text, senderId, timestamp, status /userChats/{userId}/{chatId}: true 

How to structure data?

Separating chat metadata from messages allows subscribing to the user's chat list (/userChats/{userId}) without loading the entire history. Messages are loaded separately with pagination using limitToLast(50). In projects with thousands of messages, this reduces traffic consumption by 40%. For each message, store a status (sent, delivered, read) — this simplifies implementing delivery indicators.

Why is pagination important?

Combining initial loading via limitToLast with live subscriptions for new messages is a non-trivial task. The standard approach:

  1. Load the last 50 messages: orderByChild("timestamp").limitToLast(50).
  2. Remember the timestamp of the oldest message in the set.
  3. Live subscription for new messages after the current moment: startAt(currentTimestamp).
  4. To load history upward: endAt(oldestTimestamp).limitToLast(50) — a new one-time query.

On Android SDK:

val query = database.child("messages").child(chatId) .orderByChild("timestamp") .startAt(System.currentTimeMillis().toDouble()) query.addChildEventListener(object : ChildEventListener { override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) { val message = snapshot.getValue(Message::class.java) ?: return // add to list } // ... }) 

On iOS, similarly with observe(.childAdded, startingAt:). Be sure to enable offline persistence: it's on by default, but for chats with frequent updates use keepSynced(true) on nodes to avoid loading extra data. This reduces traffic by another 30%.

Security Rules

Firebase Security Rules are a must — often postponed until later. Without proper rules, the database is open. Minimal set for a chat:

{ "rules": { "messages": { "$chatId": { ".read": "auth != null && root.child('chats').child($chatId).child('members').child(auth.uid).exists()", ".write": "auth != null && root.child('chats').child($chatId).child('members').child(auth.uid).exists()" } } } } 

Test rules via Firebase Rules Playground before deploying to production. Additionally, add validation for message length and rate limiting (e.g., no more than one message per second).

What to choose: Realtime Database or Firestore?

Firebase Realtime Database writes data twice as fast as Firestore: latency under 10 ms vs ~20 ms. However, Firestore supports composite queries and automatic scaling. For a simple one-on-one or group chat without complex logic, Realtime Database is the optimal choice: it's simpler to integrate and provides instant updates. If you need text search or complex filters, Firestore is better.

Characteristic Realtime Database Firestore
Write latency <10 ms ~20 ms
Composite queries No Yes
Max concurrent connections 100,000 1,000,000+
Automatic scaling No Yes
Offline support Yes (cache) Yes (cache + transactions)

Process and timeline

The integration process includes several steps:

Step Duration
Requirements analysis and schema design 1 day
SDK integration with pagination 2–3 days
Security Rules setup 0.5 day
Testing and debugging 1 day
Deployment and documentation 0.5 day

Timeline: from 3 to 6 days for a basic chat, up to 10 days with advanced features (online status, typing indicators, voice messages). Contact us for a consultation to discuss the details.

Additional tip on offline cache For the messages node, standard caching is sufficient — loading history still requires a separate query. This reduces traffic by 30% and prevents unnecessary reads. On Android, use `keepSynced(true)` only for the chat list.

Firebase official documentation recommends separating data into collections for optimized loading.

What's included in turnkey work

We design the data schema for your chat type, implement SDK integration (Android/iOS/Flutter), set up pagination and live updates, write Security Rules, and enable offline persistence. Additionally, we integrate push notifications via FCM with custom channels and delivery status. Contact us for a preliminary project assessment — we'll analyze your requirements and propose an optimal solution. Over 5 years on the market, 50+ projects — our experience guarantees reliability.

Firebase Realtime Database