SimpleNS LogoDocs

Architecture

Understanding SimpleNS's system architecture, components, and design decisions.


High-Level Architecture

SimpleNS HLD Diagram

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.

ConceptDocker Compose FileServices IncludedPurpose
Applicationdocker-compose/docker-compose.master.yamlapi, worker, processor, recovery, dashboardThe Node.js services that make up the SimpleNS logic. All of them are stateless and can be scaled horizontally.
Infrastructuredocker-compose/docker-compose.infra.yamlmongodb, redis, kafka, loki, grafanaThe 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_status topic

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).

  1. Default routing: Try default_provider_id first.
  2. Immediate cascading fallback (tryFallback): If a provider fails with a non-retryable error, SimpleNS iterates sequentially through the remaining fallback_provider_ids in order (skipping missing or rate-limited providers) until one succeeds or all fail.
  3. Retry-budget handoff (resolveFallbackProviderId): On retryable or rate-limit errors, once retry_count + 1 > MAX_RETRY_COUNT, SimpleNS advances to the next provider in the chain via the delayed queue with retry_count = 0.
  4. Explicit provider override (e.g., provider: ["e-3"]):
    • Only providers configured in the channel's routing (default_provider_id or fallback_provider_ids) are eligible for that channel.
    • If you pass provider: ["e-3"] and e-3 is not in that channel's routing (even if e-3 is enabled and active), SimpleNS does not use e-3 and instead routes to the channel's default_provider_id (e-1), cascading through fallback_provider_ids if needed.
    • If the explicit provider is in fallback_provider_ids, it starts there and only cascades to providers after it in the list.

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:

  1. Claim Phase: Atomically lock events for this worker using SET NX (prevents duplicate processing)
  2. Process Phase: Publish to target Kafka topic
  3. 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 processing state (timeout: 5 minutes)
  • Detects notifications stuck in pending state (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 threshold
  • orphaned_pending - Notification never picked up by processor

Data Flow:

Recovery Flow

Admin Dashboard (Essential Control Plane)

Responsibility: Essential web-based onboarding, configuration, storage, and monitoring control plane

Key Features:

  • First-launch /setup onboarding 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 production webhook_url callbacks, Discord/Telegram alert destinations, and test endpoints against private/internal network ranges.
  • Redis-Backed IP Rate Limiting: generalRateLimiter for API traffic and strict authRateLimiter for /api/auth/* (both live-tunable in /settings, with TRUST_PROXY rejecting true).
  • Kubernetes Probes: Dedicated internal probeServer for 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 documents
    • outbox - Outbox pattern entries
    • alerts - Recovery alerts
    • status_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 notifications
  • notification_status - Delivery status updates

Partitioning Strategy:

  • Channel topics: Dynamically configured per channel in Dashboard → Channel Routing (default: 6 partitions). SimpleNS creates and expands topic partitions automatically (expandTopicPartitions—note that Kafka partitions can be increased, never decreased).
  • System topics: DELAYED_PARTITION (default 1) and NOTIFICATION_STATUS_PARTITION (default 1) remain static .env variables.
  • More partitions = more parallel consumers; partitioned by notification_id hash 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=1

Redis

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 86400

3. Rate Limiting (Token Bucket)

HSET rate_limit:<provider_id> tokens <count> last_refill <timestamp>

4. Processing Locks

SET processing:<notification_id> <worker_id> EX 120

Loki + 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

Immediate Notification Flow

Scheduled Notification Flow

Scheduled Notification Flow

Retry Flow

Retry Flow

Recovery 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-email

Action: Scale up if lag > 1000

docker compose -f docker-compose/docker-compose.master.yaml up -d --scale notification-processor=5

Increase 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-processor

Performance Considerations

Increase Throughput:

  • Batch Size: Increase OUTBOX_BATCH_SIZE for 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 maxTokens and refillRate
  • Connection Pools: Tune MongoDB and Redis connection pools
  • Memory: Monitor Kafka consumer memory for large message payloads
  • Disk: Configure Kafka retention policies

On this page