Running several replicas

Kantoor can run as any number of identical copies behind a load balancer, for the web interface, IMAP, POP3, CalDAV and CardDAV alike. No replica is special, and it does not matter which one a connection lands on. This page says how that works, what you have to provide, and what to expect when a replica comes or goes.

The Kubernetes and Docker Compose examples that go with it are in deploy/examples/ in the repository: kubernetes/kantoor.yaml (a Deployment with replicas: 3) and compose/compose.yaml (three replicas behind HAProxy).

The idea

Two kinds of information, kept in two places.

What must be exact or must survive a restart is in Postgres. The mail index (folders, UIDs, modification sequences, flags), DAV collections and their sync tokens, the vault, sessions' users, login lockouts and rate limits (rate_counters), and the attachments of a message being written (staged_attachments). Every replica reads and writes the same rows. Two IMAP sessions on two replicas appending to one mailbox get distinct UIDs because the folder's counters are advanced by one locked update in the database, not by a process.

What only has to be fast is carried between replicas by Erlang distribution. When a message is ingested, a flag is set or a calendar changes, the replica that did it sends a notification through Phoenix.PubSub. With the replicas joined in a cluster the notification reaches every replica at once, so IMAP IDLE sessions and open web pages on the others update immediately (a few tens of milliseconds in the harness below).

The cluster is a speed-up, never the thing correctness rests on. Every waiting party also asks the database, on a timer, whether anything changed:

Who waitsRe-checksEvery
an IMAP session in IDLEits folder's uid_next and highest_modseq3 s (catch_up_ms)
the mail pagethe mailbox's folder counters5 s
calendar, tasks and contacts pagesthe revision of each collection shown5 s

So a replica that has not joined yet, a network split, or a lost message costs a few seconds, not an update.

What you provide

  • Postgres, reached directly. Replicas find each other through it (below), and that needs a plain connection. If your application connects through a pooler in transaction mode (PgBouncer), set KANTOOR_CLUSTER_DATABASE_URL (or KANTOOR_DIRECT_DATABASE_URL) to the database server itself and KANTOOR_DATABASE_POOLER=true; everything else can go through the pooler (see Behind a transaction pooler). If there is no direct address at all, the replicas still work, unclustered, and say so in the log.
  • A load balancer that spreads connections: HTTP for the web interface and DAV, TCP for IMAP and POP3. No sticky sessions are needed (see below).
  • One secret per environment: SECRET_KEY_BASE (the same on every replica; it signs the session cookie) and RELEASE_COOKIE (the same on every replica; it is the password of Erlang distribution).
  • The TLS certificate for IMAP and POP3 on every replica, from the same secret or volume (KANTOOR_MAIL_TLS_CERTFILE and KANTOOR_MAIL_TLS_KEYFILE), or terminate TLS in the load balancer.

Turning it on

SettingMeaning
KANTOOR_CLUSTER=truejoin the cluster (default false: a single replica, no distribution)
KANTOOR_CLUSTER_DATABASE_URLdirect Postgres URL for discovery (default KANTOOR_DIRECT_DATABASE_URL, then DATABASE_URL, which is not used with KANTOOR_DATABASE_POOLER=true: without a direct URL discovery stays off)
RELEASE_COOKIEshared secret of distribution; required
KANTOOR_NODE_HOSTthe address other replicas reach this one on (default: hostname -i; in Kubernetes the pod IP)
RELEASE_NODEnode name, default kantoor@<KANTOOR_NODE_HOST>; must be unique per replica
KANTOOR_DIST_PORTthe one port distribution listens on (default 9100)
KANTOOR_CLUSTER_HEARTBEAT_MShow often a replica announces itself (default 5000)

bin/server turns these into the Erlang flags: a long node name, the cookie, one fixed distribution port, and distribution and epmd bound to the replica's own address. Migrations are safe to run on every replica at once (KANTOOR_MIGRATE_ON_START=true; Ecto takes a lock).

How replicas find each other

Every replica listens on a Postgres channel and announces its node name on it every few seconds; a replica that hears a name it is not connected to dials it. The channel name is derived from a hash of the cookie, not the cookie. A message on the channel is acted on only if it is a well-formed node name. If the database cannot be reached the replica logs it and keeps retrying, and meanwhile runs unclustered on the database catch-up. This is the libcluster_postgres strategy; The project keeps a fork of it with those fixes (branch shiloh of external/libcluster_postgres).

Discovery only says who exists. For two replicas to talk, the node name must resolve and the distribution port must be open between them.

What must never be public

Port 4369 (epmd) and the distribution port (9100 by default) are open between the replicas and to nobody else. Anyone who can reach them and knows the cookie can run code inside the application. In Kubernetes use a NetworkPolicy (the example has one); with Docker Compose, do not publish them (the example does not); on a plain network, a firewall rule. The cookie is a secret like the database password.

Behind a TCP load balancer: client addresses

Login lockouts and the per-client connection limits are per client address. A TCP load balancer hides it unless it sends the PROXY protocol: turn it on in the balancer (provider specific; the Kubernetes example lists the annotations of three) and set KANTOOR_MAIL_PROXY_TRUSTED to the balancer's addresses (CIDR ranges, comma separated). For HTTP, set KANTOOR_TRUSTED_PROXIES as described in the deploy notes. Without this every client looks like the balancer and one lockout locks everyone out.

What to expect

  • No sticky sessions, no hand-over of sessions. A TCP connection (IMAP, POP3, a LiveView WebSocket) stays on its replica for its life. When that replica goes away the client reconnects, to any other replica, and resumes from the database: an IMAP client with QRESYNC gets exactly the changes since it left; a web page remounts from its URL and the database. The harness kills a replica in the middle of IDLE and shows both.
  • Page state that was only in a process is gone on a remount, as it would be on any restart; the exception that mattered, attachments added to a message being written, is staged in Postgres under a key in the page's URL, so the compose page finds them again.
  • Rolling updates: start one new replica before stopping one old (maxSurge: 1, maxUnavailable: 0), and give the old one a grace period (60 s in the examples). Clients that were on it reconnect.
  • Limits are shared where they must be exact. Login lockouts and rate limits count in Postgres, so a client locked out through one replica is locked out on all of them. The cap on simultaneous IMAP/POP3 connections per client address counts live connections in each replica's own memory, on purpose (a crashed replica must not leave a count behind); the effective cap is therefore the configured number times the number of replicas.
  • Long polling. The browser uses a WebSocket. Only if a WebSocket cannot be made does the LiveView client fall back to long polling after 2.5 seconds; Kantoor leaves that fallback enabled. Phoenix routes long-poll requests to the replica that holds the session through the cluster's PubSub, so with the cluster formed any replica can answer; without a cluster that fallback would need a sticky load balancer. The harness does not exercise this path; test/kantoor_web/longpoll_test.exs pins the parts Kantoor controls on one node (the fallback stays enabled, the session token is verified with the shared SECRET_KEY_BASE, and a poll presented as coming through another replica is answered through the pub/sub). The Erlang distribution between real replicas on this path has not been run.
  • Subscribed calendars are refreshed by every replica, once. Each replica looks for subscriptions that are due; the one that wins a conditional update in Postgres (a lease of five minutes on the subscription) fetches the feed, the others do nothing, not even a request. The facts (when the next fetch is due, the lease, the last result, the feed's validators) are in Postgres, so a restart or a replica that disappears loses nothing. See Subscribed calendars.
  • Maintenance jobs (tombstones, the rate-limit sweep, orphan bodies, the vacuum of staged attachments, and the rest) take a Postgres advisory lock, so when every replica starts them only one runs each.

Proving it on one machine

scripts/replicas/run.sh builds the release and starts three replicas as separate processes (addresses 127.0.0.2 to 127.0.0.4, one Postgres) and runs test/replicas/replicas_test.exs against them. What it checks, and what it measured on a development machine (Postgres on the same host):

CheckResult
the replicas form a cluster through Postgresformed by the time the last replica answered its health check (0.7 to 0.9 s later each run)
ingest through replica 1 (a signed Karta push) wakes an IDLE session on replica 239 to 51 ms
the same wakes a LiveView on replica 342 ms
with replica 2 cut off from the others, the IDLE session still hears of it3.0 s (the catch-up interval)
and a LiveView on replica 25.0 s (the catch-up interval)
6 wrong passwords through replica 1 lock the login on replicas 2 and 3refused on both
40 concurrent APPENDs from sessions on two replicasUIDs 1..N, no repeats; modseqs distinct and ordered
expunge 10 on replica 1replicas 2 and 3 agree on UIDs and HIGHESTMODSEQ
kill -9 replica 2 in the middle of IDLE; reconnect to replica 3 with QRESYNCthe new message and the expunge are reported

One run of the production release, inside the CI image, on a test host (2026-11-12, "one production-release run on a test host"): 6 tests passed in 13.9 s; the cluster formed in 758 ms; ingest on replica 1 woke IDLE on replica 2 in 47 ms and the LiveView on replica 3 in 48 ms; with the cluster broken IDLE heard of it after 2968 ms and the LiveView after 5014 ms. The lockout, the 40 concurrent APPENDs, the expunge and the kill -9 with QRESYNC all passed. The numbers above are from a development machine; these from the test host agree with them.

The lockout test fails if the counters are made per replica again, and the catch-up test fails if the catch-up is removed; both were checked by making exactly those changes.