Appearance
Architecture
Nexus is built with a modern, scalable architecture designed to handle millions of notifications across multiple channels. This document provides an overview of the system architecture and key design decisions.
System Overview
mermaid
graph TB
subgraph "Client Applications"
WEB[Web App]
MOB[Mobile App]
API[API Clients]
end
subgraph "Nexus Platform"
subgraph "API Layer"
APIGW[API Gateway<br/>Hono + Bun]
AUTH[Auth Service<br/>JWT + API Keys]
end
subgraph "Core Services"
WF[Workflow Engine]
TMPL[Template Service]
QUEUE[Message Queue]
SCHED[Scheduler]
end
subgraph "Delivery Services"
EMAIL[Email Service]
SMS[SMS Service]
PUSH[Push Service]
INAPP[In-App Service]
WEBHOOK[Webhook Service]
end
subgraph "Data Layer"
PG[(PostgreSQL<br/>Primary DB)]
REDIS[(Redis<br/>Cache & Queue)]
S3[(S3<br/>File Storage)]
end
end
subgraph "External Providers"
ESP[Email Providers<br/>SendGrid, SES, etc.]
SMSP[SMS Providers<br/>Twilio, SNS, etc.]
PUSHP[Push Providers<br/>FCM, APNS]
end
WEB --> APIGW
MOB --> APIGW
API --> APIGW
APIGW --> AUTH
AUTH --> WF
WF --> TMPL
WF --> QUEUE
WF --> SCHED
QUEUE --> EMAIL
QUEUE --> SMS
QUEUE --> PUSH
QUEUE --> INAPP
QUEUE --> WEBHOOK
EMAIL --> ESP
SMS --> SMSP
PUSH --> PUSHP
WF --> PG
TMPL --> PG
QUEUE --> REDIS
TMPL --> S3Technology Stack
Backend
- Runtime: Bun (high-performance JavaScript runtime)
- API Framework: Hono (lightweight, fast web framework)
- Database: PostgreSQL with Prisma ORM
- Cache: Redis for caching and queuing
- File Storage: S3-compatible object storage
Frontend
- Framework: Next.js 15 with App Router
- UI Components: React 19 with Radix UI
- Styling: Tailwind CSS
- State Management: Zustand + TanStack Query
- Real-time: WebSockets for live updates
Infrastructure
- Container: Docker with multi-stage builds
- Orchestration: Kubernetes-ready
- Monitoring: OpenTelemetry integration
- CI/CD: GitHub Actions
Core Components
1. API Gateway
The API Gateway is the entry point for all client requests. Built with Hono and running on Bun, it provides:
- Authentication: JWT tokens and API key validation
- Rate Limiting: Configurable per-organization limits
- Request Validation: Zod schema validation
- Error Handling: Consistent error responses
- OpenAPI Documentation: Auto-generated from routes
typescript
// Example API endpoint
app.post('/v1/events/trigger',
rateLimiter({ max: 100, window: '1m' }),
authenticate(),
validate(TriggerEventSchema),
async (c) => {
const event = await triggerEvent(c.req.valid('json'))
return c.json({ data: event })
}
)2. Workflow Engine
The heart of Nexus, responsible for:
- Workflow Execution: Processes multi-step notification flows
- Conditional Logic: Evaluates conditions and filters
- Delay Management: Handles timed delays between steps
- Retry Logic: Automatic retries with exponential backoff
- State Management: Tracks workflow execution state
typescript
// Workflow execution flow
async function executeWorkflow(workflow: Workflow, event: Event) {
for (const step of workflow.steps) {
if (await evaluateConditions(step.conditions, event)) {
await executeStep(step, event)
if (step.delay) {
await scheduleDelayedExecution(step.delay)
}
}
}
}3. Template Service
Manages notification templates with:
- Template Storage: Database-backed with S3 for assets
- Variable Interpolation: Handlebars-style variable replacement
- Multi-format Support: HTML, plain text, JSON
- Localization: Multi-language template support
- Caching: Redis caching for compiled templates
4. Message Queue
Built on Redis Streams/BullMQ for:
- Reliable Delivery: At-least-once delivery guarantee
- Priority Queues: High-priority notifications processed first
- Dead Letter Queue: Failed messages for investigation
- Batch Processing: Efficient bulk operations
- Real-time Processing: Low-latency message handling
5. Delivery Services
Channel-specific services that:
- Provider Abstraction: Unified interface for multiple providers
- Failover: Automatic provider switching on failure
- Delivery Tracking: Status updates and webhooks
- Provider-specific Features: Utilize unique provider capabilities
Data Model
Multi-Tenant Architecture
sql
-- Organizations (top-level tenant)
CREATE TABLE organizations (
id UUID PRIMARY KEY,
name VARCHAR(255),
created_at TIMESTAMP
);
-- Environments (dev/staging/prod isolation)
CREATE TABLE environments (
id UUID PRIMARY KEY,
organization_id UUID REFERENCES organizations(id),
name VARCHAR(50),
type ENUM('development', 'staging', 'production')
);
-- All other tables reference environment_id for isolation
CREATE TABLE workflows (
id UUID PRIMARY KEY,
environment_id UUID REFERENCES environments(id),
-- ... workflow fields
);Event Sourcing
All notification events are stored for:
- Audit Trail: Complete history of all operations
- Debugging: Replay events to debug issues
- Analytics: Generate insights from event data
- Compliance: Meet data retention requirements
typescript
interface NotificationEvent {
id: string
type: 'triggered' | 'sent' | 'delivered' | 'failed' | 'opened'
timestamp: Date
subscriberId: string
workflowId: string
channelId: string
metadata: Record<string, any>
}Scalability Patterns
1. Horizontal Scaling
All services are stateless and can be scaled horizontally:
yaml
# Kubernetes deployment example
apiVersion: apps/v1
kind: Deployment
metadata:
name: nexus-api
spec:
replicas: 3 # Scale based on load
selector:
matchLabels:
app: nexus-api
template:
spec:
containers:
- name: api
image: nexus/api:latest
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"2. Database Optimization
- Read Replicas: Separate read/write workloads
- Connection Pooling: Efficient database connections
- Indexing Strategy: Optimized for common queries
- Partitioning: Time-based partitioning for events
3. Caching Strategy
Multi-layer caching approach:
typescript
// L1: In-memory cache (process level)
const memoryCache = new LRUCache({ max: 1000 })
// L2: Redis cache (shared)
const redisCache = new Redis()
// L3: CDN cache (for static assets)
// Configured at infrastructure level
async function getCachedTemplate(id: string) {
// Check L1
let template = memoryCache.get(id)
if (template) return template
// Check L2
template = await redisCache.get(`template:${id}`)
if (template) {
memoryCache.set(id, template)
return template
}
// Load from database
template = await db.template.findUnique({ where: { id } })
// Cache in L2 and L1
await redisCache.setex(`template:${id}`, 3600, template)
memoryCache.set(id, template)
return template
}Security Architecture
1. Authentication & Authorization
- API Keys: Organization-level authentication
- JWT Tokens: User session management
- RBAC: Role-based access control
- Environment Isolation: Complete data separation
2. Data Encryption
- At Rest: AES-256-GCM encryption for sensitive data
- In Transit: TLS 1.3 for all communications
- Key Management: Rotating encryption keys
- PII Protection: Automatic PII detection and masking
3. Security Headers
typescript
// Security middleware
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true,
},
}))Monitoring & Observability
1. Metrics
- Application Metrics: Request rates, latencies, errors
- Business Metrics: Notifications sent, delivery rates
- Infrastructure Metrics: CPU, memory, disk usage
2. Logging
Structured logging with correlation IDs:
typescript
logger.info('Notification sent', {
correlationId: ctx.correlationId,
subscriberId: subscriber.id,
workflowId: workflow.id,
channel: 'email',
provider: 'sendgrid',
duration: 145,
})3. Tracing
OpenTelemetry integration for distributed tracing:
typescript
const tracer = trace.getTracer('nexus-api')
async function triggerWorkflow(data: TriggerData) {
const span = tracer.startSpan('workflow.trigger')
try {
span.setAttributes({
'workflow.id': data.workflowId,
'subscriber.id': data.subscriberId,
})
// Workflow execution logic
const result = await executeWorkflow(data)
span.setStatus({ code: SpanStatusCode.OK })
return result
} catch (error) {
span.recordException(error)
span.setStatus({ code: SpanStatusCode.ERROR })
throw error
} finally {
span.end()
}
}High Availability
1. Redundancy
- Multi-AZ Deployment: Services across availability zones
- Database Replication: Primary-replica setup
- Provider Redundancy: Multiple providers per channel
2. Disaster Recovery
- Automated Backups: Daily database backups
- Point-in-Time Recovery: Restore to any point
- Geo-Replication: Cross-region replication
- RTO/RPO: 1 hour RTO, 5 minute RPO
3. Load Balancing
nginx
upstream nexus_api {
least_conn;
server api1.nexus.internal:3001 weight=10;
server api2.nexus.internal:3001 weight=10;
server api3.nexus.internal:3001 weight=10;
# Health checks
health_check interval=5s fails=3 passes=2;
}Performance Optimization
1. Connection Pooling
typescript
// Database connection pool
const prisma = new PrismaClient({
datasources: {
db: {
url: DATABASE_URL,
},
},
connectionLimit: 20,
})
// Redis connection pool
const redis = new Redis({
host: REDIS_HOST,
port: REDIS_PORT,
maxRetriesPerRequest: 3,
enableReadyCheck: true,
lazyConnect: true,
})2. Batch Processing
typescript
// Batch notification sending
async function sendBatchNotifications(notifications: Notification[]) {
const chunks = chunk(notifications, 100) // Process 100 at a time
await Promise.all(
chunks.map(chunk =>
queue.addBulk(
chunk.map(n => ({
name: 'send-notification',
data: n,
opts: { priority: n.priority }
}))
)
)
)
}3. Response Compression
typescript
// Brotli compression for API responses
app.use(compress({
encoding: 'br',
threshold: 1024, // Only compress responses > 1KB
}))Development Workflow
1. Local Development
bash
# Start all services locally
docker-compose up -d
# Run migrations
bun run db:push
# Start development servers
bun run dev2. Testing Strategy
- Unit Tests: Core business logic
- Integration Tests: API endpoints
- E2E Tests: Critical user flows
- Load Tests: Performance validation
3. Deployment Pipeline
yaml
# GitHub Actions workflow
name: Deploy
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v1
- run: bun install
- run: bun test
build:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build Docker image
run: docker build -t nexus/api:${{ github.sha }} .
- name: Push to registry
run: docker push nexus/api:${{ github.sha }}
deploy:
needs: build
runs-on: ubuntu-latest
steps:
- name: Deploy to Kubernetes
run: |
kubectl set image deployment/nexus-api \
api=nexus/api:${{ github.sha }}Future Considerations
1. Event Streaming
- Kafka integration for high-volume events
- Real-time analytics pipeline
- Event replay capabilities
2. Machine Learning
- Optimal send time prediction
- Engagement rate optimization
- Anomaly detection
3. Edge Computing
- CDN-based notification delivery
- Regional processing nodes
- Reduced latency for global users