Running several replicas
Karta runs as any number of identical replicas of one release, in front of
load balancers, on one Postgres and one blob store. No replica is special:
HTTP APIs, the admin pages, SMTP submission and the mx listener all run on
every replica, and every claim, limit and schedule lives in the database.
Ready-to-use manifests are in deploy/examples/ (Kubernetes and Docker
Compose).
This page says what each replica keeps in memory and what that means when there are several, what a replica that is stopped or killed leaves behind, and what the optional cluster adds.
What the replicas share
| Shared | Where | Notes |
|---|---|---|
| Data | one Postgres | Direct connections, or a pooler with KARTA_DATABASE_POOLER (see below). Run bin/migrate once per release, before the replicas start (a Kubernetes Job or an init step). |
| Message bodies | one S3 bucket (KARTA_S3_*) | The Local blob store is a directory: use it with several replicas only on a volume they all mount. |
| Secrets | the same environment | SECRET_KEY_BASE (sessions, LiveView), KARTA_VAULT_KEY (data at rest), and with a cluster RELEASE_COOKIE. A replica with another value cannot read what the others wrote. |
| Image | the same release | Admin assets are digested; a rolling update serves old pages from old replicas until they go. |
Nothing needs sticky sessions, and no session is handed from one process to another: a TCP connection lives on its replica; when that replica goes, clients reconnect elsewhere and the state comes from the database.
Audit: what each replica keeps, and what happens with N
Correct with N replicas and no cluster means exactly that; every item here was run with three replicas on one database and no connection between them.
| State | Kept | With N replicas |
|---|---|---|
| Delivery, webhook, inbound and report-run claims | database, one conditional update (Karta.Claim) | Correct. A row is taken by one replica; a second run at the same moment skips it. |
| Scheduled work (sweep, domain checks and DKIM rotation, report planner and dispatcher, retention, pruning) | Oban cron in the database | Correct. One job per tick whatever the replicas; the work inside is claimed as above. |
| Rate limits for credentials, logins, TOTP, API key verification, warm-up counts | database (Karta.Limits, Karta.Outbound.Warmup) | Correct and exact across replicas. |
| Spool directory | local disk, the message while DATA is read | A write buffer, not a correctness dependency. 250 is sent only after the body is in the blob store and the database says the message is accepted; a replica that is replaced loses only mail it had not yet acknowledged, which the sender still holds. Use an emptyDir. It is emptied at start. |
| Admin sessions | signed cookie plus a row in the database | Correct. Any replica accepts a session; sign-out and removing a user end it everywhere (see Announcements). |
| OpenID Connect sign-in | state, nonce and PKCE verifier in the session cookie | Correct; the callback may land on another replica than the start. |
| LiveView | a WebSocket to one replica | A page rendered by one replica and connected to another mounts and reads fresh. A page connected to one replica sees changes made through another (Announcements). Long polling is enabled as the fallback transport; it needs the cluster (or a load balancer that keeps a client on one replica). WebSocket needs neither. |
| Route cache (the mx listener's recipients), live-update announcements, disconnect of a session | memory plus Karta.Relay | Correct without a cluster: announced through the database in well under a second. Without the relay a change could take a minute to reach other replicas, and the mx listener on them could refuse a new address in between. |
Outbound throttle (connections=, per_minute= per destination) | memory, per replica | Cluster: each replica counts its share (the limit divided by the replicas connected, rounded up). Without a cluster: each counts the whole limit, so up to N times the limit reaches a destination. Exact and durable limits are not worth a database round trip per delivery; set the limit for the whole fleet and run the cluster, or divide it yourself. |
| Per-client SMTP connection limits | memory, per replica | A TCP connection is on one replica, so each protects its own sockets. The client's address must be the real one: see SMTP behind a TCP load balancer. |
| Tracking-event and MTA-STS fetch limits | memory, per replica | N times the limit in the worst case; both are small and guard the replica's own work. |
DNS answers, MTA-STS policies, DANE records, the Public Suffix List, API key verification (Karta.Credentials.KeyCache), TLS certificates | memory, per replica | Pure caches: another replica fills its own. A revoked key or a suspended server takes effect at once, because the credential is read from the database on every request. |
IP pool addresses (Karta.IPPools.Monitor) | the replica's network interfaces | Per replica by design: a pool's queue runs on the replica that holds the address. Replicas that share one egress address use the default queue. |
| Metrics | memory, per replica | Scrape every replica (see Metrics). |
Announcements: live updates, routes, sign-out
Changes that other replicas need to see at once go through Karta.Relay:
the admin pages' live updates (Karta.Changes), the route cache's reload,
and the disconnect of a signed-out or removed user's open pages. Each is
sent on the replica and over Postgres LISTEN/NOTIFY (through Oban's
notifier, which every replica already listens on), and, when the replicas
are clustered, over the cluster as well; a replica ignores what it sent
itself and what a connected replica already sent it. So an announcement
reaches every replica once, clustered or not, in a split or not.
Behind a transaction pooler NOTIFY is not carried and Oban's notifier is
Oban.Notifiers.PG, which needs the cluster: without it the announcements
reach only the replica that made them, and the route cache catches up at its
next reload (every minute).
Stopping a replica
- Rolled (SIGTERM): the listeners stop accepting, SMTP sessions that are
open get
421 4.3.2 Service shutting down(the sender tries again, on another replica), and the delivery queue stops starting jobs and waits for the running ones: Oban'sshutdown_grace_period, 15 seconds. Measured: five deliveries that each took ten seconds ended in 6.3 seconds after the signal and all five were delivered once; an idle replica exits in under a second. A delivery that is still running after the grace period is stopped; it is not lost (below). Give KubernetesterminationGracePeriodSeconds: 30, and apreStopthat sleeps a few seconds so the load balancers stop sending first. - Killed (
kill -9, a node that vanishes): nothing is lost and nothing is delivered twice that was recorded. A message the replica was delivering when it died keeps its claim, which is longer than a delivery may run (an hour), and is delivered after it ends; at most as many messages as the replica's delivery concurrency (KARTA_OUTBOUND_CONCURRENCY, 10) wait so. Measured with akill -9during a burst of 500 messages across three replicas: 499 arrived at the destination at once, one an hour later, none twice. A message delivered to the destination whose record was not written before the kill can be delivered again; that is inherent to any mail system that retries. - A full rollout, a split, a replica that has not joined the cluster: the same as above. The cluster is never in the path of a claim.
SMTP behind a TCP load balancer
A TCP load balancer hides the client's address from Karta. Run the balancer
with the PROXY protocol (version 2) and tell Karta the balancer's ranges with
KARTA_SMTP_TRUSTED_PROXIES: then the per-client limits, the Received:
header and SPF see the real client (see SMTP listeners).
Every listener then accepts connections only from those ranges, so the
Kubernetes health checks of a Service of type LoadBalancer must also speak
PROXY or go to a port that is not a listener; the example probes the HTTP port
instead (/readyz).
Metrics
Scrape every replica's metrics port (METRICS_PORT, internal only), not the
Service: a pod monitor or a headless Service. Counters (rate()) are added
across replicas, and a replica that restarts resets only its own. The
gauges that the replicas read from the database (karta_outbound_queue_*,
karta_inbound_deliveries, karta_webhook_backlog_deliveries,
karta_suppressions_entries) are the same on every replica, so aggregate
them with max, not sum: the dashboard and the alerts in priv/ do. The
per-address gauges (karta_ip_pool_address_held) are per replica by design.
The cluster
Replicas may form an Erlang cluster. It is for speed and for the throttle's share; nothing depends on it for correctness: every claim, limit and schedule stays in the database, so a replica that has not joined, a network split, or a rollout of every replica loses nothing.
Without the cluster: announcements still reach every replica (through the database); the throttle counts the whole limit on each replica; long polling needs a load balancer that keeps a client on one replica. With it: announcements arrive over the cluster as well, the throttle splits its limits over the replicas, and long polling works from any replica.
Set KARTA_CLUSTER=true. Replicas find each other through the database:
each sends a heartbeat over LISTEN/NOTIFY and connects to the nodes it
hears from. This needs a direct connection to Postgres (LISTEN does not
pass a transaction pooler): KARTA_CLUSTER_DATABASE_URL is that connection
(default: the main DATABASE_URL; required when KARTA_DATABASE_POOLER
is set, otherwise clustering stays off and one line in the log says so).
Discovery only says who exists; the replicas still need:
- a node name the others can reach: the release's
bin/server(notenv.sh, sobin/migrateandbin/karta remotedo not start a second node of the same name) setsRELEASE_DISTRIBUTION=nameandRELEASE_NODE=karta@<address>fromKARTA_NODE_HOST, or the addresshostname -igives (the pod's address); - the same
RELEASE_COOKIEeverywhere, kept out of images and logs; - TCP 4369 (epmd) and one distribution port (
KARTA_DIST_PORT, default 9100) open between the replicas only (a KubernetesNetworkPolicy; the example has one). The cookie is the only credential of the distribution, and a node that holds it can run code on every replica.
bin/server refuses to start a replica with KARTA_CLUSTER=true and no cookie or address; the epmd and distribution ports are bound to the replica's own address when it is an IPv4 address. Discovery itself fails soft: if it cannot reach the database it keeps retrying and Karta runs unclustered meanwhile.
Checking it yourself
dev/replicas/run.sh [clustered|unclustered|broken] starts three replicas
(mix phx.server) on one machine against a Postgres and a resolver of its own
(Docker, ports 57433 and 57353, stopped on exit) and a test destination that
counts what it receives, and checks:
- the replicas find each other through the database (or,
unclustered, are not connected at all;brokencuts one off on purpose after they joined); - an announcement made on one replica arrives once on each of the others;
- 3,000 rows taken by all three replicas at the same moment are taken once;
- a burst of 500 messages submitted through
/api/v2round robin to the three replicas arrives at the destination, none twice and none lost, in total, with one replica killed (kill -9) 3 seconds in (what it was delivering is delayed by its claim, never lost), and with one rolled (SIGTERM).
It takes about ten minutes and prints ALL CHECKS PASSED (<mode>). Run it in
each of the three modes: the results are the same, with the cluster only
faster. Its exit status is the number of failed checks.
On a machine without Elixir, dev/replicas/run-in-docker.sh <mode> runs the
same harness inside the CI Elixir image, on a private Docker network with a
throwaway Postgres and resolver, and removes all of it on exit.
What it does not cover. The replicas run as mix phx.server in dev mode,
not as releases: a production release sends to port 25 and refuses loopback
addresses, so it cannot deliver to a test destination on one machine. The
release-specific parts (bin/server, the node name, the distribution port) are
checked by starting a release by hand. A release can be pointed at a test
destination without changing its defaults: KARTA_OUTBOUND_PORT (tests only; the
port deliveries connect to) and KARTA_NET_GUARD_ALLOWED_NETWORKS (the destination's
private or loopback address, e.g. 127.0.0.1/32), with a resolver that answers the
test domain's MX with that address. The harness does not use them yet. It also does not run the report
dispatcher end to end across replicas (the claim it uses is checked on the
same table, from all three replicas at once), and it does not drive admin pages
in a browser across replicas (that was done by hand: a page rendered by one
replica, its WebSocket sent to another, a message sent through a third). It
does not check the example manifests in deploy/examples/ by running them (they were
validated against the Kubernetes schemas and with docker compose config, and the
parts of the Compose example that are not Karta were run). The PROXY protocol is
checked against HAProxy 3.1 (test/karta/smtp/haproxy_test.exs, opt-in), not against
a cloud load balancer.