Flow Platform - Technical Architecture

Documento pre-migrazione Supabase-only

Questo documento descrive l’architettura microservizi che Flow usava fino al 2026-03-29. Dopo la migrazione Supabase-only l’API Gateway, i microservizi Node.js, MongoDB e Redis non esistono più.

Per l’architettura attuale vedi Architecture Overview. Questo file è conservato come riferimento storico.

Table of Contents

  1. System Overview
  2. Microservices Architecture
  3. Technology Stack
  4. Database Architecture
  5. API Gateway
  6. Real-time Architecture
  7. Caching Strategy
  8. Security Architecture
  9. Service Communication
  10. Deployment Architecture

System Overview

Flow is an AI-powered event discovery and social networking platform built with a modern microservices architecture. The platform enables users to discover events, connect with others, form crews, and participate in social activities.

High-Level Architecture

┌─────────────┐     ┌──────────────┐     ┌─────────────┐
│   Mobile    │     │ Admin Portal │     │  Web Client │
│  (Flutter)  │     │  (Next.js)   │     │             │
└──────┬──────┘     └──────┬───────┘     └──────┬──────┘
       │                   │                     │
       └───────────────────┼─────────────────────┘
                           │
                    ┌──────▼──────┐
                    │ API Gateway │
                    │  (Port 3000)│
                    └──────┬──────┘
                           │
       ┌───────────────────┼───────────────────┐
       │                   │                   │
┌──────▼──────┐    ┌──────▼──────┐    ┌──────▼──────┐
│    User     │    │    Event    │    │   Social    │
│  Service    │    │  Service    │    │  Service    │
│ (Port 3001) │    │ (Port 3002) │    │ (Port 3003) │
└──────┬──────┘    └──────┬──────┘    └──────┬──────┘
       │                   │                   │
┌──────▼──────┐    ┌──────▼──────┐    ┌──────▼──────┐
│Notification │    │  Realtime   │    │     AI      │
│  Service    │    │  Service    │    │  Services   │
│ (Port 3004) │    │ (Port 3005) │    │ (Port 8001) │
└─────────────┘    └─────────────┘    └─────────────┘
       │                   │                   │
       └───────────────────┼───────────────────┘
                           │
       ┌───────────────────┼───────────────────┐
       │                   │                   │
┌──────▼──────┐    ┌──────▼──────┐    ┌──────▼──────┐
│   MongoDB   │    │  PostgreSQL │    │    Redis    │
│             │    │  (Supabase) │    │   (Cache)   │
└─────────────┘    └─────────────┘    └─────────────┘

Microservices Architecture

1. API Gateway (Port 3000)

Technology: Node.js + Express + http-proxy-middleware Responsibilities:

  • Central entry point for all client requests
  • Request routing to appropriate microservices
  • Authentication and authorization
  • Rate limiting and throttling
  • Request/response logging
  • CORS management
  • API documentation (Swagger)

Key Features:

  • JWT token verification
  • Service proxy with retry logic (3 retries, 30s timeout)
  • Correlation ID tracking for distributed tracing
  • Health check aggregation
  • WebSocket proxy for real-time service

Service Routes:

  • /api/users → User Service
  • /api/v1/users → User Service (versioned)
  • /api/events → Event Service
  • /api/v1/events → Event Service (versioned)
  • /api/social → Social Service
  • /api/v1/social → Social Service (versioned)
  • /api/notifications → Notification Service
  • /api/v1/notifications → Notification Service (versioned)
  • /api/recommendations → Recommendation Engine
  • /api/matchmaking → Matchmaking Service
  • /socket.io → Realtime Service (WebSocket)

Security Middleware:

  • Helmet.js for security headers
  • Rate limiting: 100 requests per 15 minutes
  • Request size limits: 10MB
  • MongoDB sanitization
  • XSS protection
  • HPP (HTTP Parameter Pollution) prevention

2. User Service (Port 3001)

Technology: Node.js + Express + MongoDB Database: MongoDB (NoSQL) Responsibilities:

  • User authentication and authorization
  • Profile management
  • User preferences and settings
  • Two-factor authentication
  • Password reset and email verification
  • Device token management for push notifications
  • User statistics and achievements

Core Models:

  • User: Email, username, password, profile info, location, privacy settings
  • Profile: Extended profile information, bio, interests
  • Preferences: Notification preferences, language, timezone, theme

Key Features:

  • BCrypt password hashing (12 rounds)
  • JWT token generation (access + refresh tokens)
  • Account lockout after 5 failed login attempts
  • Geospatial indexing for location-based features
  • Email verification and password reset tokens
  • Login history tracking
  • 2FA with backup codes

API Endpoints:

  • POST /api/v1/auth/register - User registration
  • POST /api/v1/auth/login - User authentication
  • POST /api/v1/auth/refresh - Refresh access token
  • POST /api/v1/auth/logout - User logout
  • GET /api/v1/users/:id - Get user profile
  • PUT /api/v1/users/:id - Update user profile
  • GET /api/v1/profiles/:id - Get extended profile
  • PUT /api/v1/preferences - Update preferences

3. Event Service (Port 3002)

Technology: Node.js + Express + MongoDB Database: MongoDB (NoSQL) Responsibilities:

  • Event creation and management
  • Venue management
  • Event categories and tags
  • Attendee registration and check-in
  • Ticketing system
  • Event search and filtering
  • Geospatial event discovery
  • Event analytics

Core Models:

  • Event: Title, description, schedule, location, capacity, ticketing, attendees
  • Venue: Name, address, coordinates, amenities, pricing, availability
  • Category: Event categorization and subcategories

Key Features:

  • Full-text search on title and description
  • Geospatial queries for nearby events
  • Recurring event support (daily, weekly, monthly, yearly)
  • Multi-tier ticketing system
  • Waitlist management
  • Event social features (likes, comments, shares)
  • Weather forecast integration
  • Event quality scoring
  • Virtual, hybrid, and physical event support

Event Types:

  • In-person (physical venue)
  • Virtual (Zoom, Teams, Meet, WebEx)
  • Hybrid (both physical and virtual)

API Endpoints:

  • GET /api/events - List events with filters
  • POST /api/events - Create new event
  • GET /api/events/:id - Get event details
  • PUT /api/events/:id - Update event
  • DELETE /api/events/:id - Delete event
  • POST /api/events/:id/attend - Register for event
  • POST /api/events/:id/like - Like event
  • GET /api/events/nearby - Find nearby events
  • GET /api/events/featured - Get featured events
  • GET /api/venues - List venues
  • POST /api/venues - Create venue
  • GET /api/categories - Get event categories

4. Social Service (Port 3003)

Technology: Node.js + Express + MongoDB Database: MongoDB (NoSQL) Responsibilities:

  • Friend/connection management
  • Social groups and communities
  • Posts and social feed
  • Connection suggestions
  • Social interactions tracking

Core Models:

  • Connection: Friend requests, connections, mutual friends
  • Group: Social groups and memberships
  • Post: User-generated content, likes, comments

Key Features:

  • Connection request workflow (pending → accepted/declined/blocked)
  • Mutual connection discovery
  • Connection strength calculation
  • Suggested connections based on mutual friends
  • Connection expiration (30 days for pending requests)
  • Interaction tracking (messages, events attended together, groups in common)
  • Multiple connection types (friend, follow, professional, family)

Connection Statuses:

  • pending - Request sent, awaiting response
  • accepted - Connection established
  • declined - Request declined
  • blocked - User blocked
  • cancelled - Request cancelled by requester

API Endpoints:

  • POST /api/connections/request - Send connection request
  • POST /api/connections/:id/accept - Accept connection
  • POST /api/connections/:id/decline - Decline connection
  • GET /api/connections - Get user connections
  • GET /api/connections/suggestions - Get suggested connections
  • GET /api/groups - List groups
  • POST /api/groups - Create group
  • POST /api/posts - Create post
  • GET /api/posts/feed - Get social feed

5. Notification Service (Port 3004)

Technology: Node.js + Express + MongoDB Database: MongoDB (NoSQL) Responsibilities:

  • Multi-channel notification delivery (push, email, SMS, in-app)
  • Notification templates and personalization
  • User notification preferences
  • Scheduled and batch notifications
  • Notification analytics and tracking
  • Retry logic with exponential backoff

Core Models:

  • Notification: Multi-channel notification with delivery tracking
  • NotificationTemplate: Reusable notification templates
  • UserPreference: Per-user notification settings

Notification Types:

  • connection_request - New friend request
  • connection_accepted - Friend request accepted
  • group_invitation - Group invitation
  • post_like - Post liked
  • post_comment - Comment on post
  • event_invitation - Event invitation
  • event_reminder - Event reminder
  • event_update - Event details changed
  • system_announcement - System-wide announcement
  • security_alert - Security-related alerts

Delivery Channels:

  • Push Notifications: Firebase Cloud Messaging
  • Email: SendGrid integration
  • SMS: Twilio integration
  • In-App: Real-time via Socket.IO

Key Features:

  • Priority-based delivery (low, normal, high, urgent)
  • Scheduled notifications with timezone support
  • Retry mechanism (max 3 attempts, exponential backoff)
  • Notification grouping and batching
  • Deep linking for mobile apps
  • Template system with variable substitution
  • Multi-language support
  • Delivery tracking and analytics
  • User preference enforcement

API Endpoints:

  • POST /api/notifications - Create notification
  • GET /api/notifications - Get user notifications
  • PUT /api/notifications/:id/read - Mark as read
  • DELETE /api/notifications/:id - Delete notification
  • GET /api/notifications/unread/count - Get unread count
  • GET /api/templates - List notification templates
  • POST /api/templates - Create template
  • GET /api/preferences - Get user preferences
  • PUT /api/preferences - Update preferences

6. Realtime Service (Port 3005)

Technology: Node.js + Express + Socket.IO + Redis Database: Redis (pub/sub and session storage) Responsibilities:

  • Real-time bidirectional communication
  • Live messaging and chat
  • User presence tracking
  • Real-time event updates
  • Live notifications
  • Room-based communication

Core Models:

  • Message: Chat messages with delivery tracking
  • Room: Chat rooms and channels
  • UserPresence: Online/offline status tracking

Socket.IO Namespaces:

  • / - Default namespace for general real-time updates
  • /chat - Private messaging
  • /events - Event-specific updates
  • /notifications - Real-time notifications

WebSocket Events:

  • Connection Events:

    • connect - Client connected
    • disconnect - Client disconnected
    • authenticate - JWT authentication
  • Message Events:

    • message:send - Send message
    • message:received - Message received
    • message:read - Mark message as read
    • typing:start - User started typing
    • typing:stop - User stopped typing
  • Presence Events:

    • presence:online - User came online
    • presence:offline - User went offline
    • presence:away - User is away
    • presence:busy - User is busy
  • Room Events:

    • room:join - Join chat room
    • room:leave - Leave chat room
    • room:message - Room message

Key Features:

  • JWT-based Socket authentication
  • Redis adapter for horizontal scaling
  • Automatic reconnection handling
  • Message persistence in MongoDB
  • Delivery acknowledgments
  • Typing indicators
  • User presence with heartbeat
  • Room-based broadcasts
  • Rate limiting on socket events

Technology Stack

Backend Services

  • Runtime: Node.js 18+
  • Framework: Express.js 4.18
  • Language: JavaScript (ES6+)

Databases

  • MongoDB 7.5: NoSQL database for user data, events, social features

    • User Service: User profiles, authentication
    • Event Service: Events, venues, categories
    • Social Service: Connections, groups, posts
    • Notification Service: Notifications, templates
    • Realtime Service: Messages, rooms
  • PostgreSQL (Supabase): SQL database for structured data

    • Profiles (extends Supabase Auth)
    • Events
    • Event attendees
    • Venues
    • Tags
    • Crews (social groups anchored to events/venues/areas)
    • Crew members
    • Crew feedback and karma system
  • Redis 4.6: In-memory data store

    • Session management
    • Caching layer
    • Real-time pub/sub
    • Rate limiting storage

Frontend

  • Mobile: Flutter (Dart)
  • Admin Portal: Next.js 14 + React + TypeScript
  • Web: React (planned)

AI/ML Services

  • Framework: Python + FastAPI
  • Port: 8001
  • Features: Event recommendations, user matching

External Services

  • Authentication: Supabase Auth
  • Storage: AWS S3 / Cloudinary
  • Email: SendGrid
  • Push Notifications: Firebase Cloud Messaging
  • SMS: Twilio
  • Maps: Google Maps API
  • Payment: Stripe (planned)

DevOps & Infrastructure

  • Containerization: Docker
  • Orchestration: Docker Compose
  • CI/CD: GitHub Actions (planned)
  • Monitoring: Winston (logging)
  • API Documentation: Swagger/OpenAPI

Database Architecture

Dual Database Strategy

Flow uses a dual database architecture combining MongoDB and PostgreSQL (Supabase):

MongoDB (Primary for Microservices)

Use Cases:

  • Rapidly evolving schemas
  • Complex nested documents
  • High write throughput
  • Flexible data models

Collections by Service:

  • User Service: users, profiles, preferences
  • Event Service: events, venues, categories
  • Social Service: connections, groups, posts
  • Notification Service: notifications, templates, user_preferences
  • Realtime Service: messages, rooms, user_presence

PostgreSQL/Supabase (Primary for Structured Data)

Use Cases:

  • Structured relational data
  • ACID transactions
  • Complex joins and queries
  • Geospatial queries (PostGIS)
  • Row-level security (RLS)

Tables:

  • profiles - User profiles (extends auth.users)
  • events - Event details with geospatial data
  • event_attendees - Event registrations
  • venues - Venue information with geospatial data
  • tags - Event and content tags
  • crews - Social groups anchored to locations/events
  • crew_members - Crew memberships
  • crew_feedback - Peer reviews and karma system

Data Consistency Strategy

  1. Eventual Consistency:

    • MongoDB and PostgreSQL operate independently
    • Critical data (auth, payments) in PostgreSQL
    • Performance-oriented features in MongoDB
  2. Synchronization:

    • User creation triggers profile creation in both databases
    • Event updates propagated to both systems
    • Background jobs handle reconciliation
  3. Primary Source of Truth:

    • Authentication: Supabase (PostgreSQL)
    • User Profiles: MongoDB (User Service)
    • Events: Both (MongoDB for details, PostgreSQL for geospatial)
    • Social: MongoDB
    • Notifications: MongoDB

API Gateway

Request Flow

Client Request
    │
    ▼
┌─────────────────────┐
│  CORS + Helmet      │ Security headers
└─────────┬───────────┘
          │
          ▼
┌─────────────────────┐
│  Rate Limiting      │ 100 req/15min
└─────────┬───────────┘
          │
          ▼
┌─────────────────────┐
│  Request Logging    │ Morgan + Winston
└─────────┬───────────┘
          │
          ▼
┌─────────────────────┐
│  Authentication     │ JWT verification (if protected)
└─────────┬───────────┘
          │
          ▼
┌─────────────────────┐
│  Service Proxy      │ Route to microservice
└─────────┬───────────┘
          │
          ▼
    Microservice

Rate Limiting Configuration

  • Window: 15 minutes
  • Max Requests: 100 per window
  • Slow Down: Starts at 50 requests (500ms delay, max 20s)
  • Standard Headers: RateLimit-* headers included
  • Per-IP Limiting: Based on trusted proxy IP

Authentication Flow

1. Client sends JWT in Authorization header: "Bearer <token>"
2. API Gateway extracts and verifies JWT
3. Validates issuer, audience, expiration
4. Extracts user info (id, email, role, permissions)
5. Adds headers to proxied request:
   - x-user-id: User ID
   - x-user-role: User role
   - x-correlation-id: Request tracking ID
6. Forwards request to microservice

Protected Routes

  • /api/users/profile
  • /api/users/preferences
  • /api/events/create
  • /api/social/*
  • /api/notifications/*
  • /api/recommendations/*
  • /api/matchmaking/*

Real-time Architecture

Socket.IO Implementation

Transport Layers:

  1. WebSocket (primary)
  2. HTTP long-polling (fallback)

Redis Adapter for horizontal scaling:

// Multiple server instances share socket state via Redis
io.adapter(redisAdapter({
  pubClient: redisPub,
  subClient: redisSub
}));

Connection Lifecycle

Client                    Server                     Redis
  │                          │                          │
  │────connect───────────────▶│                          │
  │                          │                          │
  │◀───connection-ack────────│                          │
  │                          │                          │
  │────authenticate(JWT)─────▶│                          │
  │                          │──verify JWT──────────────│
  │◀───authenticated─────────│                          │
  │                          │                          │
  │────join-room(eventId)────▶│                          │
  │                          │──publish join────────────▶│
  │◀───room-joined───────────│                          │
  │                          │                          │
  │────message-send──────────▶│                          │
  │                          │──publish msg─────────────▶│
  │                          │                          │
  │◀───message-received──────│◀─subscribe msg───────────│
  │                          │                          │
  │────disconnect────────────▶│                          │
  │                          │──publish offline─────────▶│

Presence System

  • Heartbeat: Client sends ping every 30 seconds
  • Timeout: Server marks offline after 60 seconds without ping
  • States: online, away, busy, offline
  • Persistence: Presence data stored in Redis with TTL

Caching Strategy

Redis Caching Layers

1. User Service Cache

// User profile cache
Key: `user:profile:${userId}`
TTL: 1 hour
Invalidation: On profile update
 
// User preferences cache
Key: `user:preferences:${userId}`
TTL: 24 hours
Invalidation: On preferences update

2. Event Service Cache

// Event details cache
Key: `event:${eventId}`
TTL: 30 minutes
Invalidation: On event update
 
// Featured events cache
Key: `events:featured`
TTL: 15 minutes
Invalidation: Periodic refresh
 
// Nearby events cache (geo-fenced)
Key: `events:nearby:${lat}:${lng}:${radius}`
TTL: 5 minutes
Invalidation: Time-based

3. Social Service Cache

// User connections cache
Key: `connections:${userId}`
TTL: 1 hour
Invalidation: On connection change
 
// Connection suggestions cache
Key: `suggestions:${userId}`
TTL: 6 hours
Invalidation: Periodic refresh

4. Session Cache

// JWT session cache
Key: `session:${sessionId}`
TTL: Same as JWT expiry
Invalidation: On logout
 
// Rate limit cache
Key: `ratelimit:${ip}:${endpoint}`
TTL: 15 minutes
Invalidation: Time-based

Cache Patterns

1. Cache-Aside (Lazy Loading):

async function getUserProfile(userId) {
  // Try cache first
  let profile = await redis.get(`user:profile:${userId}`);
 
  if (!profile) {
    // Cache miss - fetch from database
    profile = await User.findById(userId);
 
    // Store in cache
    await redis.setex(`user:profile:${userId}`, 3600, JSON.stringify(profile));
  }
 
  return JSON.parse(profile);
}

2. Write-Through:

async function updateUserProfile(userId, data) {
  // Update database
  const profile = await User.findByIdAndUpdate(userId, data, { new: true });
 
  // Update cache
  await redis.setex(`user:profile:${userId}`, 3600, JSON.stringify(profile));
 
  return profile;
}

3. Cache Invalidation:

async function invalidateUserCache(userId) {
  await redis.del(`user:profile:${userId}`);
  await redis.del(`user:preferences:${userId}`);
  await redis.del(`connections:${userId}`);
}

Security Architecture

Authentication & Authorization

JWT Structure

{
  "header": {
    "alg": "HS256",
    "typ": "JWT"
  },
  "payload": {
    "sub": "user-id",
    "email": "user@example.com",
    "username": "username",
    "role": "user",
    "permissions": ["read:events", "create:events"],
    "sessionId": "session-uuid",
    "iss": "flow-app",
    "aud": "flow-users",
    "iat": 1234567890,
    "exp": 1234568790
  }
}

Token Types

  • Access Token: 15 minutes expiry
  • Refresh Token: 7 days expiry

Security Levels

1. Public Routes (No authentication):

  • GET /api/events - List public events
  • GET /api/events/:id - View event details
  • POST /api/auth/register - User registration
  • POST /api/auth/login - User login

2. Protected Routes (Authentication required):

  • GET /api/users/profile - View own profile
  • PUT /api/users/profile - Update profile
  • POST /api/events - Create event
  • POST /api/social/* - All social endpoints

3. Role-Based Routes:

  • admin - Full platform access
  • moderator - Content moderation
  • user - Standard access

4. Permission-Based Routes:

  • edit_event - Can edit events
  • manage_attendees - Can manage event attendees
  • view_analytics - Can view analytics

Security Features

1. Password Security

  • Hashing: BCrypt with 12 rounds
  • Complexity: Minimum 8 characters
  • Reset: Secure token with 10-minute expiry
  • Lockout: After 5 failed attempts for 2 hours

2. Two-Factor Authentication

  • Method: TOTP (Time-based One-Time Password)
  • Backup Codes: 10 single-use backup codes
  • Secret Storage: Encrypted in database

3. Request Security

  • CORS: Whitelist of allowed origins
  • CSRF: Token-based protection
  • XSS: Input sanitization and output encoding
  • SQL Injection: Parameterized queries, MongoDB sanitization
  • NoSQL Injection: express-mongo-sanitize middleware
  • Rate Limiting: IP-based and user-based

4. Data Privacy

  • PII Encryption: Sensitive data encrypted at rest
  • Password: Never returned in API responses
  • Tokens: Stored hashed in database
  • Privacy Settings: User-controlled visibility
  • GDPR Compliance: Data export and deletion

5. Security Headers (Helmet.js)

Content-Security-Policy: default-src 'self'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

Row-Level Security (PostgreSQL/Supabase)

Profile Access:

-- Users can view all profiles
CREATE POLICY "Public profiles are viewable by everyone"
  ON public.profiles FOR SELECT USING (true);
 
-- Users can only update their own profile
CREATE POLICY "Users can update own profile"
  ON public.profiles FOR UPDATE USING (auth.uid() = id);

Event Access:

-- Public events visible to all
CREATE POLICY "Events are viewable by everyone"
  ON public.events FOR SELECT USING (true);
 
-- Only organizers can update events
CREATE POLICY "Organizers can update own events"
  ON public.events FOR UPDATE USING (auth.uid() = organizer_id);

Service Communication

Communication Patterns

1. Synchronous Communication (HTTP)

Use Case: Real-time data requirements

// Event Service calls User Service
const axios = require('axios');
 
async function getUserDetails(userId) {
  const response = await axios.get(
    `${USER_SERVICE_URL}/api/users/${userId}`,
    {
      headers: {
        'x-correlation-id': correlationId,
        'x-api-key': SERVICE_API_KEY
      },
      timeout: 5000,
      retry: 3
    }
  );
 
  return response.data;
}

2. Asynchronous Communication (Events)

Use Case: Non-blocking operations

// Event Service publishes event
const eventBus = require('./eventBus');
 
eventBus.publish('event.created', {
  eventId: event.id,
  organizerId: event.organizer,
  title: event.title,
  startDate: event.schedule.startDate
});
 
// Notification Service subscribes
eventBus.subscribe('event.created', async (data) => {
  await sendEventCreatedNotification(data);
});

3. Database-Level Integration

  • Shared database tables (PostgreSQL)
  • Event triggers and stored procedures
  • Materialized views for cross-service queries

Service Discovery

Currently using static configuration (environment variables):

services: {
  userService: process.env.USER_SERVICE_URL || 'http://localhost:3001',
  eventService: process.env.EVENT_SERVICE_URL || 'http://localhost:3002',
  socialService: process.env.SOCIAL_SERVICE_URL || 'http://localhost:3003'
}

Future: Consul or Kubernetes service discovery

Error Handling & Resilience

Circuit Breaker Pattern

const circuitBreaker = {
  failures: 0,
  threshold: 5,
  timeout: 60000,
  state: 'CLOSED', // CLOSED, OPEN, HALF_OPEN
 
  async call(fn) {
    if (this.state === 'OPEN') {
      throw new Error('Circuit breaker is OPEN');
    }
 
    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (error) {
      this.onFailure();
      throw error;
    }
  },
 
  onSuccess() {
    this.failures = 0;
    this.state = 'CLOSED';
  },
 
  onFailure() {
    this.failures++;
    if (this.failures >= this.threshold) {
      this.state = 'OPEN';
      setTimeout(() => {
        this.state = 'HALF_OPEN';
      }, this.timeout);
    }
  }
};

Retry Logic

const retry = async (fn, maxAttempts = 3, delay = 1000) => {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (attempt === maxAttempts) throw error;
      await new Promise(resolve => setTimeout(resolve, delay * attempt));
    }
  }
};

Deployment Architecture

Development Environment

# docker-compose.dev.yml
services:
  api-gateway:
    build: ./backend/api-gateway
    ports: ["3000:3000"]
    environment:
      - NODE_ENV=development
 
  user-service:
    build: ./backend/user-service
    ports: ["3001:3001"]
 
  event-service:
    build: ./backend/event-service
    ports: ["3002:3002"]
 
  mongodb:
    image: mongo:7
    ports: ["27017:27017"]
 
  redis:
    image: redis:7-alpine
    ports: ["6379:6379"]
 
  postgres:
    image: postgres:15
    ports: ["5432:5432"]

Production Considerations

Scalability

  • Horizontal Scaling: Multiple instances of each service
  • Load Balancing: Nginx or AWS ALB
  • Database Sharding: MongoDB sharding for high-volume collections
  • Read Replicas: PostgreSQL read replicas
  • Redis Cluster: For distributed caching

High Availability

  • Multi-AZ Deployment: Services across availability zones
  • Database Replication: MongoDB replica sets, PostgreSQL streaming replication
  • Health Checks: Kubernetes liveness and readiness probes
  • Graceful Shutdown: SIGTERM handling for zero-downtime deployments

Monitoring & Observability

  • Logging: Winston + CloudWatch / ELK Stack
  • Metrics: Prometheus + Grafana
  • Tracing: OpenTelemetry / Jaeger
  • Alerts: PagerDuty / Opsgenie

Backup & Recovery

  • Database Backups: Daily automated backups
  • Point-in-Time Recovery: PostgreSQL PITR
  • Disaster Recovery: Cross-region replication
  • Backup Retention: 30 days for production data

Performance Optimizations

Database Optimizations

MongoDB Indexes

// User Service
userSchema.index({ email: 1 });
userSchema.index({ username: 1 });
userSchema.index({ 'location.coordinates': '2dsphere' });
userSchema.index({ isActive: 1, isVerified: 1 });
 
// Event Service
eventSchema.index({ title: 'text', 'description.short': 'text' });
eventSchema.index({ 'schedule.startDate': 1, 'schedule.endDate': 1 });
eventSchema.index({ category: 1, status: 1, 'schedule.startDate': 1 });
eventSchema.index({ 'venue.physical.customLocation.coordinates': '2dsphere' });

PostgreSQL Indexes

-- Geospatial indexes
CREATE INDEX idx_events_geo ON public.events USING GIST (geo_point);
CREATE INDEX idx_venues_geo ON public.venues USING GIST (geo_point);
 
-- Compound indexes
CREATE INDEX idx_events_status_date ON public.events(status, start_date);
CREATE INDEX idx_event_attendees_event ON public.event_attendees(event_id, status);

Caching Strategy Summary

  • User Profiles: 1 hour TTL
  • Events: 30 minutes TTL
  • Featured Events: 15 minutes TTL
  • API Responses: 5-60 minutes based on volatility
  • Session Data: Same as JWT expiry

Request Optimization

  • Compression: Gzip compression for all responses
  • Pagination: Default 20 items, max 100
  • Field Selection: Sparse fieldsets to reduce payload
  • Eager Loading: Population of related documents
  • Connection Pooling: MongoDB max 10 connections per service

Future Enhancements

  1. Service Mesh: Istio for advanced traffic management
  2. Message Queue: RabbitMQ / Apache Kafka for event-driven architecture
  3. GraphQL Gateway: Apollo Federation for flexible querying
  4. API Versioning: Comprehensive v2 API with breaking changes
  5. CDN Integration: CloudFront / Cloudflare for static assets
  6. Elasticsearch: Advanced search and analytics
  7. Machine Learning: Enhanced recommendation engine
  8. Blockchain: NFT ticketing and event credentials

Document Version: 1.0 Last Updated: 2024-03-10 Maintained By: Flow Development Team