# postalserver/postal architecture

> Architecture diagram of the GitHub repository postalserver/postal, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-06-18). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/postalserver/postal
- Repository: https://github.com/postalserver/postal

## Overview

##### Project Type and Purpose
- This is Postal: a self-hosted, full-featured mail server written in Ruby on Rails. It provides:
- Web UI and HTTP APIs for managing domains, credentials, routes, servers, webhooks, etc.
- An SMTP server to accept incoming mail.
- SMTP client functionality to deliver outbound mail.
- Background workers and scheduled tasks for queue processing, webhooks, cleanup, stats.
- A specialized message-database layer (lib/postal/message_db) for high-volume message storage and live stats.
- Integrations with DNS, DKIM signing, spam-inspectors (ClamAV, SpamAssassin, Rspamd), Prometheus metrics, and external webhook targets.

A. User & API Clients
- Web browsers or CLI tools hit the Rails Web UI and HTTP API (app/controllers, config/routes.rb).
- Legacy API endpoints under `/legacy_api`.
B. Rails Application
- Controllers → Services/Models → Primary SQL Database (config/database.yml).
- Uses ActiveRecord for configuration data (domains, credentials, users, routes, etc.).
- Hosts an embedded health HTTP server for metrics (app/util/health_server.rb).
C. Message Database
- Separate message‐DB library (lib/postal/message_db) with its own schema optimized for messages, deliveries, clicks, suppressions, webhooks.
- Used by both the Rails app and background workers for message storage and live stats.
D. SMTP Server
- Custom SMTP server implementation (app/lib/smtp_server) listens for SMTP traffic from external SMTP clients.
- Performs SMTP handshake, start‐tls, authentication, and hands off messages to the queue.
E. SMTP Client
- Custom SMTP client (app/lib/smtp_client) used by the delivery subsystem to send mail out to remote mail servers.
F. HTTP Sender
- HTTP‐based endpoints (app/lib/senders/http_sender) for delivering inbound mail via webhooks.
G. Message Queue & Workers
- In‐process queue or external queue (depending on deployment) managed by `message_dequeuer` (app/lib/message_dequeuer) and background workers (app/lib/worker).
- Worker jobs: `process_queued_messages_job`, `process_webhook_requests_job`.
- Scheduled tasks (app/scheduled_tasks) for DNS checks, retention, cleanup, stats, notifications.
H. External Integrations
- DNS Resolver (app/lib/dns_resolver) for domain verification and routing lookups.
- DKIM signer (app/lib/dkim_header & lib/postal/signer).
- Spam inspections via plug-ins in lib/postal/message_inspectors.
- Webhook delivery to user‐configured URLs.
- Prometheus metrics endpoint.
I. Persistence & Configuration
- Primary relational database (PostgreSQL/MySQL) for Rails data.
- File-based config (YAML, ENV vars), Docker & Helm manifests, and Kubernetes configuration exporters.

##### Component Relationships and Data Flows
1. Administrator & Users
–> Web UI / HTTP API requests reach Rails controllers → business logic → primary DB.
2. Inbound Mail Flow
SMTP client (external sender)
–> SMTP Server → SMTP handshake → message passed to message_dequeuer → message stored in message_db → worker jobs process the message → optionally forwarded via HTTP Sender or delivered to local mailboxes.
3. Outbound Mail Flow
Rails app or API clients enqueue outgoing messages → message_dequeuer stores them → workers pick up → DKIM signing & spam checks → SMTP Client connects to remote MX records → delivers mail.
4. Webhook Delivery
After processing, webhook events enqueued → worker → HTTP Sender → external webhook endpoint.
5. Scheduled Tasks & Metrics
Cron‐like scheduled tasks hit the database, prune old data, check DNS, send notifications → Prometheus metrics scraped from health server.

##### Architectural Patterns & Design Principles
- Monolithic Rails core with clear sub‐systems (SMTP server, SMTP client, HTTP sender, background workers).
- Separation of concerns: config data vs. high‐volume message data in a specialized message DB library.
- Plugin architecture for message inspection (spam, DKIM).
- Composer pattern for services (app/services, app/senders, app/lib/message_dequeuer).
- Convention over configuration for Rails plus explicit Docker/Kubernetes deployment layers.

## Diagram (Mermaid)

```mermaid
flowchart TB
    %% Client Interaction
    subgraph "Client Interaction"
        direction TB
        User["Users & API Clients"]:::frontend
    end

    %% Rails Application
    subgraph "Rails Application"
        direction TB
        Controllers["Controllers"]:::frontend
        LegacyAPI["Legacy API Endpoints"]:::frontend
        Routes["Routes"]:::frontend
        Models["Models"]:::backend
        Services["Services"]:::backend
        HealthServer["Health HTTP Server"]:::backend
    end

    %% Databases
    subgraph "Databases"
        direction TB
        PrimaryDB["Primary Relational DB"]:::db
        MessageDB["MessageDB Library"]:::db
    end

    %% SMTP Components
    subgraph "SMTP Components"
        direction TB
        SMTPServer["SMTP Server"]:::smtp
        SMTPClient["SMTP Client"]:::smtp
    end

    %% HTTP Sender
    HTTPSender["HTTP Sender"]:::http

    %% Worker Pool
    subgraph "Worker Pool & Queue"
        direction TB
        Dequeuer["Message Dequeuer"]:::workers
        Jobs["Worker Jobs"]:::workers
        ScheduledTasks["Scheduled Tasks"]:::workers
    end

    %% External Integrations
    subgraph "External Integrations"
        direction TB
        DNS["DNS Resolver"]:::external
        DKIM["DKIM Signer"]:::external
        SpamInspect["Spam Inspectors"]:::external
        WebhookTargets["Webhook Targets"]:::external
        Prometheus["Prometheus Metrics"]:::external
    end

    %% Connections
    User -->|"HTTP:80/443"| Controllers
    User -->|"HTTP:80/443"| LegacyAPI
    Controllers -->|reads/writes| PrimaryDB
    LegacyAPI -->|reads/writes| PrimaryDB
    Controllers -->|enqueue outbound| Dequeuer
    LegacyAPI -->|enqueue outbound| Dequeuer

    %% Inbound mail
    ExternalSMTPClient["External SMTP Clients"]:::external
    ExternalSMTPClient -->|SMTP:25/587| SMTPServer
    SMTPServer -->|enqueue inbound| Dequeuer

    %% Queue to DB
    Dequeuer -->|store message| MessageDB
    Dequeuer --> Jobs

    %% Worker processing
    Jobs -->|process message| MessageDB
    Jobs -->|DKIM sign| DKIM
    Jobs -->|spam inspect| SpamInspect
    Jobs -->|deliver outbound| SMTPClient
    Jobs -->|send webhook| HTTPSender

    %% HTTP Sender flow
    HTTPSender -->|HTTP POST| WebhookTargets

    %% Outbound SMTP Client
    SMTPClient -->|SMTP->MX| ExternalSMTPServer["Remote MX Servers"]:::external

    %% Scheduled tasks
    ScheduledTasks -->|cron| PrimaryDB
    ScheduledTasks -->|cron| MessageDB
    ScheduledTasks -->|metrics & health| Prometheus

    %% Health Server metrics
    HealthServer --> Prometheus

    %% DNS Integration
    Controllers -->|domain lookup| DNS
    Dequeuer -->|routing lookup| DNS
    Jobs -->|routing lookup| DNS

    %% Click Events
    click Controllers "https://github.com/postalserver/postal/tree/main/app/controllers"
    click LegacyAPI "https://github.com/postalserver/postal/tree/main/app/controllers/legacy_api"
    click Routes "https://github.com/postalserver/postal/blob/main/config/routes.rb"
    click Models "https://github.com/postalserver/postal/tree/main/app/models"
    click Services "https://github.com/postalserver/postal/tree/main/app/services"
    click HealthServer "https://github.com/postalserver/postal/blob/main/app/util/health_server.rb"
    click PrimaryDB "https://github.com/postalserver/postal/blob/main/config/database.yml"
    click MessageDB "https://github.com/postalserver/postal/tree/main/lib/postal/message_db"
    click DNS "https://github.com/postalserver/postal/blob/main/app/lib/dns_resolver.rb"
    click DKIM "https://github.com/postalserver/postal/blob/main/app/lib/dkim_header.rb"
    click DKIM "https://github.com/postalserver/postal/blob/main/lib/postal/signer.rb"
    click SpamInspect "https://github.com/postalserver/postal/blob/main/lib/postal/message_inspectors/clamav.rb"
    click SpamInspect "https://github.com/postalserver/postal/blob/main/lib/postal/message_inspectors/spam_assassin.rb"
    click SpamInspect "https://github.com/postalserver/postal/blob/main/lib/postal/message_inspectors/rspamd.rb"
    click Dequeuer "https://github.com/postalserver/postal/tree/main/app/lib/message_dequeuer"
    click Jobs "https://github.com/postalserver/postal/blob/main/app/lib/worker/jobs/process_queued_messages_job.rb"
    click Jobs "https://github.com/postalserver/postal/blob/main/app/lib/worker/jobs/process_webhook_requests_job.rb"
    click ScheduledTasks "https://github.com/postalserver/postal/tree/main/app/scheduled_tasks"
    click SMTPServer "https://github.com/postalserver/postal/blob/main/app/lib/smtp_server/server.rb"
    click SMTPServer "https://github.com/postalserver/postal/blob/main/app/lib/smtp_server/client.rb"
    click SMTPClient "https://github.com/postalserver/postal/blob/main/app/lib/smtp_client/server.rb"
    click SMTPClient "https://github.com/postalserver/postal/blob/main/app/lib/smtp_client/endpoint.rb"
    click SMTPClient "https://github.com/postalserver/postal/blob/main/app/lib/smtp_client/ssl_modes.rb"
    click HTTPSender "https://github.com/postalserver/postal/blob/main/app/senders/http_sender.rb"
    click HTTPSender "https://github.com/postalserver/postal/blob/main/app/services/webhook_delivery_service.rb"
    click Prometheus "https://github.com/postalserver/postal/blob/main/app/util/has_prometheus_metrics.rb"

    %% Styles
    classDef frontend fill:#cce5ff,stroke:#004085,color:#004085
    classDef backend fill:#e2e3e5,stroke:#6c757d,color:#383d41
    classDef smtp fill:#d4edda,stroke:#155724,color:#155724
    classDef db fill:#fff3cd,stroke:#856404,color:#856404
    classDef workers fill:#f5c6cb,stroke:#721c24,color:#721c24
    classDef http fill:#d1ecf1,stroke:#0c5460,color:#0c5460
    classDef external fill:#e2e3e5,stroke:#6c757d,color:#383d41
```
