firebase-firestore
Skill: firebase-firestore
Version: 1.0.0 Purpose: Build with Firestore NoSQL database — real-time sync, offline support, and scalable document storage Author: The Forge Last Updated: 2025-07-14
Title
Firebase Firestore - Design, implement, and optimize Firestore NoSQL databases with real-time sync, security rules, and scalable document storage
File Structure
forge-plugin/skills/firebase-firestore/
├── SKILL.md # This file - mandatory workflow
└── examples.md # Usage scenarios and examples
Required Reading
Before executing this skill, load context and memory via interfaces:
-
Context: Use
contextProvider.getDomainIndex("schema")for relevant domain context. See ContextProvider Interface. -
Skill memory: Use
memoryStore.getSkillMemory("firebase-firestore", "{project-name}")for previous Firestore configurations. See MemoryStore Interface.
Interface References
- Context: Loaded via ContextProvider Interface
- Memory: Accessed via MemoryStore Interface
- Shared Patterns: Shared Loading Patterns
- Schemas: Validated against context_metadata.schema.json and memory_entry.schema.json
Design Requirements
Core Functionality
This skill must:
- Design collection and document structures (hierarchies, subcollections, denormalization)
- Build queries (simple, compound, collection group, pagination, ordering)
- Write security rules (authentication, field-level validation, role-based access)
- Implement real-time listeners (onSnapshot, query listeners, presence)
- Configure offline persistence (cache size, multi-tab, sync strategies)
- Handle transactions and batch writes (atomic operations, distributed counters)
- Model data for NoSQL (embedding vs referencing, fan-out, aggregation)
- Optimize performance (indexing, pagination cursors, query planning)
- Store Firestore configuration in memory for future reference
Output Requirements
Generate complete, production-ready Firestore implementations with:
- Collection and document schema definitions
- Security rules (firestore.rules)
- Query implementations (Web, Admin, Mobile SDKs)
- Real-time listener setup with error handling
- Offline persistence configuration
- Transaction and batch write patterns
- Composite index definitions (firestore.indexes.json)
- Data migration scripts when applicable
Quality Requirements
Generated implementations must:
- Follow Firestore best practices (document size limits, query constraints)
- Include comprehensive security rules (never deploy with open rules)
- Handle edge cases (offline scenarios, concurrent writes, pagination boundaries)
- Be SDK-appropriate (Web v9 modular, Admin SDK, Flutter, iOS, Android)
- Include error handling (permission denied, not found, quota exceeded)
- Be well-documented (collection schemas, query patterns, rule logic)
10 Common Firestore Errors Prevented
This skill actively prevents these frequently encountered Firestore mistakes:
1. Missing Composite Index
Error: FAILED_PRECONDITION: The query requires an index
Prevention: Generate firestore.indexes.json for all compound queries. Always check if a query combines multiple where() clauses or mixes where() with orderBy() on different fields.
2. Insecure Security Rules
Error: Data breach from allow read, write: if true;
Prevention: Never generate open rules. Always require authentication and validate data structure. Generate role-based rules with field-level validation.
3. Unbounded Queries
Error: Reading entire collections, excessive reads, cost explosion
Prevention: Always implement pagination with limit() and cursor-based pagination using startAfter(). Never query without a limit in production.
4. Incorrect Data Modeling (SQL Thinking)
Error: Over-normalized data requiring excessive JOINs (Firestore has no JOINs) Prevention: Design for query patterns, not normalization. Denormalize strategically. Embed frequently-accessed related data within documents.
5. Document Size Limit Exceeded
Error: INVALID_ARGUMENT: maximum document size is 1 MiB
Prevention: Monitor document growth. Use subcollections for unbounded lists. Never store arrays that can grow indefinitely inside a document.
6. Hot Spots from Sequential IDs
Error: Write throttling from auto-incrementing or timestamp-based document IDs Prevention: Use Firestore auto-generated IDs. Avoid sequential document IDs that cause write hot spots on a single tablet.
7. Missing Offline Handling
Error: App crashes or hangs when offline, stale data displayed without indication
Prevention: Configure persistence settings, handle fromCache metadata, implement connectivity state listeners, and design UI for offline states.
8. Transaction Contention
Error: ABORTED: Transaction was aborted due to contention
Prevention: Keep transactions small and fast. Avoid transactions on frequently updated documents. Use distributed counters for high-write scenarios.
9. Inefficient Real-Time Listeners
Error: Excessive reads from poorly scoped listeners, memory leaks from undetached listeners Prevention: Scope listeners to minimal data sets. Always unsubscribe when components unmount. Use query listeners instead of document listeners when possible.
10. Missing Error Handling on Writes
Error: Silent data loss when writes fail (offline queue overflow, permission denied)
Prevention: Always handle write errors. Implement retry logic. Monitor pending writes count. Handle permission-denied errors gracefully with user feedback.
Instructions
MANDATORY STEPS (Must Execute in Order)
Step 1: Initial Analysis
Purpose: Understand the Firestore implementation requirements
Actions:
- Identify the application type (web, mobile, server-side)
- Determine the SDK environment (Web v9 modular, Admin SDK, Flutter, iOS, Android)
- Review existing Firestore configuration if present (firebase.json, firestore.rules, firestore.indexes.json)
- Understand the data access patterns and query requirements
- Identify real-time requirements (which data needs live updates)
- Note any existing data models or migration needs
Output: Clear understanding of Firestore requirements and constraints
Step 2: Load Memory
Purpose: Retrieve previous Firestore configurations for this project
Follow Standard Memory Loading with
skill="firebase-firestore"anddomain="schema".
Actions:
- Use
memoryStore.getSkillMemory("firebase-firestore", "{project-name}")to load project memory. See MemoryStore Interface. - If memory exists, review:
collection_structure.md- Existing collection hierarchies and document schemassecurity_rules.md- Current security rules and access patternsquery_patterns.md- Established query patterns and indexesdata_model.md- Data modeling decisions and trade-offsperformance_config.md- Performance tuning and optimization settings
- If not exists, note this is first-time Firestore setup
Output: Understanding of project Firestore history or recognition of new project
Step 3: Load Context
Purpose: Load relevant NoSQL and Firestore knowledge
Follow Standard Context Loading for the
schemadomain. Stay within the file budget declared in frontmatter.
Actions:
- Use
contextProvider.getDomainIndex("schema")for database design context - Load relevant context files based on requirements:
- NoSQL data modeling patterns
- Security best practices
- Performance optimization guidelines
- Note any best practices for Firestore implementation
Output: Comprehensive understanding of Firestore patterns and best practices
Step 4: Firestore Implementation
Purpose: Design and implement the Firestore solution
Actions:
A. Collection and Document Design:
-
Design collection hierarchy:
- Map entities to collections and subcollections
- Decide embedding vs referencing strategy
- Define document schemas with field types
- Plan for document size limits (1 MiB max)
- Design document ID strategy (auto-generated vs custom)
-
Data modeling for queries:
- Identify all query patterns the application needs
- Denormalize data to support queries without client-side JOINs
- Design fan-out writes for feed-style data
- Plan aggregation fields (counters, sums, averages)
- Handle many-to-many relationships
B. Security Rules:
-
Design security rules (firestore.rules):
- Authentication requirements per collection
- Field-level validation (type, format, range)
- Role-based access control (RBAC)
- Data ownership rules (user can only access own data)
- Rate limiting patterns
- Cross-collection validation (when needed)
-
Security rules testing:
- Provide test scenarios for rules
- Cover allow and deny cases
- Test edge cases (missing fields, wrong types)
C. Query Implementation:
- Simple queries: Single field filters, ordering, limiting
- Compound queries: Multiple
where()clauses (equality + range) - Collection group queries: Querying across subcollections
- Pagination: Cursor-based with
startAfter(),limit() - Real-time queries:
onSnapshot()with error handling - Aggregation queries:
count(),sum(),average()
D. Real-Time Listeners:
- Document listeners: Single document change monitoring
- Query listeners: Filtered collection monitoring
- Snapshot metadata: Handle
fromCacheandhasPendingWrites - Listener lifecycle: Attach on mount, detach on unmount
- Error recovery: Handle listener errors gracefully
E. Offline and Transactions:
- Offline persistence: Configure cache size, multi-tab support
- Transactions: Read-then-write atomic operations
- Batch writes: Atomic multi-document writes (max 500 operations)
- Distributed counters: Shard counters for high-write scenarios
- Optimistic concurrency: Handle contention gracefully
F. Indexing and Performance:
- Single-field indexes: Automatic, manage exemptions
- Composite indexes: Generate
firestore.indexes.json - Query planning: Optimize for read-heavy vs write-heavy
- Connection management: Configure SDK settings
Output: Complete Firestore implementation
Step 5: Generate Output
Purpose: Produce deliverable artifacts
Actions:
- Save output to
/claudedocs/firebase-firestore_{project}_{YYYY-MM-DD}.md - Follow naming conventions in
../OUTPUT_CONVENTIONS.md - Generate deliverable files:
firestore.rules- Security rulesfirestore.indexes.json- Composite index definitions- Collection schema documentation
- Query implementation code (appropriate SDK)
- Real-time listener setup code
- Data migration scripts (if applicable)
- Include the 10-error prevention checklist in output
Output: Complete, production-ready Firestore implementation artifacts
Step 6: Update Memory
Purpose: Store configuration for future reference
Follow Standard Memory Update for
skill="firebase-firestore". Store any newly learned patterns, conventions, or project insights.
Actions:
- Use
memoryStore.update(layer="skill-specific", skill="firebase-firestore", project="{project-name}", ...)to store: - collection_structure.md:
- Collection hierarchy and subcollections
- Document schemas with field types
- Document ID strategies
- Denormalization decisions
- security_rules.md:
- Current security rules
- Access control patterns
- Validation logic
- Rule testing results
- query_patterns.md:
- Implemented query patterns
- Composite indexes required
- Pagination strategies
- Real-time listener scopes
- data_model.md:
- Embedding vs referencing decisions
- Fan-out write patterns
- Aggregation strategies
- Relationship modeling
- performance_config.md:
- Cache configuration
- Index optimizations
- Read/write distribution
- Cost optimization notes
Output: Memory stored for future skill invocations
Best Practices
Collection Design
- Model for queries: Design collections around how data is read, not how it's related
- Use subcollections: For one-to-many relationships with large cardinality
- Denormalize strategically: Duplicate data that is read together frequently
- Keep documents small: Aim for under 100 KiB, never exceed 1 MiB
- Avoid unbounded arrays: Use subcollections instead of growing arrays
Security Rules
- Never deploy open rules: Always require authentication
- Validate all writes: Check field types, ranges, and required fields
- Use custom claims: For role-based access control
- Test rules thoroughly: Use the Firebase Emulator for rule testing
- Keep rules DRY: Use functions for reusable validation logic
Query Optimization
- Create indexes proactively: Don't wait for errors to create composite indexes
- Paginate all list queries: Never fetch unbounded collections
- Use cursor pagination:
startAfter()overoffset()for efficiency - Scope listeners tightly: Listen to the minimum data set needed
- Use aggregation queries: Prefer server-side
count()over client-side counting
Real-Time Listeners
- Always unsubscribe: Detach listeners when no longer needed
- Handle errors in listeners: Network failures, permission changes
- Use metadata: Check
fromCacheto indicate stale data to users - Debounce rapid updates: Avoid re-rendering on every snapshot
- Prefer query listeners: Over individual document listeners for lists
Error Handling
Common Issues
- Permission denied: Check security rules and user authentication state
- Missing index: Create composite index from error link or
firestore.indexes.json - Document not found: Handle gracefully with fallback UI
- Quota exceeded: Implement backoff and monitor usage
- Network errors: Leverage offline persistence, show connectivity state
Debugging
- Use Firebase Emulator: Test locally without affecting production
- Check rules in console: Use the Rules Playground for testing
- Monitor in Firebase Console: Track reads, writes, and deletes
- Enable debug logging:
firebase.firestore.setLogLevel('debug') - Review index usage: Check for unnecessary or missing indexes
Compliance Checklist
Before completing, verify:
- All mandatory workflow steps executed in order
- Standard Memory Loading pattern followed (Step 2)
- Standard Context Loading pattern followed (Step 3)
- Output saved with standard naming convention
- Standard Memory Update pattern followed (Step 6)
- Security rules require authentication (no open rules)
- All compound queries have composite indexes defined
- Pagination implemented for all list queries
- Real-time listeners have proper unsubscribe handling
- 10-error prevention checklist verified
Version History
| Version | Date | Changes |
|---|---|---|
| 1.0.0 | 2025-07-14 | Initial release with interface-based patterns, 10-error prevention, comprehensive Firestore workflow |
Related Skills
- database-schema-analysis: For analyzing existing database schemas before migration
- generate-api-spec: For designing APIs that interact with Firestore
- security-audit: For comprehensive security rule review