FoundationDB + Stalwart + Valkey

Stalwart is a modern, open-source mail and collaboration server written in Rust. One binary speaks SMTP, IMAP, POP3, JMAP, ManageSieve, CalDAV, CardDAV and WebDAV. It brings its own spam filter, DKIM, SPF, DMARC, ARC, MTA-STS, DANE, TLS reporting, automatic ACME certificates, auto-ban for abusive clients, and a web admin interface.

What makes it special for operators: Stalwart can run as a cluster of stateless nodes on top of a distributed database. This guide builds exactly that:

  • FoundationDB, Apple’s distributed, ACID-transactional key-value store, holds everything persistent: accounts, mailboxes, messages, the full-text index and configuration.
  • Valkey, the open-source Redis fork in Debian 13, is the shared in-memory store for rate limits, locks and sessions, and the cluster coordinator that passes events between nodes.
  • Three Stalwart nodes serve mail. Any of them can fail without anyone noticing.

The result is a mail platform without a single point of failure:

  • FoundationDB: three servers, double redundancy, mutual TLS between all processes and clients
  • Valkey: a primary with two replicas and Sentinel failover, TLS-only, with ACL users and no default account
  • Stalwart: three nodes on the FoundationDB build, with secrets in environment variables and the setup wizard never exposed
  • Load balancing: a keepalived + HAProxy pair with the PROXY protocol, so Stalwart sees real client IPs for auto-ban and rate limits
  • Mail security: DKIM, SPF, DMARC, MTA-STS, TLS-RPT and DANE records, plus sensible auto-ban periods
  • Operations: FoundationDB backups, rolling upgrades, failure tests and monitoring

Tested on: Debian 13 “trixie” with Stalwart 1.1 (FoundationDB build), FoundationDB 7.4 (official packages), and Valkey 8.1 and HAProxy 3.0 from the Debian archive. All commands run as root.

Scope check: this is a lot of infrastructure, eight VMs in total. For a few hundred mailboxes, a single Stalwart node with its built-in RocksDB store and good backups is simpler and perfectly reliable. Build this cluster when you need high availability, or when you’re growing into thousands of mailboxes.


Table of contents

  1. Placeholders
  2. Architecture
  3. Prerequisites
  4. A private CA for all internal TLS
  5. FoundationDB: install
  6. FoundationDB: build the cluster with TLS
  7. Valkey: primary, replicas and Sentinel
  8. Stalwart: install the FoundationDB build
  9. Stalwart: first node and setup wizard
  10. Stalwart: in-memory store and coordinator
  11. Stalwart: join the other nodes
  12. Listeners, TLS and the load balancer
  13. DNS: MX, SPF, DKIM, DMARC, MTA-STS, TLS-RPT, DANE
  14. Security settings
  15. Firewall
  16. Testing
  17. Backups
  18. Monitoring
  19. Upgrades and day-2 operations
  20. Troubleshooting
  21. Checklist

1. Placeholders

PlaceholderMeaning
fdb-01..03 / 10.20.0.51..53FoundationDB servers
mail-01..03 / 10.20.0.61..63Stalwart nodes, which also run Valkey and Sentinel
lb-01, lb-02 / 10.20.0.71..72HAProxy + keepalived pair
10.20.0.70The load balancers’ VIP. Your firewall or router forwards the public mail ports to it.
203.0.113.10The platform’s public IPv4 address
mail.example.orgPublic name of the mail service (MX, IMAP, submission, web)
example.orgThe first mail domain
10.20.99.0/24Admin network (SSH, setup wizard, management)

2. Architecture

                    Internet
                        |
              203.0.113.10 (NAT)
                        |
          +-------------+-------------+
          |  VIP 10.20.0.70 keepalived |
          |  lb-01            lb-02    |   HAProxy, TCP mode, PROXY protocol v2
          +-------------+-------------+
                        |
       +----------------+----------------+
       |                |                |
    mail-01          mail-02          mail-03     Stalwart (stateless)
    Valkey primary   Valkey replica   Valkey replica
    Sentinel         Sentinel         Sentinel
       |                |                |
       +----------------+----------------+
                        |  (FDB client, TLS)
       +----------------+----------------+
       |                |                |
     fdb-01           fdb-02           fdb-03      FoundationDB (double, 3 coordinators)
ComponentRoleHoldsSurvives the loss of
FoundationDBData, blob and search storeEverything persistent1 of 3 servers
Valkey + SentinelIn-memory store and cluster coordinatorRate limits, locks, sessions, cluster events (rebuildable)1 of 3 nodes (Sentinel promotes a replica)
StalwartAll mail protocols, web admin, spam filterNothing locally: node IDs are leased from the shared store2 of 3 nodes
HAProxy + keepalivedOne entry point, health checks, real client IPsNothing1 of 2

Why these choices:

  • FoundationDB gives Stalwart strictly serialisable transactions across all nodes, automatic re-replication, and no primary to fail over. Stalwart stores large blobs in chunks, within FoundationDB’s limits (10 MB per transaction, 100 KB per value), so no separate S3 store is needed.
  • Valkey is in Debian 13 and gets security updates through the archive. Stalwart supports it through its Redis-compatible Sentinel mode. (Stalwart’s own Keep is the alternative it recommends for clusters. Valkey makes sense if you already run it, or want a component with a long track record.)
  • Stalwart’s coordinator setting Default reuses the in-memory store connection. Without a coordinator, nodes wouldn’t share config reloads, cache invalidations, blocked IPs or IMAP IDLE notifications.

3. Prerequisites

(all VMs)

  • Debian 13 minimal installs, hardened (see my guide Hardening a Debian 13 Virtual Machine), and time synchronised (chrony). Stalwart’s node leases and FoundationDB both depend on sane clocks.
  • Separate hypervisor hosts for the three FoundationDB servers and the three mail nodes.
  • FoundationDB servers: at least 4 vCPU, 8โ€“16 GB RAM, and SSD/NVMe storage for /var/lib/foundationdb. FoundationDB is latency-sensitive and calls fsync constantly.
  • Mail nodes: 2โ€“4 vCPU and 4โ€“8 GB RAM. They’re stateless, apart from Valkey’s small data set.
  • All names resolve on all nodes (internal DNS or /etc/hosts).
  • Port 25 outbound isn’t blocked by your provider, and the public IP has a PTR record of mail.example.org.

4. A private CA for all internal TLS

FoundationDB, Valkey and Sentinel all talk TLS, verified against one internal CA. On an admin workstation:

mkdir -p ~/mailcluster-ca && cd ~/mailcluster-ca
umask 077

openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
  -days 3650 -subj "/CN=Mail Cluster CA" -keyout ca.key -out ca.crt

issue() {   # issue <name> <ip>
  openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
    -subj "/CN=$1.example.org" -keyout "$1.key" -out "$1.csr"
  openssl x509 -req -in "$1.csr" -CA ca.crt -CAkey ca.key -CAcreateserial -days 825 -out "$1.crt" \
    -extfile <(printf 'subjectAltName=DNS:%s.example.org,DNS:%s,IP:%s,IP:127.0.0.1\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth,clientAuth\n' "$1" "$1" "$2")
}
issue fdb-01 10.20.0.51;  issue fdb-02 10.20.0.52;  issue fdb-03 10.20.0.53
issue mail-01 10.20.0.61; issue mail-02 10.20.0.62; issue mail-03 10.20.0.63
openssl verify -CAfile ca.crt *.crt | grep -v ': OK' || echo "all certificates OK"Code language: PHP (php)

openssl req -newkey ... -nodes writes keys in PKCS#8 format (BEGIN PRIVATE KEY), which FoundationDB requires. Each certificate is valid for server and client use, so the same pair authenticates a FoundationDB server to its peers and a Stalwart node to FoundationDB. Keep ca.key off the servers.

On every VM, also trust the CA system-wide, so tools and Stalwart’s TLS clients accept the internal certificates:

cp ca.crt /usr/local/share/ca-certificates/mailcluster-ca.crt
update-ca-certificates

5. FoundationDB: install

FoundationDB isn’t in Debian’s archive. Apple publishes .deb packages, each with a .sha256 checksum, on GitHub. Stalwart’s FoundationDB build is compiled against the 7.4 API, so install a 7.4.x release. The 7.4 release notes call releases from 7.4.7 on stable. GitHub labels all FoundationDB releases “Pre-release”, so don’t let that confuse you.

Every server and every client must run the same FoundationDB version. Patch releases within 7.4 can be mixed during a rolling upgrade. Different minor versions (7.3 vs 7.4) can’t talk to each other at all.

On fdb-01..03 (server and client) and on mail-01..03 (client only):

FDB=7.4.10
cd /usr/local/src
for p in clients server; do
  curl -fsSLO "https://github.com/apple/foundationdb/releases/download/${FDB}/foundationdb-${p}_${FDB}-1_amd64.deb"
  curl -fsSLO "https://github.com/apple/foundationdb/releases/download/${FDB}/foundationdb-${p}_${FDB}-1_amd64.deb.sha256"
done

# Compare the computed checksums with the published ones; they must match exactly
sha256sum foundationdb-*_${FDB}-1_amd64.deb
cat foundationdb-*_${FDB}-1_amd64.deb.sha256Code language: PHP (php)

Then install. FoundationDB servers get both packages, and mail nodes get only the client library:

apt install ./foundationdb-clients_${FDB}-1_amd64.deb ./foundationdb-server_${FDB}-1_amd64.deb   # fdb-01..03
apt install ./foundationdb-clients_${FDB}-1_amd64.deb                                             # mail-01..03Code language: PHP (php)

Hold the packages so a stray apt operation never mixes versions. Upgrades are a deliberate, cluster-wide procedure (section 19):

apt-mark hold foundationdb-clients foundationdb-server 2>/dev/null; apt-mark showholdCode language: JavaScript (javascript)

What the server package does on install: it creates /etc/foundationdb/fdb.cluster and starts fdbmonitor, which runs a single-node, memory-engine database listening on 127.0.0.1. That’s a test instance. The next section turns the three servers into one real cluster.


6. FoundationDB: build the cluster with TLS

6.1 Certificates

(fdb-01..03) with each server’s own files:

install -m 0644 -o root -g foundationdb ca.crt     /etc/foundationdb/ca.pem
install -m 0644 -o root -g foundationdb fdb-01.crt /etc/foundationdb/cert.pem
install -m 0640 -o root -g foundationdb fdb-01.key /etc/foundationdb/key.pem

6.2 Process layout and TLS

(fdb-01..03) Replace /etc/foundationdb/foundationdb.conf. FoundationDB scales by running several processes per machine, each with a role (class). This layout suits a 4-vCPU server:

## /etc/foundationdb/foundationdb.conf
[fdbmonitor]
user = foundationdb
group = foundationdb

[general]
restart-delay = 60
cluster-file = /etc/foundationdb/fdb.cluster

[fdbserver]
command = /usr/sbin/fdbserver
public-address = auto:$ID:tls
listen-address = public
datadir = /var/lib/foundationdb/data/$ID
logdir = /var/log/foundationdb
# Memory limit per process; processes x memory must fit in RAM
memory = 4GiB
# Mutual TLS between all processes and clients
tls_certificate_file = /etc/foundationdb/cert.pem
tls_key_file = /etc/foundationdb/key.pem
tls_ca_file = /etc/foundationdb/ca.pem
tls_verify_peers = Check.Valid=1

## One process per core, each with a role
[fdbserver.4500]
class = storage
[fdbserver.4501]
class = storage
[fdbserver.4502]
class = transaction
[fdbserver.4503]
class = stateless

[backup_agent]
command = /usr/lib/foundationdb/backup_agent/backup_agent
logdir = /var/log/foundationdb
# The backup agent is a client of the cluster, so it needs TLS too
tls_certificate_file = /etc/foundationdb/cert.pem
tls_key_file = /etc/foundationdb/key.pem
tls_ca_file = /etc/foundationdb/ca.pem

[backup_agent.1]Code language: PHP (php)

Before replacing the file, check the command = path of the [backup_agent] section in the package’s original foundationdb.conf, and keep that path if it differs.

ClassRole
storageHolds data. Most processes should be storage processes.
transactionRuns transaction logs: the durability path for every commit, latency-critical
statelessProxies, resolvers and the cluster controller

public-address = auto:$ID:tls makes each process listen on the machine’s address, with its section number as the port, TLS only.

6.3 Form the cluster

On fdb-02 and fdb-03, stop the local test instance and remove its data:

systemctl stop foundationdb
rm -rf /var/lib/foundationdb/data/*Code language: JavaScript (javascript)

On fdb-01, turn the local instance into a TLS-enabled cluster bound to its LAN address:

systemctl stop foundationdb
rm -rf /var/lib/foundationdb/data/*
/usr/lib/foundationdb/make_public.py -a 10.20.0.51 -t
cat /etc/foundationdb/fdb.cluster
# e.g.  mailfdb:Xyz123AbC@10.20.0.51:4500:tls
systemctl start foundationdbCode language: JavaScript (javascript)

Copy that fdb.cluster file, unchanged, to fdb-02 and fdb-03 (/etc/foundationdb/fdb.cluster, owner foundationdb, mode 0664), then start them:

systemctl start foundationdb

fdbcli is a client too, so it needs TLS settings. Set them for root’s shell on the FoundationDB servers (for example in /root/.bashrc):

export FDB_TLS_CERTIFICATE_FILE=/etc/foundationdb/cert.pem
export FDB_TLS_KEY_FILE=/etc/foundationdb/key.pem
export FDB_TLS_CA_FILE=/etc/foundationdb/ca.pemCode language: JavaScript (javascript)

Now create the real database. On fdb-01:

fdbcli --exec "configure new double ssd"
fdbcli --exec "coordinators auto"
fdbcli --exec "status"Code language: JavaScript (javascript)
ChoiceWhy
doubleTwo copies of every piece of data on different machines. With three servers, any one can fail. (triple needs five or more machines.)
ssdThe proven on-disk storage engine. FoundationDB also offers the newer Redwood engine. fdbcli --exec "help configure" lists the exact engine names your version supports, and you can switch later with configure <engine>. FoundationDB migrates the data online.
coordinators autoPicks three coordinators, one per machine. Coordinators hold the cluster’s own state, so three tolerate one failure.

status must show Redundancy mode - double, Storage engine - ssd..., three machines, Fault Tolerance - 1 machine, and Healthy.

The cluster file now lists three coordinators. Copy the final /etc/foundationdb/fdb.cluster from fdb-01 to all servers and all mail nodes. It’s how every client finds the cluster. (After coordinators auto, the servers update their own copy automatically.)

The cluster file is a secret-free but critical file. Clients need write access to it, so they can update it when coordinators change. On the mail nodes, it’s owned by the Stalwart user (section 8).


7. Valkey: primary, replicas and Sentinel

Valkey runs on the three mail nodes: a primary on mail-01 and replicas on mail-02 and mail-03. Sentinel on all three watches the primary, and promotes a replica if it fails.

(mail-01..03)

apt install valkey-server valkey-sentinel
systemctl stop valkey-server valkey-sentinel

7.1 Certificates

install -d -m 0750 -o root -g valkey /etc/valkey/tls
install -m 0644 -o root -g valkey ca.crt      /etc/valkey/tls/ca.crt
install -m 0644 -o root -g valkey mail-01.crt /etc/valkey/tls/server.crt
install -m 0640 -o root -g valkey mail-01.key /etc/valkey/tls/server.key

7.2 ACL users

No default user, and one user per purpose. Generate four passwords once, and use the same values on all three nodes:

for u in admin stalwart replicator sentinel; do echo "$u: $(openssl rand -base64 30 | tr -d '/+=')"; doneCode language: PHP (php)

The ACL file stores only SHA-256 hashes of the passwords:

h() { printf '%s' "$1" | sha256sum | cut -d' ' -f1; }
cat > /etc/valkey/users.acl <<EOF
user default off
user admin on #$(h '<admin-password>') ~* &* +@all
user stalwart on #$(h '<stalwart-password>') ~* &* +@all -@dangerous
user replicator on #$(h '<replicator-password>') +psync +replconf +ping
user sentinel on #$(h '<sentinel-password>') allchannels +multi +slaveof +replicaof +ping +exec +subscribe +config|rewrite +role +publish +info +client|setname +client|kill +script|kill
EOF
chown valkey:valkey /etc/valkey/users.acl
chmod 0600 /etc/valkey/users.aclCode language: PHP (php)
UserPermissions
defaultDisabled. No anonymous access at all.
adminEverything, for you with valkey-cli
stalwartAll keys and commands, except the @dangerous category (FLUSHALL, CONFIG, DEBUG, KEYS, …)
replicatorOnly what replicas need to sync from the primary
sentinelExactly the commands Sentinel uses for monitoring and failover

7.3 Valkey configuration

Leave Debian’s /etc/valkey/valkey.conf as it is. Add one line at its end, so a local file overrides everything above:

echo 'include /etc/valkey/valkey-local.conf' >> /etc/valkey/valkey.confCode language: JavaScript (javascript)

Create /etc/valkey/valkey-local.conf (addresses for mail-01):

# --- Network: LAN address and localhost, TLS only -----------------------------
bind 10.20.0.61 127.0.0.1
protected-mode yes
port 0
tls-port 6379
tls-cert-file /etc/valkey/tls/server.crt
tls-key-file /etc/valkey/tls/server.key
tls-ca-cert-file /etc/valkey/tls/ca.crt
# Stalwart authenticates with ACL user and password, not client certificates
tls-auth-clients optional
tls-replication yes
tls-protocols "TLSv1.2 TLSv1.3"

# --- Authentication ----------------------------------------------------------------
aclfile /etc/valkey/users.acl
# How replicas authenticate to the primary
primaryuser replicator
primaryauth <replicator-password>

# --- Memory and persistence ----------------------------------------------------------
maxmemory 1gb
# Never silently drop keys Stalwart relies on: fail writes instead, and alert on memory
maxmemory-policy noeviction
appendonly yesCode language: PHP (php)

On mail-02 and mail-03 only, also add (with their own bind address):

replicaof 10.20.0.61 6379Code language: CSS (css)
chmod 0640 /etc/valkey/valkey-local.conf && chown root:valkey /etc/valkey/valkey-local.conf
systemctl start valkey-server
valkey-cli --tls --cacert /etc/valkey/tls/ca.crt -h 127.0.0.1 --user admin --askpass INFO replication
# on mail-01: role:master, connected_slaves:2Code language: PHP (php)

appendonly yes matters for replication: a primary that restarts empty would replicate its emptiness to the replicas. With persistence, it comes back with its data, and Sentinel promotes a replica if it doesn’t come back at all.

7.4 Sentinel

(mail-01..03) Sentinel rewrites its own config file at runtime, so add your settings to Debian’s /etc/valkey/sentinel.conf directly (at the end):

# --- Network: TLS only ---------------------------------------------------------------
bind 10.20.0.61 127.0.0.1
port 0
tls-port 26379
tls-cert-file /etc/valkey/tls/server.crt
tls-key-file /etc/valkey/tls/server.key
tls-ca-cert-file /etc/valkey/tls/ca.crt
tls-auth-clients optional
tls-replication yes

# --- Sentinel's own password (clients and other Sentinels) ---------------------------
requirepass <sentinel-password>
sentinel sentinel-pass <sentinel-password>

# --- What to watch: the primary on mail-01, failover needs 2 of 3 Sentinels ----------
sentinel monitor stalwart-mem 10.20.0.61 6379 2
sentinel auth-user stalwart-mem sentinel
sentinel auth-pass stalwart-mem <sentinel-password>
sentinel down-after-milliseconds stalwart-mem 5000
sentinel failover-timeout stalwart-mem 60000
sentinel parallel-syncs stalwart-mem 1Code language: PHP (php)
systemctl start valkey-sentinel
valkey-cli --tls --cacert /etc/valkey/tls/ca.crt -h 127.0.0.1 -p 26379 -a '<sentinel-password>' \
  SENTINEL primary stalwart-mem | paste - - | grep -E 'ip|port|num-slaves|num-other-sentinels|flags'
# num-slaves 2, num-other-sentinels 2, flags masterCode language: PHP (php)

8. Stalwart: install the FoundationDB build

(mail-01..03) Stalwart’s official installer downloads the release binary, creates the stalwart user and the systemd service. The --fdb option selects the FoundationDB build. Download the script, read it, then run it:

curl --proto '=https' --tlsv1.2 -sSf https://get.stalw.art/install.sh -o /usr/local/src/stalwart-install.sh
less /usr/local/src/stalwart-install.sh
sh /usr/local/src/stalwart-install.sh --fdbCode language: JavaScript (javascript)

What it creates:

PathContents
/usr/local/bin/stalwartThe server binary
/etc/stalwart/config.jsonNode-local bootstrap config: the data store connection. Written by the setup wizard.
/etc/stalwart/stalwart.envEnvironment variables, read at every start
/var/lib/stalwart/, /var/log/stalwart/Local state and logs
stalwart.serviceRuns as user stalwart, with only CAP_NET_BIND_SERVICE for the low ports

Stop the service again: it starts in setup mode, and we prepare FoundationDB access first.

systemctl stop stalwart

Give Stalwart its FoundationDB client files:

install -d -m 0750 -o root -g stalwart /etc/stalwart/fdb
install -m 0644 -o root -g stalwart ca.crt      /etc/stalwart/fdb/ca.pem
install -m 0644 -o root -g stalwart mail-01.crt /etc/stalwart/fdb/cert.pem
install -m 0640 -o root -g stalwart mail-01.key /etc/stalwart/fdb/key.pem
install -m 0664 -o stalwart -g stalwart /etc/foundationdb/fdb.cluster /etc/stalwart/fdb.cluster

Then set the node’s environment in /etc/stalwart/stalwart.env (per node):

# Unique per node: used for the node-ID lease in the shared store
STALWART_HOSTNAME=mail-01.example.org

# FoundationDB client TLS
FDB_TLS_CERTIFICATE_FILE=/etc/stalwart/fdb/cert.pem
FDB_TLS_KEY_FILE=/etc/stalwart/fdb/key.pem
FDB_TLS_CA_FILE=/etc/stalwart/fdb/ca.pem

# Secrets referenced from Stalwart's configuration (section 10)
VALKEY_PASSWORD=<stalwart-password>
SENTINEL_PASSWORD=<sentinel-password>Code language: PHP (php)
chown root:stalwart /etc/stalwart/stalwart.env
chmod 0640 /etc/stalwart/stalwart.env

Test FoundationDB access as the stalwart user before going further:

sudo -u stalwart env $(grep ^FDB_ /etc/stalwart/stalwart.env | xargs) \
  fdbcli -C /etc/stalwart/fdb.cluster --exec "status minimal"
# The database is available.Code language: PHP (php)

9. Stalwart: first node and setup wizard

On mail-01 only. On its first start without configuration, Stalwart runs a setup wizard on port 8080 over plain HTTP. Never expose it. Reach it through an SSH tunnel from your admin machine:

systemctl start stalwart
journalctl -u stalwart -n 200 | grep -A8 'bootstrap mode'    # the one-time admin passwordCode language: PHP (php)
# On your admin workstation:
ssh -L 8080:127.0.0.1:8080 admin@mail-01.example.org
# then open http://127.0.0.1:8080/adminCode language: CSS (css)

Walk through the five screens:

  1. Identity: hostname mail.example.org (the public name, identical on all nodes), and the first domain example.org.
  2. Storage: data store FoundationDB, cluster file /etc/stalwart/fdb.cluster. Use the same store (Default) for blobs and full-text search.
  3. Directory: internal (accounts stored in FoundationDB), or LDAP/OIDC if you have an identity provider.
  4. Logging: journal/stdout (systemd captures it).
  5. DNS management: optional automatic DNS updates through your DNS provider’s API.

The storage choice ends up in /etc/stalwart/config.json as a DataStore object:

{"@type": "FoundationDb", "clusterFile": "/etc/stalwart/fdb.cluster"}Code language: JSON / JSON with Comments (json)

Choose automatic certificates (ACME, Let’s Encrypt) when asked. Then restart:

systemctl restart stalwart

From now on, the web admin is at https://mail.example.org/admin (once DNS and the load balancer are in place), or through the tunnel on port 443 until then. Change the admin password immediately, and enable two-factor authentication or a passkey for the admin account.

Where Stalwart keeps its configuration: apart from the data store connection in config.json, all settings are objects in the shared data store. They’re edited in the web admin or with stalwart-cli, and are instantly identical on every node. That’s what makes the nodes interchangeable.


10. Stalwart: in-memory store and coordinator

A cluster needs a shared in-memory store, and a coordinator that passes events between the nodes. Configure them on mail-01 before adding the other nodes, in this order.

1. In-memory store: Valkey through Sentinel. In the web admin under the in-memory store settings, choose Redis Sentinel, with:

FieldValue
URLsrediss://10.20.0.61:26379, rediss://10.20.0.62:26379, rediss://10.20.0.63:26379 (the Sentinels)
Service namestalwart-mem
Auth usernamestalwart
Auth secretEnvironment variable VALKEY_PASSWORD
Sentinel username(empty: the Sentinels use requirepass)
Sentinel secretEnvironment variable SENTINEL_PASSWORD

Stored as an object, it looks like this:

{
  "@type": "RedisSentinel",
  "urls": ["rediss://10.20.0.61:26379", "rediss://10.20.0.62:26379", "rediss://10.20.0.63:26379"],
  "serviceName": "stalwart-mem",
  "authUsername": "stalwart",
  "authSecret": {"@type": "EnvironmentVariable", "variableName": "VALKEY_PASSWORD"},
  "sentinelSecret": {"@type": "EnvironmentVariable", "variableName": "SENTINEL_PASSWORD"}
}Code language: JSON / JSON with Comments (json)

The rediss:// scheme means TLS. The internal CA is in the system trust store (section 4), so Stalwart can verify the Valkey certificates. Don’t enable the “allow invalid certificates” option to work around a certificate problem: fix the certificate.

2. Coordinator: Default. Under the cluster coordinator settings, choose Default. It reuses the in-memory store connection, so no extra service is needed.

3. Restart, then check the log:

systemctl restart stalwart
journalctl -u stalwart -n 50 --no-pager | grep -iE 'error|warn|cluster|coordinator|redis'Code language: JavaScript (javascript)

11. Stalwart: join the other nodes

On mail-02 and mail-03. The node-local config.json only holds the data store connection, and every other setting comes from FoundationDB. So a new node only needs mail-01’s config.json, its own environment file and its own certificates (section 8):

scp mail-01:/etc/stalwart/config.json /etc/stalwart/config.json
chown root:stalwart /etc/stalwart/config.json && chmod 0640 /etc/stalwart/config.json
# stalwart.env: STALWART_HOSTNAME=mail-02.example.org (unique!), same FDB_* and passwords
systemctl start stalwartCode language: PHP (php)

The node leases a free node ID from the shared store, loads the configuration, and joins through the coordinator. In the web admin under Management โ†’ Cluster, all three nodes appear:

stalwart-cli query ClusterNode       # alternative to the web admin, if you use the CLICode language: PHP (php)

Node leases are renewed every 30 minutes and expire after an hour, which is why every node must keep a unique STALWART_HOSTNAME forever, and why clocks must be synchronised.


12. Listeners, TLS and the load balancer

12.1 Stalwart listeners

Stalwart creates these listeners on first start, bound to all addresses:

ListenerPortTLSKeep?
smtp25STARTTLSYes: incoming mail from other servers
submissions465ImplicitYes: mail clients sending (RFC 8314’s preferred submission port)
imaps993ImplicitYes
pop3s995ImplicitOnly if you need POP3. Otherwise delete it.
sieve4190STARTTLSYes, if users manage filters from their mail clients
https443ImplicitYes: JMAP, web admin, CalDAV/CardDAV, autoconfig, MTA-STS, ACME TLS-ALPN
http8080NoneDelete it, or bind it to 127.0.0.1. It’s not needed after setup.

Add submission on 587 with STARTTLS if older clients need it: a listener with protocol smtp, bind [::]:587, and STARTTLS enabled.

12.2 Trust the load balancers’ PROXY protocol

Behind HAProxy, every connection would appear to come from the load balancer. Stalwart’s auto-ban and rate limits would then hit everyone at once. The PROXY protocol passes the real client IP. In the web admin’s system settings, set proxy trusted networks to the load balancers:

10.20.0.71/32, 10.20.0.72/32

Only connections from those addresses may send a PROXY header. Anyone else who tries is rejected.

12.3 HAProxy + keepalived

On lb-01 and lb-02: apt install haproxy keepalived. HAProxy runs in TCP mode, so TLS terminates on Stalwart, which holds the ACME certificates. Add to /etc/haproxy/haproxy.cfg:

defaults stalwart
    mode tcp
    timeout connect 5s
    timeout client 30m
    timeout server 30m
    default-server check inter 3s fall 3 rise 2 send-proxy-v2 check-send-proxy

frontend smtp        from stalwart
    bind :25
    default_backend smtp
backend smtp         from stalwart
    balance roundrobin
    server mail-01 10.20.0.61:25
    server mail-02 10.20.0.62:25
    server mail-03 10.20.0.63:25

frontend submissions from stalwart
    bind :465
    default_backend submissions
backend submissions  from stalwart
    balance leastconn
    server mail-01 10.20.0.61:465
    server mail-02 10.20.0.62:465
    server mail-03 10.20.0.63:465

frontend imaps       from stalwart
    bind :993
    default_backend imaps
backend imaps        from stalwart
    balance leastconn
    server mail-01 10.20.0.61:993
    server mail-02 10.20.0.62:993
    server mail-03 10.20.0.63:993

frontend sieve       from stalwart
    bind :4190
    default_backend sieve
backend sieve        from stalwart
    balance leastconn
    server mail-01 10.20.0.61:4190
    server mail-02 10.20.0.62:4190
    server mail-03 10.20.0.63:4190

frontend https       from stalwart
    bind :443
    default_backend https
backend https        from stalwart
    balance leastconn
    server mail-01 10.20.0.61:443
    server mail-02 10.20.0.62:443
    server mail-03 10.20.0.63:443Code language: CSS (css)

send-proxy-v2 makes HAProxy put the real client address in a PROXY header on every connection. check-send-proxy does the same for the health checks, so Stalwart doesn’t log malformed connections from them. Add a 587 frontend and backend if you created that listener.

keepalived moves the VIP 10.20.0.70 between lb-01 and lb-02, exactly as in the HAProxy pair from my Patroni post: unicast VRRP between the two, a track_script with systemctl is-active --quiet haproxy run as an unprivileged script_user, nopreempt, and VRRP accepted only from the peer. Use a virtual_router_id that no other keepalived pair in that network uses.

Why not DNS round robin to the mail nodes? For incoming SMTP, multiple MX hosts are a perfectly good alternative, because sending servers retry other MX hosts on their own. But IMAP, submission and web clients don’t fail over between addresses gracefully. The load balancer gives every protocol the same behaviour, and one public IP for a clean PTR record and IP reputation.


13. DNS: MX, SPF, DKIM, DMARC, MTA-STS, TLS-RPT, DANE

Stalwart’s web admin shows the exact records for each domain under the domain’s DNS settings, including the generated DKIM public keys. Publish them. The full set for example.org looks like this:

; Mail host
mail.example.org.            A      203.0.113.10
; PTR for 203.0.113.10 -> mail.example.org (set at your provider)

; Incoming mail
example.org.                 MX     10 mail.example.org.

; SPF: only this platform sends for example.org
example.org.                 TXT    "v=spf1 mx -all"

; DKIM: published from Stalwart's generated keys (Ed25519 and RSA)
<selector>._domainkey.example.org. TXT "v=DKIM1; k=ed25519; p=..."
<selector>._domainkey.example.org. TXT "v=DKIM1; k=rsa; p=..."

; DMARC: start with p=none and reports, move to quarantine/reject
_dmarc.example.org.          TXT    "v=DMARC1; p=reject; rua=mailto:dmarc@example.org; adkim=s; aspf=s"

; MTA-STS: senders must use TLS with a valid certificate
_mta-sts.example.org.        TXT    "v=STSv1; id=2026112201"
mta-sts.example.org.         CNAME  mail.example.org.

; TLS reporting: senders report TLS problems to you
_smtp._tls.example.org.      TXT    "v=TLSRPTv1; rua=mailto:tlsrpt@example.org"

; Client autoconfiguration
autoconfig.example.org.      CNAME  mail.example.org.
_imaps._tcp.example.org.     SRV    0 1 993 mail.example.org.
_submissions._tcp.example.org. SRV  0 1 465 mail.example.org.Code language: HTML, XML (xml)

Notes:

  • DMARC: start with p=none for a couple of weeks, read the reports, then go to quarantine and finally reject.
  • MTA-STS needs the mta-sts.example.org name in the TLS certificate. Add it to the domain’s names in Stalwart’s ACME settings, and Stalwart serves the policy file itself.
  • DANE (_25._tcp.mail.example.org. TLSA 3 1 1 ...) protects SMTP against TLS downgrade, but only with DNSSEC on the zone. It also has to be updated before each certificate key change. Stalwart supports it. Enable it only if your DNS setup handles DNSSEC and TLSA rollovers reliably (for example, with reuseKey in the ACME settings, so the key stays the same across renewals).

14. Security settings

In the web admin, adjust these defaults:

SettingRecommendationWhy
Auto-ban periods (authBanPeriod, abuseBanPeriod, loiterBanPeriod, scanBanPeriod)Set to e.g. 1dBy default, bans are permanent. One user with a wrong password on a phone behind a carrier NAT would lock out everyone behind that NAT forever.
Allowed IPsMonitoring hosts, office egress, the load balancersNever auto-banned
Admin accountStrong password plus 2FA or a passkeyThe web admin controls the whole platform
Spam filterKeep it on, and train the classifier with users’ junk foldersBuilt in: rules, a statistical classifier, DNSBLs and greylisting
Outbound DKIMOne Ed25519 and one RSA key per domain, with automatic rotationEd25519 for modern receivers, RSA for compatibility
Encryption at restOffer it to users (S/MIME or OpenPGP)Stored mail stays encrypted with the user’s key, even in a database dump. (After upgrades, check the release notes: one 1.0.x release required re-enabling it.)
POP3, 8080Remove the listeners if unusedLess attack surface

15. Firewall

Create one nftables table per role in /etc/nftables.d/ (start each file with destroy table, as in my Fail2Ban post).

fdb-01..03: FoundationDB ports only from FoundationDB servers and mail nodes:

destroy table inet fdb
table inet fdb {
    chain input {
        type filter hook input priority filter - 10; policy accept;
        iif "lo" accept
        tcp dport 4500-4503 ip saddr { 10.20.0.51, 10.20.0.52, 10.20.0.53, 10.20.0.61, 10.20.0.62, 10.20.0.63 } accept
        tcp dport 4500-4503 counter drop
    }
}Code language: JavaScript (javascript)

mail-01..03: mail ports only from the load balancers, and Valkey and Sentinel only between mail nodes:

destroy table inet stalwart
table inet stalwart {
    chain input {
        type filter hook input priority filter - 10; policy accept;
        iif "lo" accept
        tcp dport { 25, 465, 587, 993, 4190, 443 } ip saddr { 10.20.0.71, 10.20.0.72 } accept
        tcp dport { 25, 465, 587, 993, 995, 4190, 443, 8080 } counter drop
        tcp dport { 6379, 26379 } ip saddr { 10.20.0.61, 10.20.0.62, 10.20.0.63 } accept
        tcp dport { 6379, 26379 } counter drop
    }
}Code language: JavaScript (javascript)

lb-01..02: the public mail ports from anywhere, and VRRP from the peer only (see the keepalived example in my Patroni post).

Outbound, the mail nodes need TCP 25 to the internet (delivery), DNS, the ACME endpoint (443), and FoundationDB and Valkey internally.


16. Testing

16.1 FoundationDB

fdbcli --exec "status details"        # 3 machines, double, fault tolerance 1, Healthy
systemctl stop foundationdb           # on fdb-02
fdbcli --exec "status"                # still available, data being re-replicated
systemctl start foundationdb          # on fdb-02; wait for "Healthy"Code language: PHP (php)

16.2 Valkey failover

valkey-cli --tls --cacert /etc/valkey/tls/ca.crt -h 127.0.0.1 -p 26379 -a '<sentinel-password>' \
  SENTINEL failover stalwart-mem
# within seconds: a replica is promoted
valkey-cli --tls --cacert /etc/valkey/tls/ca.crt -h 127.0.0.1 -p 26379 -a '<sentinel-password>' \
  SENTINEL get-primary-addr-by-name stalwart-memCode language: PHP (php)

Stalwart follows the new primary through the Sentinels, with no restart. Check its log for reconnect messages, and that logins keep working.

16.3 Mail flow

apt install swaks
# Submission with authentication (from an admin machine)
swaks --to someone@external.example --from user@example.org \
  --server mail.example.org --port 465 --tlsc --auth-user user@example.org --auth-password '<pw>'
# Inbound delivery (from an external host)
swaks --to user@example.org --server mail.example.org --port 25 --tlsCode language: PHP (php)

Then check: the message arrives in IMAP. At the external recipient, the headers show dkim=pass, spf=pass and dmarc=pass. Testing services such as mail-tester.com or internet.nl grade the whole setup.

16.4 Node loss

Stop Stalwart on one node (systemctl stop stalwart). HAProxy marks it down within about 9 seconds. Clients reconnect to the remaining nodes, and IMAP IDLE keeps working thanks to the coordinator. Repeat with a second node: the platform runs on one Stalwart node as long as FoundationDB and Valkey are healthy.

16.5 Real client IPs and auto-ban

Make a few failed logins from a test host. The web admin’s blocked IPs must show the test host’s address, not a load balancer’s. Remove the entry afterwards.


17. Backups

Everything persistent is in FoundationDB, so a FoundationDB backup is a backup of the whole platform. FoundationDB’s built-in backup runs continuously through the backup_agent processes (already configured in section 6) and allows point-in-time restores.

# On an fdb server: continuous backup to a local or mounted target
mkdir -p /srv/fdb-backup && chown foundationdb:foundationdb /srv/fdb-backup
fdbbackup start -d file:///srv/fdb-backup -z
fdbbackup statusCode language: PHP (php)

For off-site copies, FoundationDB can write straight to S3-compatible storage (blobstore://<key>:<secret>@<host>:<port>/<name>?bucket=<bucket>). FoundationDB backups aren’t encrypted, so use an encrypted target: an encrypted filesystem, server-side encryption in the bucket, or an encrypted copy job.

Restore into an empty cluster with fdbrestore start -r <backup-url> --dest-cluster-file <file>. Practise it on a test cluster.

Also keep:

  • A copy of /etc/stalwart/config.json, /etc/stalwart/stalwart.env, /etc/foundationdb/foundationdb.conf, the Valkey configs and the CA, in your configuration management or password manager.
  • Optionally, stalwart-cli snapshot exports Stalwart’s configuration objects as a readable plan (without secrets). That’s useful for change tracking and for rebuilding config from scratch.
  • Valkey’s data is transient (rate limits, locks, sessions), so it doesn’t need backups.

18. Monitoring

WhatHowAlert on
FoundationDB healthfdbcli --exec "status json" (scripted, or with an fdb exporter)Not Healthy, fault tolerance below 1, storage over 80%, a process down
Valkeyprometheus-redis-exporter (Debian package), with the admin user over TLSrole changed (a failover happened), connected_slaves < 2, memory near maxmemory, rejected writes
SentinelSENTINEL primary stalwart-memnum-other-sentinels < 2, flags other than master
StalwartIts telemetry and metrics settings, plus the journalNode missing from the cluster list, queue growing, delivery errors
Mail flowDMARC and TLS-RPT reports, external checks (internet.nl)Authentication failures, TLS failures reported by others
HostsNode Exporter (see my Node Exporter post)Disk, memory, time sync

19. Upgrades and day-2 operations

Stalwart (rolling): one node at a time. Take it out of HAProxy (disable server, or just stop it; health checks handle the rest), then rerun the installer with the same options:

sh /usr/local/src/stalwart-install.sh --fdb
# "Upgrade complete! The service was restarted with the new binary."Code language: PHP (php)

Read the release notes first. Some versions need a one-time step, for example setting STALWART_UPDATE_ROLE_PERMISSIONS=true in stalwart.env for one start after upgrading to 1.1 (then remove it). Back up FoundationDB before minor and major upgrades.

FoundationDB patch releases (7.4.x โ†’ 7.4.y): download and verify the new packages (section 5), then upgrade all mail nodes’ client packages and all servers. Within the same minor version, servers can be restarted one at a time. Minor or major upgrades (7.4 โ†’ 7.5 or 8.x) change the network protocol: all servers restart together (a short outage), and the clients need a compatible library first. That’s a planned maintenance with a rehearsal on a test cluster. It also has to wait for a Stalwart FoundationDB build that supports the new version.

Valkey: comes from Debian, so it’s patched by unattended-upgrades. Stagger reboots of the mail nodes (see my unattended-upgrades post), so Sentinel never loses its majority.

TaskCommand
FoundationDB statusfdbcli --exec "status"
Retire an FDB serverfdbcli --exec "exclude 10.20.0.53", wait for “safe to remove”, then stop it
Valkey replicationvalkey-cli ... INFO replication
Manual Valkey failoverSENTINEL failover stalwart-mem
Stalwart cluster nodesWeb admin โ†’ Management โ†’ Cluster
Stalwart logsjournalctl -u stalwart

20. Troubleshooting

SymptomCause / fix
Stalwart won’t start: FoundationDB connection errorsCluster file path or permissions (the stalwart user needs write access to /etc/stalwart/fdb.cluster), missing FDB_TLS_* variables, or a client and server version mismatch. Test with fdbcli as the stalwart user (section 8).
fdbcli hangs: “The database is unavailable”No TLS settings in the shell, a coordinator unreachable, or a cluster file with old coordinators. Compare /etc/foundationdb/fdb.cluster on all machines.
FDB status: Fault Tolerance - 0A server or process is down, or data is still re-replicating. Check status details.
Stalwart: “A cluster coordinator requires a Stalwart Keep or Redis in-memory store”Coordinator set before the in-memory store. Configure the Valkey Sentinel store first (section 10).
Valkey: NOPERM errors in Stalwart’s logStalwart needs a command from the @dangerous category. Grant that command explicitly to the stalwart ACL user (for example +keys), rather than +@all.
Valkey TLS errors from StalwartThe internal CA isn’t in the system trust store (update-ca-certificates), or the certificate’s SAN doesn’t contain the IP that Sentinel reports
Everyone gets banned at onceThe PROXY protocol isn’t configured, so all connections appear to come from the load balancer. Set send-proxy-v2 and the proxy trusted networks (section 12).
Mail lands in spam at the big providersPTR record missing or wrong, DKIM not published, DMARC failing, or a poor IP reputation. Check a received message’s authentication headers.
Nodes not seeing each other’s config changesThe coordinator is set to Disabled, or Valkey is unreachable from that node

21. Checklist

Infrastructure

  • โ˜ Eight hardened Debian 13 VMs across separate hypervisor hosts, with NTP and internal DNS
  • โ˜ One internal CA, per-node certificates (server and client use, PKCS#8 keys), and the CA in every system trust store

FoundationDB

  • โ˜ 7.4.x installed from checksum-verified packages, the same version everywhere, packages held
  • โ˜ Mutual TLS (:tls addresses, tls_verify_peers), a process layout with storage, transaction and stateless classes
  • โ˜ double redundancy, ssd engine, three coordinators, status Healthy with fault tolerance 1
  • โ˜ Continuous fdbbackup to an encrypted, off-site target, and a restore rehearsed

Valkey

  • โ˜ TLS only (port 0), the default user off, ACL users with hashed passwords, noeviction, AOF on
  • โ˜ Primary plus two replicas, three Sentinels with quorum 2, and failover tested

Stalwart

  • โ˜ FoundationDB build on three nodes, unique STALWART_HOSTNAME per node, secrets only in stalwart.env
  • โ˜ Setup wizard used only through an SSH tunnel, admin with 2FA or a passkey, and the 8080 listener removed
  • โ˜ In-memory store is Valkey Sentinel over rediss://, coordinator Default, and all nodes visible in the cluster view
  • โ˜ Auto-ban periods set (not permanent), allowed IPs defined, unused listeners removed

Edge and DNS

  • โ˜ HAProxy pair with keepalived, TCP mode, send-proxy-v2, and proxy trusted networks set in Stalwart
  • โ˜ PTR, MX, SPF, DKIM (Ed25519 + RSA), DMARC (moving to reject), MTA-STS, TLS-RPT, autoconfig, and optionally DANE with DNSSEC
  • โ˜ Firewall per role: FDB and Valkey only internal, mail ports only from the load balancers

Operations

  • โ˜ Node, FoundationDB and Valkey failure tests passed, and real client IPs are visible
  • โ˜ Monitoring for FoundationDB health, Valkey role and memory, Stalwart nodes and queues, and DMARC and TLS reports
  • โ˜ Rolling upgrade procedure documented, release notes read before every upgrade