Skip to content

Zero-downtime migration

A zero-downtime migration moves the accounts of a self-hosted mail server to Stalwart one at a time, while both servers run side by side. Users keep the server name, the ports and, in most cases, their passwords. An account that has not moved yet keeps working on the source as before, and an account that has moved is served by Stalwart from its next connection onwards. No account is unreachable for longer than its switch, which holds new logins for a few seconds to a few minutes.

The mode suits every self-hosted source that the Stalwart proxy can sit in front of: the source’s IMAP, POP3, ManageSieve, submission and HTTP ports must be reachable from the proxy, and the public server name must be repointable to the proxy. Hosted services such as Microsoft 365 and Google Workspace do not allow this, because the operator controls neither their network nor their ports; they are migrated with a one-shot migration instead. In Vandelay, this mode is the cutover strategy “Account by account through the migration proxy” (cutover.mode = "proxy").

Three ideas carry the migration. Client sessions are routed per account by the proxy, inbound mail always enters through Stalwart, and nothing is deleted from the source.

The proxy accepts every client connection on the public server name. It reads the account from the credentials the client presents, looks the account up in its mapping store and forwards the session to the destination that holds the account. An account without a mapping goes to the default destination, which is the source, so before the first switch the proxy is transparent and every user keeps working on the source. Switching an account means giving its login names a mapping to Stalwart.

Inbound SMTP carries no login, so the proxy cannot route it per account. It passes port 25 to Stalwart, which is the public mail exchanger for the whole migration and performs split delivery: a message for an account that already exists on Stalwart is delivered locally, and a message for an account still on the source is relayed to the source. Because one server receives all inbound mail from start to finish, the MX records never change.

Vandelay itself never connects through the proxy. It reads the source and writes to Stalwart over their internal addresses, so its own sessions are never held or closed by a switch, and it drives the proxy through the proxy’s management API. The following diagram shows the three paths:

flowchart LR
    CL(["IMAP, POP3, ManageSieve,
submission, HTTP"]):::ink MS(["Sending servers"]):::ink P["Stalwart proxy
mapping store"]:::muted N["Stalwart
public mail exchanger"]:::brand SRC["Source"]:::muted V["Vandelay"]:::muted CL -->|client sessions| P MS -->|SMTP port 25| P P -->|account mapped| N P -->|account not mapped| SRC P -->|all inbound SMTP| N N -->|"split delivery:
account still on source"| SRC V -->|reads| SRC V -->|writes| N V -->|management API| P

Vandelay only reads the source. The source keeps a complete copy of every account as it stood when the account moved, which remains the last fallback until the source is decommissioned. Vandelay itself, however, cannot move an account back: once its logins are mapped to Stalwart they stay there, as described in No rollback.

Before its switch, an account is only read: Vandelay copies it from the source into the account’s archive on the Vandelay host, and repeats delta passes to keep the archive current. Nothing is written to Stalwart for that account yet. The account is created on Stalwart only when it switches, so that split delivery keeps relaying its mail to the source until then.

A switch runs these steps, in order, and the account detail screen shows the step in progress:

  1. Create the account (createAccount). Vandelay creates the account on Stalwart with its aliases and the group memberships it owns. From this moment Stalwart treats the address as local, so new mail for it is delivered on Stalwart instead of being relayed.
  2. Write the archive (exportArchive). The archive is exported into the new account in full.
  3. Hold logins (holdLogins). The proxy delays new logins for every login form of the account, so that no client reconnects to the source while the last changes are copied. The total hold is bounded by the “Hold logins for at most” setting (cutover.hold_logins), which accepts at most 10 minutes.
  4. Close source sessions (kickSource). The proxy closes the account’s open sessions on the source, so that no client keeps changing the account there.
  5. Copy the last changes (finalDelta). Vandelay reads the account once more and writes what changed, including flag changes and folder moves of messages that were already copied. The step stops at the hold deadline.
  6. Map the logins (mapLogins). Each login form of the account (its address, a bare user name where the source accepts one, and its aliases) is mapped to the Stalwart destination, and the proxy’s cached route is invalidated. The held logins proceed to Stalwart.
  7. Close remaining sessions (kick). Sessions that are still open are closed once more, and their clients reconnect to Stalwart.
  8. Catch up (catchUp). Mail that the source still delivered locally after the final copy, for example from an account still on the source to the account that just moved, is copied. Later catch-up passes follow the “Catch-up passes after the switch” setting.
  9. Verify (verify). A sample of the account’s data is compared between the archive and Stalwart, with a verdict of pass, pass with warnings or fail.

Users of the account notice one disconnection, and a short wait at their next login while logins are held. Their clients then see the account’s data as new data: Stalwart assigns its own identifiers, so IMAP clients download the folders again, CalDAV, CardDAV and WebDAV clients synchronise their collections again, and every message carries one of the keywords $hasattachment and $hasnoattachment, which Stalwart sets from the message’s content.

A switch starts when the operator asks for it, from the dashboard or with vandelay migrate switch, or automatically as soon as an account’s first copy is ready when “Switch automatically” (cutover.auto_switch) is on. A step that fails stops the account and waits for a decision, as described in Failed steps.

The proxy is installed and configured as a general-purpose proxy, as described in Installation and the pages that follow it. Vandelay needs Stalwart proxy 2.0 or later, and refuses an older one with proxy admin API has no /api/v1 routes: Stalwart proxy 2.0 or later is required. For the migration, the proxy’s configuration needs:

  • Two destinations. One reaches the source and is the default destination, so that every account without a mapping keeps going there. The other reaches Stalwart. The destination of the source announces clients in the way the source understands (XCLIENT and IMAP ID for Dovecot and Postfix, PROXY protocol for Stalwart), and the destination of Stalwart uses the PROXY protocol. Migrating from Dovecot shows a complete configuration.
  • Inbound SMTP to Stalwart. The SMTP pass-through destination is Stalwart, so that split delivery handles all inbound mail.
  • A writable mapping store. Vandelay writes the mapping of each login through the management API, so the store must accept writes: the file store, the Redis store, or a SQL store with write statements. Pre-flight refuses proxy mode with a read-only store.
  • The management API, with its token. Vandelay authenticates with the token that proxy init created. The API always uses TLS. When Vandelay runs on another host, reach the API through an SSH tunnel to its loopback address rather than binding it to a routable address, as Network exposure explains.

In Vandelay, the proxy is set on the Source: detect step, or with vandelay migrate source:

  • Migration proxy admin URL (proxy.admin_url): the management API, for example https://127.0.0.1:9443.
  • Proxy admin token (proxy.token): a reference to the token, such as file:/etc/proxy/admin-token, never the token itself.
  • Proxy destination of the old server and Proxy destination of Stalwart (proxy.old_destination, proxy.new_destination): the destination names from the proxy configuration. Vandelay proposes them from the proxy’s destination list.
  • Proxy certificate pin (proxy.tls.sha256): the SHA-256 fingerprint of the management API’s certificate. A loopback URL does not match the certificate’s name, and Vandelay never turns certificate verification off, so a self-signed or name-mismatched certificate is accepted only through the pin.
  • Old server internal address (proxy.source_internal): the host:port that pre-flight uses to check that the source answers directly, not through the proxy. When it is empty, it is read from the proxy’s destination for the source. Pre-flight warns when this address answers as the proxy.

The following command sets the proxy for a project, with the token read from the file that proxy init wrote:

Terminal window
vandelay migrate source \
--proxy=https://127.0.0.1:9443 \
--proxy-token=file:/etc/proxy/admin-token \
--proxy-old=legacy \
--proxy-new=stalwart \
--proxy-tls-pin=<64 hexadecimal characters>

vandelay migrate test proxy checks the API, the token, the destinations and the mapping store, and pre-flight runs the same checks again. A certificate pin applies to one host name on every port. When the proxy runs on the source host and its admin URL uses the source’s name, a pin there also makes TLS mandatory for the source’s IMAP and ManageSieve connections; reaching the API through a loopback address or a different host name keeps the two apart.

The source must accept two kinds of connections that it did not see before, and each source page describes the settings for that system:

  • Connections from the proxy. Every client connection now arrives from the proxy’s address. The source must trust the proxy to announce the real client address, or it records every login as coming from the proxy, and its own brute-force protection may block the proxy.
  • Mail relayed from Stalwart. Mail for accounts still on the source arrives from Stalwart, not from the sending servers. The source must accept it from Stalwart’s address without applying SPF, DMARC, greylisting or spam checks that would reject it, and it must deliver mail for its accounts locally rather than to the domain’s MX, which now points at Stalwart.

Dovecot and Postfix shows these settings for a Postfix-based source; the pages of the other systems link to it or describe their own.

Stalwart needs four changes before the proxy goes live. None of them affects clients, because Stalwart serves no users yet. The examples use the command-line interface; every object can also be edited in the WebUI.

Every connection that reaches Stalwart through the proxy comes from the proxy’s address. The proxy therefore starts each forwarded connection with a PROXY protocol header, and Stalwart records the client’s address from it. Stalwart honours the header only from the networks listed in proxyTrustedNetworks of SystemSettings, found under Settings › Network › General:

Terminal window
stalwart-cli update SystemSettings --field 'proxyTrustedNetworks={"203.0.113.10/32":true}'

Replace 203.0.113.10/32 with the proxy’s address, and restart Stalwart afterwards: a ReloadSettings action does not apply this setting, and until the restart, connections forwarded by the proxy fail. The setting also exempts the proxy’s own address from automatic banning; bans and rate limits apply to the client addresses that the headers announce. A connection from a trusted network must start with a PROXY header and is dropped otherwise, so tools on the proxy host reach Stalwart through the proxy or from another host.

Clients find the JMAP, OAuth and WebUI endpoints from the URL that the server advertises. During the migration that URL must be the public server name, which the proxy answers, so that a client following it stays on the proxy and keeps being routed. Stalwart takes its public URL from the STALWART_PUBLIC_URL environment variable:

STALWART_PUBLIC_URL=https://mail.example.org

The variable takes effect at the next restart.

By default, Stalwart rejects mail for a recipient in one of its domains when no account or address matches it. During the migration this is wrong, because most valid recipients have no account on Stalwart until their switch. Split delivery needs relaying for unknown recipients, a relay route to the source and a routing rule that chooses between the two. Vandelay creates the domains during provisioning but sets none of these, so they are configured by hand before the first switch.

The allowRelaying field of each Domain makes Stalwart accept mail for an unknown recipient of the domain and hand it to the routing rule. The field is set by the domain’s identifier:

Terminal window
stalwart-cli query Domain --where name=example.org --fields id
stalwart-cli update Domain <domain-id> --field allowRelaying=true

An MtaRoute of the Relay variant, under Settings › MTA › Outbound › Routes, names the source by its internal address. The link is internal, so the route uses STARTTLS when the source offers it and accepts the source’s certificate without verification. The route’s name, which the routing rule below refers to, is set when the route is created and cannot be changed afterwards:

Terminal window
stalwart-cli create MtaRoute/Relay \
--field name=source \
--field host=mail-old.internal.example.org \
--field port=25 \
--field protocol=smtp \
--field implicitTls=false \
--field allowInvalidCerts=true

The routing rule is the route expression of MtaOutboundStrategy, under Settings › MTA › Outbound › Strategy. It is evaluated for each recipient and returns a route name. The following value delivers locally to a recipient that exists on Stalwart, relays a recipient of a local domain that does not exist yet to the source, and sends every other recipient through the mx route:

{
"route": {
"match": {
"0": {"if": "is_local_address(rcpt)", "then": "'local'"},
"1": {"if": "is_local_domain(rcpt_domain)", "then": "'source'"}
},
"else": "'mx'"
}
}

The order of the two conditions produces the split. A switched account exists on Stalwart and matches the first condition, so its mail stops being relayed without any further change. The route names must match existing routes: an unknown name falls back to MX delivery, which for a migrated domain points back at Stalwart and loops.

Save the current value before applying the new one, so that it can be restored after the migration, then apply the new value saved as route.json:

Terminal window
stalwart-cli get MtaOutboundStrategy --fields route --json | jq '{route}' > route-before.json
stalwart-cli update MtaOutboundStrategy --file route.json

A catch-all address takes precedence over relaying: mail for an unknown recipient goes to the catch-all mailbox and never reaches the source. Vandelay therefore sets catch-all addresses only at Finish, after the last switch, and a catch-all created by hand during the migration breaks split delivery for its domain.

Some source pages offer an optional step that sends the source’s outbound mail through Stalwart, for example so that only one host sends mail for the domain. In that arrangement the source connects to Stalwart’s port 25 as an unauthenticated client and submits mail for remote domains, which Stalwart’s default allowRelaying expression refuses with 550 5.7.1 Relay not allowed.; repeated refusals also count towards the automatic ban of the source’s address. The allowRelaying expression of MtaStageRcpt, under Settings › MTA › Session › RCPT TO Stage, allows relaying for the source’s address while keeping the default for every other client. The following value does this for a source at 203.0.113.30:

{
"allowRelaying": {
"match": {
"0": {"if": "remote_ip == '203.0.113.30'", "then": "true"}
},
"else": "!is_empty(authenticated_as)"
}
}

Apply it, saved as relay.json, with stalwart-cli update MtaStageRcpt --file relay.json. Mail relayed this way arrives unauthenticated, so Stalwart does not sign it with DKIM under its default dkimSignDomain expression; the source keeps signing its own mail.

On a source where users sign in with a bare name such as alice, Stalwart must complete that name with the right domain. It uses its default domain, the defaultDomainId field of SystemSettings, so set it to the domain those users belong to. CalDAV, CardDAV and WebDAV clients whose collection URL contains the bare name, such as /dav/cal/alice/, must be reconfigured after the switch, because Stalwart’s paths hold the full address, percent-encoded, or the account’s numeric identifier prefixed with _. Clients that discover their collections from /.well-known/caldav or /.well-known/carddav find the new path by running discovery again; the proxy cannot hide the change, because it routes HTTP requests by their credentials and does not rewrite paths.

From the moment the proxy goes live, Stalwart receives the domain’s inbound mail under the MX host name, and it sends mail for switched accounts. The following must be in place first:

  • Certificates. The proxy presents a certificate for the public server name to mail clients, and Stalwart presents its own on port 25, because the proxy passes SMTP through without terminating TLS. Once the proxy answers on the public name, ACME challenges validated by connecting to that name (HTTP-01 and TLS-ALPN-01) reach the proxy, so Stalwart uses the DNS-01 challenge or a certificate installed by hand.
  • SPF. The SPF record of each domain authorises Stalwart in addition to the source, which keeps sending mail for the accounts it still holds.
  • MTA-STS and DANE. An MTA-STS policy keeps working as long as Stalwart’s certificate is valid for the MX host name. With DANE, TLSA records that pin the source’s certificate or key are extended with Stalwart’s before the proxy goes live, or senders that validate DANE stop delivering.
  • TTL of the public name. Lowering the TTL of the public server name a day in advance shortens the time during which some clients still reach the source directly after the name is repointed.

DKIM keys are handled by provisioning, which imports the source’s keys or generates new ones per domain, as described in Planning. New keys must be published in DNS before the first switch.

Once the proxy, the source and Stalwart are configured, the proxy takes over the public server name:

  1. Apply the source’s settings for the proxy and reload or restart the source, as its page describes.
  2. Start the proxy and check in its web interface that both destinations are up.
  3. Repoint the public server name, and the MX host name if it differs, to the proxy.
  4. Test each protocol through the proxy with a test account that is still on the source, then send a message from outside to an account on the source and confirm that it arrives through Stalwart’s relay.

This is the only step that interrupts service, for as long as the source takes to reload. After it, every account is still served by the source, and the accounts can be switched at any pace. The Vandelay project is run as described in Server migration up to pre-flight, which checks the proxy and refuses proxy mode when the proxy is missing or its mapping store cannot be written.

When every account has switched and verified, the migration is closed in three stages: Vandelay’s own clean-up, the removal of the migration settings, and the decommissioning of the source. There is no need to hurry: running Stalwart behind the proxy for a while after the last switch lets latent problems surface while the source is still available.

Vandelay’s Finish operation, from the Verify and report screen or with vandelay migrate finish, sets the catch-all addresses held back for split delivery and removes the allowed-IP entry it created for its own host. Deleting the archives of completed accounts and wiping the project’s secret store cannot be undone, so they run only when ticked, or named with --only archives,vault. After Finish the runner stops and the project is read-only, with the report and downloads still available, as described in Finishing a project.

Before removing anything else, confirm that nothing still depends on the source. GET /api/v1/mappings/lookup?identifier=<login> on the proxy’s management API reports "routed_to_default": false for every login, Stalwart’s delivery log shows no more messages through the source route, and the source’s logs show no more client sign-ins.

Then remove the settings that existed only for the migration:

  1. Repoint the public server name from the proxy to Stalwart. Stalwart already advertises that name as its public URL, so clients notice no change. Stop the proxy once the old record’s TTL has expired.

  2. Restore the routing rule first and then delete the relay route, so that no recipient is ever routed to a route that no longer exists:

    Terminal window
    stalwart-cli update MtaOutboundStrategy --file route-before.json
    stalwart-cli query MtaRoute --where name=source --fields id
    stalwart-cli delete MtaRoute --ids <route-id>
  3. Turn allowRelaying off on each domain, so that mail for an address that does not exist is rejected again.

  4. Remove the proxy’s address from proxyTrustedNetworks and restart Stalwart. A host that later takes over that address could otherwise announce arbitrary client addresses.

  5. Revert the limits raised for the bulk import, as listed in Planning, and raise the TTLs that were lowered.

Shut the source down only after a period of confidence that Stalwart works on its own. Until then, the source holds a copy of every account as it stood at its switch. Once it is gone, the migration is final.