Architecture
Understanding SimpleNS's system architecture, components, and design decisions.
High-Level Architecture

SimpleNS follows an event-driven, microservices-inspired architecture where each component has a specific responsibility. The system is built around the outbox pattern for reliability and uses Kafka for event streaming.
What runs where?
SimpleNS is split into two logical halves to make deployment flexible.
| Concept | Docker Compose File | Services Included | Purpose |
|---|---|---|---|
| Application | docker-compose/docker-compose.master.yaml | api, worker, processor, recovery, dashboard | The Node.js services that make up the SimpleNS logic. All of them are stateless and can be scaled horizontally. |
| Infrastructure | docker-compose/docker-compose.infra.yaml | mongodb, redis, kafka, loki, grafana | The stateful databases and event buses. You can self-host these or use managed cloud equivalents (e.g., MongoDB Atlas, AWS MSK, ElastiCache). |
Local & All-in-One Deployment
In simplens-core, all compose files live under docker-compose/ (docker-compose.master.yaml, docker-compose.infra.yaml, docker-compose.local.yaml, and docker-compose.dev.yaml).
Core Principles
Separation of Concerns
Orchestration (SimpleNS Core) handles retries, rate limiting, scheduling, recovery. Delivery (Plugins) handles actual notification sending via provider APIs.
Plugin-Based Extensibility
Swap providers without changing application code. Community-driven ecosystem with easy custom integrations.
Horizontal Scalability
Scale each component independently with partition-based parallelism and load distribution across workers.
Fault Tolerance
Outbox pattern prevents message loss. Crash recovery for stuck notifications. Automatic retries with exponential backoff.
System Components
API Server
Responsibility: REST API for notification ingestion
Key Features:
/api/notification- Send a single notification to a single recipient through multiple channels/api/notification/batch- Send the same notification to multiple recipients through multiple channels (batch limit configurable live in Dashboard → Settings (/settings))- Request validation using Zod schemas
- Bearer token authentication
Technology: Express.js, TypeScript
Scaling: Multiple instances behind load balancer
Data Flow:
Background Worker
Responsibility: Polls outbox, polls outbox_status, publishes to Kafka, updates status
Key Features:
- Polls MongoDB outbox table every 5 seconds (configurable)
- Publishes notifications from outbox collection to appropriate Kafka topics
- Consumes status updates from notification_status kafka topic
- Updates notification status in MongoDB
- Sends webhook callbacks
- Handles worker crashes via claim timeouts
- Polls MongoDB Outobx Status collection every 5 seconds (configurable) and publishes status to notification_status kafka topic. (Auto resolution of ghost deliveries)
Technology: Node.js, MongoDB, Kafka Producer/Consumer
Scaling: Multiple worker instances (distributed claiming prevents duplicates)
Data Flow:
Ghost Delivery and Permanently Failed Status Update Flow
Unified Notification Processor
Responsibility: Plugin-based notification delivery with rate limiting and automatic fallback
Key Features:
- Dynamically loads and hot-reloads plugins, encrypted provider credentials, and channel routings from MongoDB via Redis Pub/Sub (
PluginSyncService,ProviderManagerService,ChannelRoutingService) - Resolves and downloads file attachments (
StorageService.downloadFile) before dispatch, retrying via delayed queue if download fails - Consumes from channel-specific Kafka topics
- Per-provider rate limiting (Token Bucket Algorithm)
- Exponential backoff retries (live-configurable via
DynamicConfigService, default: 5 attempts) - Automatic fallback to secondary provider when default provider fails with non-retryable error
- Schema validation and single-render template variable substitution at dispatch
- Idempotency using Redis cache
- Processing locks via Redis (TTL: 2 minutes)
- Publishes delivery status to
notification_statustopic
Technology: Node.js, Kafka Consumer, Redis, Plugin SDK
Scaling:
- Multiple processor instances per channel
- Kafka partition-based parallelism
- Can run channel-specific processors (e.g., only email)
Configuration:
PROCESSOR_CHANNEL=all # or 'email', 'sms', etc.Retry counts and processing TTLs are configured live in Dashboard → Settings (/settings) (DynamicConfigService).
Provider Fallback (Cascading Chain & Explicit Provider)
Channel routing stores a default_provider_id and an ordered list of fallback_provider_ids: string[] (e.g., e-1 -> e-2 -> e-3).
- Default routing: Try
default_provider_idfirst. - Immediate cascading fallback (
tryFallback): If a provider fails with a non-retryable error, SimpleNS iterates sequentially through the remainingfallback_provider_idsin order (skipping missing or rate-limited providers) until one succeeds or all fail. - Retry-budget handoff (
resolveFallbackProviderId): On retryable or rate-limit errors, onceretry_count + 1 > MAX_RETRY_COUNT, SimpleNS advances to the next provider in the chain via the delayed queue withretry_count = 0. - Explicit
provideroverride (e.g.,provider: ["e-3"]):- Only providers configured in the channel's routing (
default_provider_idorfallback_provider_ids) are eligible for that channel. - If you pass
provider: ["e-3"]ande-3is not in that channel's routing (even ife-3is enabled and active), SimpleNS does not usee-3and instead routes to the channel'sdefault_provider_id(e-1), cascading throughfallback_provider_idsif needed. - If the explicit provider is in
fallback_provider_ids, it starts there and only cascades to providers after it in the list.
- Only providers configured in the channel's routing (
Retryable errors (for example rate limit or timeout) do not use immediate fallback first. They follow retry/backoff and hand off to the next fallback provider only after the current provider's retry budget is exhausted.
Data Flow:
Fallback Routing Modes
SimpleNS applies two separate fallback mechanisms:
How Fallback Provider Is Resolved
Fallback resolution walks the ordered fallback_provider_ids chain and guards against circular routing:
Delayed Re-Entry After Handoff
Handoff is asynchronous and re-enters through the delayed pipeline:
Offset Commit Semantics
When handoff is scheduled successfully:
- Unified consumer returns success for the current Kafka message.
- Offset is committed.
- Continuation is represented by the new delayed event.
If handoff cannot be scheduled, terminal failure handling is used.
Delayed Processor
Responsibility: Handles scheduled notifications using two-phase commit
Key Features:
- Redis ZSET-based delay queue (score = Unix timestamp)
- Two-phase commit prevents message loss during crashes
- Polls every 1 second for due notifications (configurable)
- Fetches batch of due notifications (default: 10)
- Publishes to appropriate channel topics
- Handles poller failures with retries and exponential backoff
Two-Phase Commit Implementation:
- Claim Phase: Atomically lock events for this worker using
SET NX(prevents duplicate processing) - Process Phase: Publish to target Kafka topic
- Confirm Phase: Remove from queue ONLY after successful publish
If a worker crashes between claim and confirm, the claim expires after 60 seconds and another worker can pick up the event.
Technology: Node.js, Redis ZSET + Lua Scripts, Kafka Producer
Scaling: Multiple Delayed Processor instances (distributed claiming prevents duplicates)
Data Flow:
Recovery Service
Responsibility: Detects orphaned/stuck notifications and creates alerts
Key Features:
- Runs every 60 seconds (configurable)
- Detects notifications stuck in
processingstate (timeout: 5 minutes) - Detects notifications stuck in
pendingstate (timeout: 5 minutes) - Creates alerts in MongoDB for manual intervention
- Cleanup of resolved alerts (retention: 24 hours)
- Cleanup of processed status outbox entries
Technology: Node.js, MongoDB, Cron-like polling
Scaling: Stateless and horizontally scalable. Uses atomic MongoDB findOneAndUpdate claiming (recovery_claimed_by: WORKER_ID, recovery_claimed_at) with RECOVERY_CLAIM_TIMEOUT_MS stale-claim recovery across stuck processing, orphaned pending, and alert auto-resolution.
Alert Types:
ghost_delivery- Status mismatch between Redis and MongoDB (notification delivered but status not updated)stuck_processing- Notification stuck in processing state beyond thresholdorphaned_pending- Notification never picked up by processor
Data Flow:

Admin Dashboard (Essential Control Plane)
Responsibility: Essential web-based onboarding, configuration, storage, and monitoring control plane
Key Features:
- First-launch
/setuponboarding and guided tour - Plugin catalog install/version/uninstall, custom npm registry/scope auth, encrypted provider config, and channel routing (
/plugins) - Scoped API key management (
/keys) and live operational settings (/settings) - MinIO / S3-compatible object storage setup (
/storage) and attachment uploader in/send&/payload-studio - Events explorer with attachment metadata & downloads (
/events,/events/[id]) - Failed events workspace with edit & requeue and bulk retry (
/failed) - Notification templates (
/templates), system alerts (/alerts), admin alert channels (/admin-alerts), and analytics (/analytics) - Authentication via backend JWT/cookie sessions (
JWT_SECRET)
Technology: Next.js, React, shadcn/ui, SimpleNS Core APIs
Scaling: Multiple instances (stateless, JWT cookie sessions)
Security & Health Probes
- Unified Access Control (
accessControl): Separates Admin JWT/cookie sessions from scoped client API keys. - SSRF Protection (
safe-outbound-url/safe-http-client): Validates productionwebhook_urlcallbacks, Discord/Telegram alert destinations, and test endpoints against private/internal network ranges. - Redis-Backed IP Rate Limiting:
generalRateLimiterfor API traffic and strictauthRateLimiterfor/api/auth/*(both live-tunable in/settings, withTRUST_PROXYrejectingtrue). - Kubernetes Probes: Dedicated internal
probeServerfor liveness/readiness checks alongside/api/health*.
Infrastructure Components
MongoDB
Persistent storage for notifications, outbox, and alerts. Replica set required.
Kafka
Event streaming and message queue with channel-specific topics.
Redis
Caching, delay queue, rate limiting, and processing locks.
Loki + Grafana
Centralized logging and visualization across all services.
MongoDB
Purpose: Persistent storage for notifications, outbox, alerts
Configuration:
- Replica set required (minimum 1 node for dev, 3 for production)
- Collections:
notifications- Notification documentsoutbox- Outbox pattern entriesalerts- Recovery alertsstatus_outbox- Status update outbox
- Indexes for performance on
status,created_at,notification_id
Kafka
Purpose: Event streaming and message queue
Topics:
{channel}_notification- Channel-specific (e.g.,email_notification,sms_notification)delayed_notification- Scheduled notificationsnotification_status- Delivery status updates
Partitioning Strategy:
- Channel topics: Dynamically configured per channel in Dashboard → Channel Routing (default:
6partitions). SimpleNS creates and expands topic partitions automatically (expandTopicPartitions—note that Kafka partitions can be increased, never decreased). - System topics:
DELAYED_PARTITION(default1) andNOTIFICATION_STATUS_PARTITION(default1) remain static.envvariables. - More partitions = more parallel consumers; partitioned by
notification_idhash for ordering within the same notification.
Configuration:
# .env (system topics only; channel partitions are set in Dashboard → Channel Routing)
DELAYED_PARTITION=1
NOTIFICATION_STATUS_PARTITION=1Redis
Purpose: Caching, delay queue, rate limiting
Use Cases:
1. Delay Queue (ZSET)
ZADD delay_queue <scheduled_timestamp> <notification_json>2. Idempotency Cache
SET idempotency:<notification_id> <result> EX 864003. Rate Limiting (Token Bucket)
HSET rate_limit:<provider_id> tokens <count> last_refill <timestamp>4. Processing Locks
SET processing:<notification_id> <worker_id> EX 120Loki + Grafana
Purpose: Centralized logging and visualization
Configuration:
- All services send logs to Loki via winston-loki
- Grafana datasource configured for Loki
- Labels:
service,level,notification_id - Query examples:
{service="api"}
{service="notification-processor", level="error"}
{notification_id="abc123"}Data Flow
Immediate Notification Flow

Scheduled Notification Flow

Retry Flow

Recovery Flow

Scalability Model
Horizontal Scaling
API Server
- Run multiple instances behind load balancer (NGINX, ALB)
- Stateless (no in-memory session)
- Share same MongoDB and Kafka
Background Worker
- Multiple instances supported
- Distributed claiming via MongoDB (
worker_id+claimed_at) - Claim timeout handles crashed workers
Notification Processor
- Scale independently per channel
- Kafka consumer group ensures no duplicate processing
- Increase instances to reduce consumer lag
Delayed Processor
- Typically 1-2 instances
- Redis atomic operations prevent duplicates
- Low CPU usage, minimal scaling needed
Scaling Guidelines
Metric: Kafka Consumer Lag
# Check in Kafka UI or CLI
kafka-consumer-groups.sh --bootstrap-server localhost:9092 \
--describe --group notification-processor-emailAction: Scale up if lag > 1000
docker compose -f docker-compose/docker-compose.master.yaml up -d --scale notification-processor=5Increase Kafka Partitions:
Update the partition count for the channel in Dashboard → Channel Routing (default 6). SimpleNS dynamically expands the Kafka topic partitions (expandTopicPartitions—partitions can be increased, not decreased).
Processor per Channel:
# Instead of PROCESSOR_CHANNEL=all
# Run separate processors:
PROCESSOR_CHANNEL=email # update in .env
docker compose -f docker-compose/docker-compose.master.yaml up -d notification-processorPerformance Considerations
Increase Throughput:
- Batch Size: Increase
OUTBOX_BATCH_SIZEfor high throughput - Kafka Partitions: Increase partitions for parallel processing
- Worker Count: Scale processors horizontally
- MongoDB: Add indexes on frequently queried fields
Reduce Latency:
- Polling Interval: Reduce outbox polling interval (trade-off: DB load)
- Processing TTL: Reduce lock TTL for faster failure detection
- Network: Colocate services in same region/VPC
- Redis: Use cluster mode for high cache throughput
Optimize Resources:
- Rate Limits: Adjust per-provider
maxTokensandrefillRate - Connection Pools: Tune MongoDB and Redis connection pools
- Memory: Monitor Kafka consumer memory for large message payloads
- Disk: Configure Kafka retention policies
Docs