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
timestamp of 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.
Firebase Realtime Database
How to Start Integrating API into a Mobile App?
The request goes out, the response doesn't come, timeout — 30 seconds. The user stares at the spinner. No network — mobile card in the subway. Or the network is there, but the server returns 200 with an HTML error page instead of JSON — and the app crashes on JSONDecoder.decode(). We see such cases on every second project. So integrating API into a mobile app is not just calling an endpoint, but designing a reliable network layer: error handling, caching, offline mode, certificate pinning. Order an audit of your current network layer — we will evaluate the project in 1 day. Our team guarantees a thorough analysis and provides a detailed roadmap.
Standard libraries like URLSession and OkHttp provide basic HTTP clients, but for production you need retries with exponential backoff, status code validation, typed deserialization, and network state monitoring. Without this, the app loses data and users. We have been doing mobile development for 5 years and implemented more than 30 projects with API integration on iOS, Android, and Flutter — from startups to enterprise solutions.
How to Choose a Protocol for API Integration?
| Protocol |
Response Size |
Parsing Speed |
Caching |
Suitable For |
| REST |
Large (fixed structure) |
Medium |
HTTP cache + local |
CRUD, typical screens |
| GraphQL |
Minimal (only needed fields) |
Medium (normalized cache) |
In-memory cache (Apollo) |
Complex UIs with different queries |
| gRPC |
Minimal (protobuf) |
High |
Stream-level |
High-load, real-time, IoT |
| WebSocket |
— (binary/text) |
— |
Manual |
Chats, quotes, synchronization |
REST remains the standard for most projects. But when a profile screen needs 5 fields out of 40, GraphQL eliminates over-fetching and reduces traffic by 30–60%. gRPC is justified for thousands of requests per minute (trading, IoT) — binary serialization is 3–5 times faster than JSON. WebSocket is the only choice for real-time without polling (messages, notifications).
Practical example: For a fintech app, we replaced REST (40 fields) with GraphQL — response size dropped from 12 KB to 2.5 KB, screen render time decreased by 70%. Traffic savings were significant. Our certified iOS and Android developers have deep experience with all these protocols — you can rely on proven solutions.
How to Ensure Reliable Connection and Offline-First?
Users lose network in the subway, elevator, tunnel. A mobile app must work without internet — at least in read-only mode. We implement the offline-first pattern:
- On screen open, first show data from the local cache (Core Data / Room).
- Simultaneously perform a network request, update UI after response.
- If network is unavailable — show cached data and a 'no connection' label.
- When network is restored, automatically synchronize changes.
For HTTP response caching we use URLCache (iOS) and OkHttp Cache (Android) with Cache-Control support. For structured data — SwiftData / Room. NWPathMonitor / ConnectivityManager.NetworkCallback monitor network state and trigger updates.
REST and Client Library Selection
Alamofire (iOS) — de facto standard for Swift projects. On top of URLSession it adds request chaining, response validation, automatic retry, certificate pinning via ServerTrustManager. AF.request() with .validate() returns an error for any status code outside 200–299. Without .validate(), Alamofire considers 404 and 500 as successful responses. With Swift Concurrency — async version via serializingDecodable.
Retrofit (Android) — annotation-based HTTP client on top of OkHttp. An interface with annotations compiles into implementation. @GET, @POST, @Path, @Query, @Body — declarative API description. OkHttp under the hood: connection pooling, transparent gzip, HTTP/2 multiplex. HttpLoggingInterceptor — logging in debug builds. Authenticator — automatic token refresh on 401.
Ktor (KMM/Flutter) — multiplatform HTTP client. On iOS it works via Darwin engine (URLSession), on Android — via OkHttp. Single code for both platforms with KMM architecture.
GraphQL: When REST Falls Short
REST returns a fixed structure. A profile screen needs name, avatar, email — the server sends 40 fields. Over-fetching. GraphQL solves this: the client requests exactly the needed fields. This is critical for mobile where traffic and parsing time are real constraints. Apollo iOS and Apollo Kotlin generate typed classes from schema: schema.graphql + query files → strict types at compile time. Subscriptions via WebSocket — real-time without polling. Limitation: GraphQL is harder to cache at the HTTP level. Apollo uses a normalized in-memory cache InMemoryNormalizedCache — requests with overlapping data update the cache without duplication.
WebSocket: Real-Time Without Extra Traffic
Polling (setInterval every 5 seconds) — battery and traffic waste. WebSocket is a persistent bidirectional connection. iOS: URLSessionWebSocketTask (native, iOS 13+). Android: OkHttp WebSocket. Mandatory reconnect handling: on onFailure — exponential backoff (1s → 2s → 4s → 8s → max 60s). Socket.IO is an overlay with automatic reconnect, but for new projects native WebSocket is preferable (fewer dependencies).
gRPC: For High-Load Services
gRPC with protobuf — binary serialization: smaller size, faster parsing. grpc-swift for iOS, grpc-kotlin for Android. The protobuf schema compiles to typed classes. Streaming (server-side, client-side, bidirectional) is a native feature. Application threshold: high request frequency (trading, IoT) or critical latency. For regular CRUD, REST is simpler to debug and monitor.
Certificate Pinning and Security
A corporate proxy can intercept HTTPS by substituting the certificate. Certificate pinning prevents this: the app accepts only a specific certificate or public key. Alamofire: ServerTrustManager with PinnedCertificatesTrustEvaluator. OkHttp: CertificatePinner with SHA-256 hash. Apple's App Transport Security documentation recommends pinning certificates for sensitive data. Operational complexity: on certificate rotation, older app versions stop working. Solution — pinning to the CA public key or support multiple pins with a grace period.
What Is Included in the Work
| Stage |
Duration |
Result |
| API and requirements analysis |
1–2 days |
Endpoint specification, protocol selection, caching schema |
| Network layer implementation |
3–5 days |
Client library, error handling, retry, pinning |
| Offline mode and caching |
2–3 days |
Local storage, offline-first pattern |
| Integration and testing |
2–3 days |
Unit tests (URLProtocol/OkHttp MockWebServer), UI tests |
| Deployment and documentation |
1 day |
CI/CD, store access, team README |
We deliver: source code of the network layer, documentation on used libraries, certificate rotation instructions, 2 weeks post-delivery support. Our experience guarantees that the solution will be stable and maintainable.
Timeline and Cost
Implementation of a network layer with REST, retry, caching, and offline mode — 1–2 weeks. Adding GraphQL or WebSocket — another 1–2 weeks. gRPC — 2–3 weeks, including code generation. The cost is calculated individually after analyzing the API and offline behavior requirements. We will evaluate the project in 1 day — contact us for a consultation. Get a reliable API integration with guaranteed quality.