March 24, 2026 • 8 min read • By Madhawa Sadil

Firebase Firestore & Realtime Architecture at Scale: Lessons from Arcade Leaderboards

Practical lessons in Firestore document schemas, read/write cost mitigation, rate limiting, and security rules when handling traffic spikes in web apps.

#Firebase #Cloud Architecture #Database Design #Security
Firebase Firestore is one of the most accessible cloud databases available to front-end developers, offering effortless real-time synchronization and serverless scalability. However, its pricing model—billing directly per document read, write, and delete—creates a dangerous pitfall for unoptimized web apps. A viral post on Reddit or Hacker News can trigger hundreds of thousands of concurrent reads, quickly ballooning operational costs. Here is how we architected Play09's cloud backend to remain fast, secure, and virtually free under high traffic.

The High Cost of Naive Real-Time Subscriptions

When first implementing Firebase, it is tempting to attach `onSnapshot` real-time listeners across all public collections. If 2,000 concurrent players are playing a game and listening to a live global leaderboard with 50 entries, every single new high score submission triggers 2,000 document reads across the network.

In an arcade game setting where high scores are updated frequently, naive listeners can generate tens of millions of document reads in a single afternoon. For Play09, we replaced passive real-time snapshot listeners with cached, explicit snapshot reads triggered only when the player enters the leaderboard screen, coupled with client-side localStorage caching with a 5-minute time-to-live (TTL).

Data Modeling: Flat Leaderboard Documents vs. Nested Subcollections

A critical design decision in Firestore is choosing between nested subcollections and top-level indexed collections. In our schema, we separate each game into its own dedicated partition:

`/games/{gameId}/scores/{scoreId}`

This structure allows us to query top scores for a specific game with compound indexing (`where('gameId', '==', 'retro-racer').orderBy('score', 'desc').limit(10)`) without scanning documents belonging to other games.

javascript
// Secure Firestore Rule Schema for Public Arcade Leaderboard
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    
    function isValidScore(data) {
      return data.score is int &&
             data.score >= 0 &&
             data.score <= 999999 &&
             data.playerName is string &&
             data.playerName.size() >= 2 &&
             data.playerName.size() <= 24 &&
             data.createdAt is timestamp;
    }

    match /leaderboards/{gameId}/scores/{scoreId} {
      // Anyone can view high scores
      allow read: if true;
      
      // Strict write conditions: valid score payload, prevents tampering
      allow create: if isValidScore(request.resource.data) &&
                      request.resource.data.createdAt == request.time;
      
      // Scores are immutable once recorded
      allow update, delete: if false;
    }
  }
}

Zero-Trust Security: Mitigating Cheat Injections

In public web games without forced user authentication, malicious actors can easily inspect network requests and attempt to dispatch arbitrary POST requests claiming impossibly high scores (e.g., submitting 999,999,999 points).

To guard against this without mandating tedious login friction for casual players, our Firestore rules enforce strict mathematical bounds on scores, require valid character sets for player names, and ensure the `createdAt` timestamp matches `request.time` exactly. Immutability rules (`allow update, delete: if false;`) ensure that once a record is written, it cannot be altered by third parties.

Never Trust Client Timestamps Always validate timestamps in Firestore rules using request.time. Client clocks can be forged or out of sync, leading to broken chronological sorting.

Optimistic UI with Fallback Grace

Network latency to cloud databases can fluctuate from 50ms on fiber connections to 800ms on weak mobile connections. To preserve arcade excitement, the user interface updates optimistically: the player's personal high score is immediately written to local storage and displayed on their summary screen while the background network call synchronizes with Firestore.

If the network request fails due to offline connectivity, the score remains safe locally and can be re-synced upon reconnection.

Conclusion

Firebase Firestore is an extraordinarily capable tool when approached with architectural discipline. By replacing continuous real-time listeners with cached queries, partitioning data cleanly, and locking down schema validation through security rules, you can serve thousands of concurrent users with sub-second response times while keeping cloud infrastructure costs at zero.