Overview

Ecosistema completo para organización y gestión de contenido con interfaces espaciales

MongoDB Integration - Overview & Architecture

Last Updated: October 10, 2025
Version: 1.0.0
Status: Production Ready


Table of Contents

  1. Introduction
  2. Architecture Overview
  3. Core Components
  4. Data Flow
  5. Design Decisions
  6. Performance Characteristics
  7. Use Cases

Introduction

The MongoDB Integration extends our storage-system with intelligent cloud synchronization capabilities while preserving the exceptional performance of local operations. This strategic enhancement adds optional cloud sync, real-time features, and collaborative capabilities without compromising the sub-millisecond local cache performance that makes our storage system world-class.

Key Features

Philosophy

Our MongoDB integration follows these core principles:

  1. Performance First: Local operations never wait for the network
  2. Flexibility: Configure sync behavior per collection or even per key
  3. Resilience: Works perfectly offline with automatic queue management
  4. Intelligence: Smart batching, priority-based sync, and automatic retry
  5. Simplicity: Easy to use, hard to misuse

Architecture Overview

The MongoDB integration consists of five major components working together to provide a seamless cloud sync experience:

┌─────────────────────────────────────────────────────────────────┐
│                         Application Layer                        │
│  (Components using autoFlashState, FlashStateService, etc.)    │
└────────────────┬────────────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────────────┐
│                    Storage System (GgStorage)                    │
│              ┌──────────────────────────────────────┐           │
│              │    FlashStateHydratorService         │           │
│              │  (Pre-loading, instant access)        │           │
│              └──────────────┬───────────────────────┘           │
│                             │                                    │
│              ┌──────────────▼───────────────────────┐           │
│              │      Storage Registry                 │           │
│              │  (OPFS, IndexedDB, localStorage)     │           │
│              └──────────────┬───────────────────────┘           │
└─────────────────────────────┼────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    MongoDB Sync Layer                            │
│                                                                  │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │            Intelligent Sync Engine                        │  │
│  │  • Priority-based queue management                        │  │
│  │  • Smart batching by collection                           │  │
│  │  • Exponential backoff retry                              │  │
│  │  • Online/offline detection                               │  │
│  │  • Event notifications                                    │  │
│  └─────────┬────────────────────────────────┬────────────────┘  │
│            │                                 │                   │
│            ▼                                 ▼                   │
│  ┌──────────────────────┐        ┌──────────────────────────┐  │
│  │  MongoDB Sync Adapter│        │ MongoDB Realtime Service │  │
│  │  • Connection pool   │        │  • Change Streams        │  │
│  │  • Sync strategies   │        │  • Auto-reconnect        │  │
│  │  • Conflict resolve  │        │  • Event filtering       │  │
│  │  • Queue persistence │        │  • Bi-directional sync   │  │
│  └──────────┬───────────┘        └──────────┬───────────────┘  │
│             │                                │                   │
│             │         ┌──────────────────────▼────────────────┐ │
│             │         │   Sync Configuration Service          │ │
│             │         │  • Per-collection strategies          │ │
│             │         │  • Configuration presets              │ │
│             │         │  • Runtime strategy switching         │ │
│             │         └───────────────────────────────────────┘ │
└─────────────┼─────────────────────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      MongoDB Atlas                               │
│                    (Cloud Database)                              │
│  • MongoDB 8.0.3                                                │
│  • AWS US-EAST-1                                                │
│  • Change Streams enabled                                       │
└─────────────────────────────────────────────────────────────────┘

Component Relationships

  1. Application Layer uses Flash Persistence (autoFlashState) for state management
  2. Flash Persistence uses GgStorage for local persistence
  3. GgStorage optionally hooks into the MongoDB Sync Layer
  4. Intelligent Sync Engine coordinates all sync operations
  5. MongoDB Sync Adapter handles the actual database operations
  6. Real-Time Service manages Change Streams (optional)
  7. Configuration Service provides centralized strategy management

Core Components

1. MongoDB Sync Adapter

The sync adapter is responsible for direct interaction with MongoDB Atlas.

Responsibilities:

Key Features:

Configuration:

const adapter = new MongoDBSyncAdapter({
  connectionString: 'mongodb+srv://...',
  database: 'my-database',
  defaultStrategy: 'offline-first',
  conflictResolution: 'last-write-wins',
  storage: ggStorage
});

2. Intelligent Sync Engine

The sync engine orchestrates all sync operations with intelligence and efficiency.

Responsibilities:

Priority Levels:

Smart Batching:

Exponential Backoff:


3. MongoDB Real-Time Service

The real-time service provides optional Change Streams integration for live updates.

Responsibilities:

Change Stream Operations:

Event Filtering:

realtimeService.enable('messages', {
  filter: {
    operationType: ['insert', 'update'],
    'fullDocument.status': 'published'
  }
});

Auto-Update Local Storage: When enabled, remote changes automatically update local storage:


4. Sync Configuration Service

The configuration service provides centralized management of sync strategies.

Responsibilities:

Configuration Presets:

E-commerce:

{
  cart: 'offline-first',      // Instant cart updates
  inventory: 'online-first',  // Real-time inventory
  orders: 'critical-sync',    // Immediate order sync
  analytics: 'low-priority'   // Background analytics
}

Real-Time Messaging:

{
  messages: 'realtime',       // Live message sync
  drafts: 'offline-first',    // Local-first drafts
  read_receipts: 'realtime',  // Instant read status
  media: 'high-priority'      // Priority media uploads
}

Content Management:

{
  content: 'offline-first',   // Edit offline
  media: 'online-first',      // Cloud media storage
  drafts: 'offline-first',    // Local drafts
  published: 'realtime'       // Live published content
}

5. Angular Providers

The providers make integration into Angular applications seamless.

Full Feature Setup:

import { provideMongoDBSync } from '@storage-system/sync';

bootstrapApplication(AppComponent, {
  providers: [
    provideMongoDBSync({
      connectionString: environment.mongoDBUrl,
      database: 'my-app-db',
      autoConnect: true,
      enableRealtime: ['messages', 'notifications']
    })
  ]
});

Minimal Setup:

import { provideMongoDBSyncMinimal } from '@storage-system/sync';

bootstrapApplication(AppComponent, {
  providers: [
    provideMongoDBSyncMinimal({
      connectionString: environment.mongoDBUrl,
      database: 'my-app-db'
    })
  ]
});

Data Flow

Offline-First Flow (Default)

┌──────────────────────────────────────────────────────────────┐
│  1. User Action (e.g., create task)                         │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  2. Local Storage Write (OPFS/IndexedDB) - 0.3ms            │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  3. UI Updated Instantly                                     │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  4. Operation Queued for Background Sync                     │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  5. Intelligent Sync Engine Processes Queue                  │
│     • Sorts by priority                                      │
│     • Batches by collection                                  │
│     • Waits for optimal time window                          │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  6. MongoDB Sync Adapter Executes Batch                      │
│     • Connection pool                                        │
│     • Error handling                                         │
│     • Conflict resolution                                    │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  7. MongoDB Atlas Updated                                    │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  8. Success/Failure Event Emitted                            │
│     • UI can show sync status                                │
│     • Retry on failure (exponential backoff)                 │
└──────────────────────────────────────────────────────────────┘

Performance: User sees instant feedback in ~0.3ms, cloud sync happens in background.


Real-Time Flow (Change Streams)

┌──────────────────────────────────────────────────────────────┐
│  1. Remote Change in MongoDB Atlas                           │
│     (Another user, another device, another tab)              │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  2. MongoDB Change Stream Emits Event                        │
│     • operationType (insert, update, delete, replace)        │
│     • fullDocument (complete document or null)               │
│     • updateDescription (changed fields)                     │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  3. Real-Time Service Receives Event                         │
│     • Filters by configuration                               │
│     • Checks if collection enabled                           │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  4. Local Storage Updated (if enabled)                       │
│     • Insert → Create local                                  │
│     • Update → Merge with local                              │
│     • Delete → Remove local                                  │
│     • Replace → Replace local                                │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  5. Flash Persistence Signals Updated                        │
│     • Reactive UI updates automatically                      │
│     • Computed signals recalculate                           │
└────────────┬─────────────────────────────────────────────────┘
             │
             ▼
┌──────────────────────────────────────────────────────────────┐
│  6. UI Reflects Remote Change                                │
│     • Seamless multi-tab sync                                │
│     • Collaborative features enabled                         │
└──────────────────────────────────────────────────────────────┘

Performance: Real-time updates typically arrive in 100-500ms depending on network.


Design Decisions

1. Why Offline-First?

Decision: Make offline-first the default strategy.

Rationale:

Benefits:


2. Why Flexible Schemas?

Decision: Support any JavaScript object without rigid models.

Rationale:

Benefits:


3. Why Priority-Based Sync?

Decision: Different sync intervals based on data priority.

Rationale:

Benefits:


4. Why Multiple Conflict Resolution Strategies?

Decision: Offer last-write-wins, merge, and manual resolution.

Rationale:

Benefits:


5. Why Optional Real-Time?

Decision: Make Change Streams opt-in per collection.

Rationale:

Benefits:


Performance Characteristics

Local Operations

Operation Target Time Actual Performance
Read (Cached) < 1ms ~0.3ms
Write (Local) < 1ms ~0.3ms
Delete (Local) < 1ms ~0.3ms
Update (Local) < 1ms ~0.3ms

Conclusion: Local operations remain instant regardless of sync configuration.


Sync Operations

Priority Target Sync Time Use Cases
Critical 1-5 seconds Payment confirmations, critical updates
High 10-30 seconds User profile, important data
Normal 1-5 minutes Preferences, settings
Low 10-30 minutes Analytics, logs

Note: Actual sync time depends on network conditions and queue size.


Queue Processing

Queue Size Processing Time Notes
10 ops < 1s Single batch
100 ops < 5s 10 batches (parallel)
1000 ops < 30s Smart batching

Conclusion: Queue processing is efficient even with large backlogs.


Real-Time Updates

Metric Performance
Change Stream Latency 100-500ms
Local Storage Update ~1ms
UI Update (Signals) Immediate
Total Time to UI 100-500ms

Conclusion: Real-time updates are near-instantaneous.


Use Cases

1. Offline-First Mobile App

Scenario: Todo/task management app used on mobile with intermittent connectivity.

Strategy:

{
  tasks: 'offline-first',
  tags: 'offline-first',
  analytics: 'low-priority'
}

Benefits:


2. Real-Time Collaboration

Scenario: Collaborative document editing with multiple users.

Strategy:

{
  documents: 'realtime',
  cursors: 'realtime',
  drafts: 'offline-first'
}

Benefits:


3. E-Commerce Application

Scenario: Online store with cart, inventory, and orders.

Strategy:

{
  cart: 'offline-first',
  inventory: 'online-first',
  orders: 'critical-sync',
  reviews: 'normal'
}

Benefits:


4. Content Management System

Scenario: Blog/CMS with drafts and published content.

Strategy:

{
  drafts: 'offline-first',
  media: 'online-first',
  published: 'realtime',
  analytics: 'low-priority'
}

Benefits:


5. Analytics Dashboard

Scenario: Real-time analytics with high data volume.

Strategy:

{
  live_metrics: 'realtime',
  historical: 'online-first',
  events: 'low-priority'
}

Benefits:


Next Steps

Now that you understand the architecture and core concepts, continue with:

  1. Getting Started Guide - Set up MongoDB sync in your app
  2. Configuration Reference - All available options
  3. Advanced Topics - Custom strategies, performance tuning
  4. API Reference - Complete API documentation

Questions?

If you have questions or need help, check:


Next: Getting Started Guide →