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:
- Load the last 50 messages:
orderByChild("timestamp").limitToLast(50). - Remember the
timestampof the oldest message in the set. - Live subscription for new messages after the current moment:
startAt(currentTimestamp). - 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.







