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
- System Overview
- Microservices Architecture
- Technology Stack
- Database Architecture
- API Gateway
- Real-time Architecture
- Caching Strategy
- Security Architecture
- Service Communication
- 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 registrationPOST /api/v1/auth/login- User authenticationPOST /api/v1/auth/refresh- Refresh access tokenPOST /api/v1/auth/logout- User logoutGET /api/v1/users/:id- Get user profilePUT /api/v1/users/:id- Update user profileGET /api/v1/profiles/:id- Get extended profilePUT /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 filtersPOST /api/events- Create new eventGET /api/events/:id- Get event detailsPUT /api/events/:id- Update eventDELETE /api/events/:id- Delete eventPOST /api/events/:id/attend- Register for eventPOST /api/events/:id/like- Like eventGET /api/events/nearby- Find nearby eventsGET /api/events/featured- Get featured eventsGET /api/venues- List venuesPOST /api/venues- Create venueGET /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 responseaccepted- Connection establisheddeclined- Request declinedblocked- User blockedcancelled- Request cancelled by requester
API Endpoints:
POST /api/connections/request- Send connection requestPOST /api/connections/:id/accept- Accept connectionPOST /api/connections/:id/decline- Decline connectionGET /api/connections- Get user connectionsGET /api/connections/suggestions- Get suggested connectionsGET /api/groups- List groupsPOST /api/groups- Create groupPOST /api/posts- Create postGET /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 requestconnection_accepted- Friend request acceptedgroup_invitation- Group invitationpost_like- Post likedpost_comment- Comment on postevent_invitation- Event invitationevent_reminder- Event reminderevent_update- Event details changedsystem_announcement- System-wide announcementsecurity_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 notificationGET /api/notifications- Get user notificationsPUT /api/notifications/:id/read- Mark as readDELETE /api/notifications/:id- Delete notificationGET /api/notifications/unread/count- Get unread countGET /api/templates- List notification templatesPOST /api/templates- Create templateGET /api/preferences- Get user preferencesPUT /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 connecteddisconnect- Client disconnectedauthenticate- JWT authentication
-
Message Events:
message:send- Send messagemessage:received- Message receivedmessage:read- Mark message as readtyping:start- User started typingtyping:stop- User stopped typing
-
Presence Events:
presence:online- User came onlinepresence:offline- User went offlinepresence:away- User is awaypresence:busy- User is busy
-
Room Events:
room:join- Join chat roomroom:leave- Leave chat roomroom: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 (extendsauth.users)events- Event details with geospatial dataevent_attendees- Event registrationsvenues- Venue information with geospatial datatags- Event and content tagscrews- Social groups anchored to locations/eventscrew_members- Crew membershipscrew_feedback- Peer reviews and karma system
Data Consistency Strategy
-
Eventual Consistency:
- MongoDB and PostgreSQL operate independently
- Critical data (auth, payments) in PostgreSQL
- Performance-oriented features in MongoDB
-
Synchronization:
- User creation triggers profile creation in both databases
- Event updates propagated to both systems
- Background jobs handle reconciliation
-
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:
- WebSocket (primary)
- 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 update2. 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-based3. 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 refresh4. 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-basedCache 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 eventsGET /api/events/:id- View event detailsPOST /api/auth/register- User registrationPOST /api/auth/login- User login
2. Protected Routes (Authentication required):
GET /api/users/profile- View own profilePUT /api/users/profile- Update profilePOST /api/events- Create eventPOST /api/social/*- All social endpoints
3. Role-Based Routes:
admin- Full platform accessmoderator- Content moderationuser- Standard access
4. Permission-Based Routes:
edit_event- Can edit eventsmanage_attendees- Can manage event attendeesview_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; preloadRow-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
- Service Mesh: Istio for advanced traffic management
- Message Queue: RabbitMQ / Apache Kafka for event-driven architecture
- GraphQL Gateway: Apollo Federation for flexible querying
- API Versioning: Comprehensive v2 API with breaking changes
- CDN Integration: CloudFront / Cloudflare for static assets
- Elasticsearch: Advanced search and analytics
- Machine Learning: Enhanced recommendation engine
- Blockchain: NFT ticketing and event credentials
Document Version: 1.0 Last Updated: 2024-03-10 Maintained By: Flow Development Team