---
title: "episomer: containers and multi-machine deployment"
author: "European Centre for Disease Prevention and Control (ECDC)"
output: 
  rmarkdown::html_vignette  
vignette: >
  %\VignetteIndexEntry{episomer: containers and multi-machine deployment}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, echo = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

This document assumes a reader who administers the machines `{episomer}`
runs on: someone comfortable with a terminal, with Docker or Kubernetes, and with environment
variables.

# Running episomer in containers

A container deployment of `{episomer}` is described by three files at the root of the
source repository: a `Dockerfile`, which describes the image, a `compose.yml`, which describes the
services to run, and a `Makefile`, which holds the shortcuts used to drive them. None of the three
is in the installed R package — neither the CRAN version nor a `.tar.gz` of the package contains
them — and there is no ready-made image to pull, so a container deployment starts by cloning the
sources and building an image from them.

## What the image contains

The `Dockerfile` builds in three stages:

-   **base** — a `rocker/r-base` image with the runtime prerequisites
    already installed: a Java 21 runtime, the system libraries the R dependencies need, and the
    LaTeX and pandoc installation the dashboard uses to export PDF and Markdown reports. A reader of
    the *Prerequisites* section of the main user documentation will recognise the list; in a
    container it is already done for you.
-   **build** — adds the Java JDK and sbt, compiles the Scala code into the
    JAR that `{episomer}` embeds, installs the R dependencies and then `{episomer}` itself.
-   **final** — the base image plus the installed R library. It runs as an
    unprivileged user (uid 1000 by default, configurable with the `EPISOMER_USER` build
    argument).

One image serves every role. Which service a container runs is decided at run time by
the `EPISOMER_RUN` environment variable, which the entry point of the image reads. You do not
normally set it yourself: `compose.yml` already gives each of its three services the right value.
It is worth knowing about for two reasons — it is what makes three containers out of one image, and
it is what you would set on a fourth service if you wanted to serve the Shiny app from a container
too:

| `EPISOMER_RUN` | What the container runs |
|---|---|
| `FS` | the episomer database, after a silent `setup()` that downloads and prepares everything missing |
| `SEARCH` | the post collection and processing loop |
| `DETECT` | the requirements and alert detection loop |
| `APP` | the full Shiny app |
| `DASH` | the Shiny app, dashboard page only |
| `ADMIN` | the Shiny app, admin pages only |

A container started without `EPISOMER_RUN` says so and sleeps, rather than
guessing.

## Configuring episomer through the environment

A container has no interactive console, so the setup wizard cannot ask
anything. Everything it would ask is instead given through environment variables.

### Where things live

| Variable | What it is |
|---|---|
| `EPI_HOME` | the data directory inside the container, i.e. what you would pass to `setup("data_dir")`. In `compose.yml` it is `/episomer-data`, backed by a volume. |
| `EPI_HOST` | the address of the episomer database, for every container that is not the database itself (`http://fs:8080` in `compose.yml`). See also *Running episomer on several machines*. |
| `EPISOMER_INSTANCE` | the name this container is known by in the logs and in the services status table. Always set it: a container host name is a random hexadecimal string. |
| `EPISOMER_LOGS_TO_STDOUT` | set it to `TRUE` in a container. `{episomer}` writes one log file per service under `<data directory>/jobs` by default, which is the right shape for a machine an operator logs into and the wrong one for a container: `docker logs` and `kubectl logs` read the standard output of the container and nothing else, so with the default the logs exist and are unreachable. |

### Settings: `EPISOMER_OPTION_*`

Any setting of `properties.json` can be given through the environment by
prefixing its name with `EPISOMER_OPTION_` and writing it in upper case. For instance
`EPISOMER_OPTION_RUNNER_TTL_SEARCH=600` sets the `runner_ttl_search` property, and
`EPISOMER_OPTION_SM_ACTIVATED_MASTODON=TRUE` activates Mastodon.

Two things are worth knowing:

-   **the precedence is defaults < `properties.json` < `EPISOMER_OPTION_*`.**
    An environment variable that is set always wins over the value stored in `properties.json`,
    including on an existing data directory: change the manifest (compose, Kubernetes) and restart.
    Properties without a matching variable keep their stored value. Note that a setting fixed
    by the environment cannot be changed durably from the Shiny app or `setup()`: the variable
    wins again at the next start.
-   **values are typed and checked at startup.** A property whose default is
    a number must be given a number, one whose default is a boolean must be given a boolean
    (`TRUE`/`FALSE`, or `1`/`0`). An unusable value stops the container immediately, with a message
    naming the variable, rather than being discovered hours later in the middle of a loop.

The social media of the deployment are set the same way, which is what
replaces option 6 of the wizard:

| Variable | What it does |
|---|---|
| `EPISOMER_OPTION_SM_ACTIVATED_BLUESKY` | whether posts are collected from Bluesky |
| `EPISOMER_OPTION_SM_ALERTS_BLUESKY` | whether Bluesky posts contribute to alert detection |
| `EPISOMER_OPTION_SM_ACTIVATED_MASTODON` | whether posts are collected from Mastodon |
| `EPISOMER_OPTION_SM_ALERTS_MASTODON` | whether Mastodon posts contribute to alert detection |
| `EPISOMER_OPTION_MASTODON_INSTANCES` | the Mastodon instances to collect from, separated by semicolons, e.g. `mastodon.social;mstdn.party` |
| `EPISOMER_OPTION_LOG_MAX_SIZE_MB` | size in MB above which a service log under `jobs/` is moved to `<name>.log.1` when the service starts (default 50, `0` disables) |
| `EPISOMER_OPTION_SNAPSHOT_LOG_LINES` | number of last lines of each log included in a snapshot (default 100000, `0` = whole file) |

### Languages: `EPISOMER_LANGUAGES`

The languages of the deployment are set with a single variable, which replaces the language
question of the setup wizard:

```sh
EPISOMER_LANGUAGES="en;fr;pt;es"
```

It is a list of language codes separated by semicolons, taken from the same list as the wizard and
the Shiny app and matched without regard to case. Unlike the `EPISOMER_OPTION_*` settings it is
applied **at every start**, including on an existing data directory, which is what lets you change
the languages of a deployment that is already running:

-   **an added language** is downloaded at the next start (its word vectors are large), and is
    taken into account by the language model retraining;
-   **a removed language** has its local vector files deleted, so that the data directory does not
    quietly fill the volume. The posts already collected are not touched;
-   **an unchanged list** does nothing, so a container restarting with the same compose file does
    not trigger a retraining;
-   **an unknown code, or an empty list,** stops the container immediately with a message naming the
    variable.

The variable is read by the `fs` service only, the one that runs the setup.

### Credentials: `EPISOMER_SECRET_*`

Credentials never go into `properties.json`; they are kept in an encrypted
keyring, and in a container that keyring is a password-protected file inside the data directory. Two
kinds of variables feed it:

-   `EPISOMER_KR_PASSWORD`, the password that unlocks the keyring, or
    `EPISOMER_KR_PASSWORD_FILE`, the path of a file whose first line is that password. Without one
    of the two, a non-interactive `{episomer}` cannot open its keyring and stops with a message
    saying so.
-   one `EPISOMER_SECRET_<NAME>` per credential, or
    `EPISOMER_SECRET_<NAME>_FILE` pointing at a file that contains it. The `_FILE` form is the one to
    use: it is what Docker secrets and Kubernetes secret mounts provide, and it keeps the value out
    of the container's environment, where `docker inspect` would show it.

The names follow the social media:

| Credential | Variable |
|---|---|
| Bluesky user | `EPISOMER_SECRET_BLUESKY_USER` |
| Bluesky password | `EPISOMER_SECRET_BLUESKY_PASSWORD` |
| Mastodon access token for one instance | `EPISOMER_SECRET_MASTODON_<INSTANCE>_TOKEN`, where `<INSTANCE>` is the instance domain in upper case with its dots replaced by underscores — `mstdn.party` becomes `EPISOMER_SECRET_MASTODON_MSTDN_PARTY_TOKEN` |

## The provided Docker Compose deployment

`compose.yml` starts the three services of a working
`{episomer}`:

-   **`fs`** — the episomer database. It is the only service that holds data:
    the data directory is mounted into it as a volume, and it publishes the database port. Before
    starting the database it runs the setup wizard silently (`setup(silent = TRUE, launch =
    FALSE)`), which downloads and prepares whatever is missing — Java dependencies, GeoNames,
    language models — and then starts the database. The first start of a fresh data directory is
    therefore long.
-   **`search`** — the post collection. It waits for `fs` to be healthy,
    talks to it over HTTP through `EPI_HOST`, and mounts only the `jobs` sub-directory. Its own
    health check asks `{episomer}` whether the social media authentication still works, so a
    container whose credentials have expired is reported as unhealthy rather than quietly collecting
    nothing.
-   **`detect`** — the requirements and alert detection pipeline, with the
    same shape.

`search` and `detect` are declared `restart: on-failure`, which is what makes
a container that cannot claim its lease — see the next part — retry until the lease is free, instead
of exiting for good.

### Starting it

Work from a clone of the `{episomer}` source repository. The whole clone is the build context: the image is built from the R sources and the Scala sources it contains, and the packaging step run inside it goes through the `Makefile`, which is why the three files have to travel together.

Everything else is one file to write, named `.env`, next to `compose.yml`. Docker Compose reads it by itself; it carries both the values `compose.yml` interpolates and the credentials Compose hands to the containers as secrets.

```sh
# .env, next to compose.yml

# Where the data directory lives on the host, and on which port the database is published
EPI_HOME=/srv/episomer-data
EPISOMER_FS_PORT=8080

# The password protecting the episomer keyring inside the containers. Choose it once:
# changing it later makes the credentials already stored unreadable.
EPISOMER_KR_PASSWORD=...

# Social media credentials, as the setup wizard would have asked for them
EPISOMER_SECRET_BLUESKY_USER=...
EPISOMER_SECRET_BLUESKY_PASSWORD=...

# One token per Mastodon instance collected, only if Mastodon is activated
EPISOMER_SECRET_MASTODON_MASTODON_SOCIAL_TOKEN=...
EPISOMER_SECRET_MASTODON_MSTDN_PARTY_TOKEN=...
```

Then, from that directory:

```sh
docker compose up --build -d     # build the image if needed, then start fs, search and detect
docker compose ps                # what is running
docker compose logs -f fs        # follow one service
docker compose down              # stop everything
```

The very first `up` is long: it compiles the Scala code and installs every R dependency into the image, and then the `fs` container runs the setup wizard silently and downloads GeoNames and the language models. Follow it with `docker compose logs -f fs`; `search` and `detect` wait for the database to report itself healthy before they start.

The `Makefile` offers the same two operations as `make compose-up` and `make compose-down`. They do one thing more than the commands above: instead of reading the credentials from `.env`, they fetch them from a `pass` password store, under names such as `epitools/ecdc_bluesky_user`. It is the better option if you already keep your secrets in `pass`; if you do not, use `.env` and the plain `docker compose` commands above, which need nothing else installed.

### A word on the credentials

`.env` is a plain text file. It is convenient, and it is what Compose expects, but it must be treated as a secret: keep it out of version control and restrict it to its owner (`chmod 600 .env`).

Two alternatives avoid writing the credentials down at all. The variables can simply be exported in the shell that calls `docker compose`, which is what a CI system or an orchestrator's secret store does naturally. Or the `secrets` section of `compose.yml` can be changed from `environment:` to `file:`, so that Compose reads each credential from a file you provide rather than from a variable. The containers see no difference either way: they only ever read `/run/secrets/...`.

One last thing to keep consistent: the Mastodon instances appear in three places that must agree — `EPISOMER_OPTION_MASTODON_INSTANCES` in `compose.yml`, the matching `EPISOMER_SECRET_MASTODON_<INSTANCE>_TOKEN_FILE` entries next to it, and the values in `.env`. Collecting from a different instance means editing all three.

Note that `compose.yml` starts no Shiny app: the three services above are
what a server deployment needs, and the app is expected to be run where the analysts are. To serve
it from a container as well, add a service using the same image with `EPISOMER_RUN` set to `APP`,
`DASH` or `ADMIN`, `EPI_HOST` pointing at `fs`, and its port published.

## Two addresses, not one

Two settings of `compose.yml` look redundant and are not, and a deployment
that changes one without the other will not work:

-   `EPISOMER_OPTION_FS_URL` is the *interface the database binds*, not an
    address anything dials. It is a wildcard (`http://0.0.0.0`) because that is the one value that
    works unchanged under Docker and under Kubernetes, where a service name resolves to an address
    the container does not itself hold.
-   `EPISOMER_OPTION_FS_SETUP_HOST` and `EPISOMER_OPTION_FS_SETUP_PORT` are
    where the *temporary* database of the language model retraining binds. They are deliberately as
    narrow as possible — loopback, on a port that is neither published nor routed — because while
    that retraining runs, the collection and the alert detection must **not** find a database, or
    they would start working against untrained language models.

Opposite requirements, hence opposite values.

# Running episomer on several machines

This section is about the case: **one database, several machines**
— typically because the post collection has become too heavy for one host, or because you want a
second machine ready to take over when the first one is stopped for maintenance.

## The shape of a multi-machine deployment

There is exactly **one embedded database** (the `fs` service). It owns the Lucene indexes on its
local disk and it is the only process allowed to open them. Every other machine talks to it over
HTTP and holds no data of its own:

```
                    +--------------------------------------+
                    |  machine A        fs (the database)  |
                    |  Lucene indexes, runners/, *.json    |
                    +--------------------------------------+
                       ^                ^               ^
             HTTP      |                |               |     HTTP
       +---------------+                |               +----------------+
       |                                |                                |
+---------------+              +-----------------+             +------------------+
| machine B     |              | machine C       |             | machine D        |
| search loop   |              | search loop     |             | detect loop      |
| (collection)  |              | (standby)       |             | (alerts)         |
+---------------+              +-----------------+             +------------------+
```

Point every machine at the same database by setting `EPI_HOST` (or the `fs_url` / `fs_port`
properties) to the address of the machine running `fs`. A machine that is only a `search` or a
`detect` worker needs no data folder of its own beyond a scratch directory: `jobs/` for its logs and
a handful of small local files.

> The Shiny app is **not** a machine of that cluster. It reads and writes through the database like
> everything else, it never runs a collection loop, and several people may open it at the same time.

## One runner, one machine at a time

The problem a shared database creates is duplication. If two machines run the post collection for
Bluesky, both ask the API for the same posts and both store them — the alerts would then be computed
on doubled counts. `{episomer}` prevents this with **runner leases**.

A *runner* is a unit of work that only one machine may perform at a given moment:

| Runner | Held by | What it does |
|---|---|---|
| `fs` | `fs_loop()` | the embedded database |
| `fs_mon` | the monitor started by `fs_loop()` | watches the database and beats for it |
| `search` | `search_loop()` | the parent of the collection service |
| `search.<network>` | one collection worker per social medium, e.g. `search.bluesky` | collects posts from that network |
| `detect` | `detect_loop()` | the alerts pipeline |

A **lease** is the right, granted for a limited time and renewable, to be one of those runners. It is
one small JSON file per runner, stored on the database machine under `runners/`, and it works like a
key left on a hook:

* a service that starts **claims** the lease of its runner — it writes its identity in the file;
* while it works it **renews** it regularly, which only updates the file's modification time. This
  is the *heartbeat*;
* if the file has not been renewed for longer than its **time-to-live (TTL)**, the holder is presumed
  dead and another machine may take the runner over;
* a service that stops properly **releases** its lease, so the takeover is immediate rather than
  TTL-long;
* before every meaningful write — posting collected posts, saving `topics.json`, saving `tasks.json`,
  sending alert emails — a service **checks that it still holds its lease**, and exits cleanly if it
  does not.

A machine that cannot claim a lease does not start that runner. It says so in its log, naming the
machine that holds it:

```
Runner 'search.bluesky' is already held by another instance (7f3a1c2e) running on host
'machine-B' since 2026-08-28T09:14:02Z, last seen 12 seconds ago (lease TTL: 300 seconds).
This instance will not start it.
```

The exclusivity is per *runner*, not per service, which is what allows two useful setups:

* **standby** — machine C runs the same collection as machine B, fails to claim, and retries until
  machine B stops or disappears;
* **splitting the collection** — in principle machine B collects Bluesky while machine C collects
  Mastodon, since `search.bluesky` and `search.mastodon.<host>` are two independent leases. Be aware
  that this is *not* usable as it stands: `search_loop()` also claims the parent `search` lease
  before starting its workers, so the second machine is refused before it reaches them. This is a
  known and deliberate limit of the current release.

## Naming your machines: `EPISOMER_INSTANCE`

Every message and every status line about the leases names the machine that holds them, so give each
machine a name you will recognise:

```sh
export EPISOMER_INSTANCE="machine-B"
```

Without it `{episomer}` falls back on the host name, which inside a container is a random hexadecimal
string. Two machines must not share a value — not because it would be unsafe (`{episomer}` requires a
second, local proof before it declares a holder dead), but because you would not be able to tell
them apart in the logs or in the status table.

The name is *not* stored in the database: it describes the machine, not the deployment, and it is
read again at every start.

## Settings

Five properties tune the mechanism. They are stored in `properties.json`, which every machine reads,
so they belong to the whole cluster. They are **deliberately absent from the Shiny configuration
page**: a TTL mistyped there would break exclusivity for every machine at once, and these are
deployment knobs rather than analysis settings. Set them in `properties.json`, or through the
environment (`EPISOMER_OPTION_RUNNER_TTL_SEARCH=600` and so on; the environment wins over `properties.json`, see the section on `EPISOMER_OPTION_*` settings).

| Property | Default | What it is |
|---|---|---|
| `runner_heartbeat_span` | 30 s | time between two renewals |
| `runner_ttl_fs` | 120 s | TTL of the `fs` and `fs_mon` leases |
| `runner_ttl_search` | 300 s | TTL of `search` and `search.<network>` |
| `runner_ttl_detect` | 1800 s | TTL of `detect` |
| `runner_claim_guard` | 5 s | pause between claiming a lease and reading it back |

Two rules of thumb are worth keeping:

* **the TTL is your failover latency.** A machine that disappears without releasing anything — a
  crash, a cut network, `docker kill` — is replaced one TTL later, never sooner. Lowering a TTL to
  speed that up is the classic mistake: it makes healthy but busy services look dead, and *that*
  produces the duplication the whole mechanism exists to prevent;
* **keep the heartbeat roughly ten times shorter than the shortest TTL.** A few renewals lost in a
  row — a slow database, a network hiccup — must not be enough to expire a live lease.

`detect` has a much longer TTL than the others on purpose: one of its tasks (alert detection,
geolocation, aggregation) can legitimately run for a very long time without writing anything, and a
working service that looks dead is worse than a dead one noticed late.

# Operator guide: reading the runner leases {#leases}

## From the Shiny app

The configuration page shows, in its *Status* section, a table with
one row per runner *currently holding a lease*, wherever in the cluster it runs:

| Runner | Status | Host | Last seen | Since |
|---|---|---|---|---|
| episomer database (`fs`) | running | `machine-A (this machine)` | 4 s ago | 2026-08-28 07:02 UTC |
| Data collection & processing (`search.bluesky`) | stale (no heartbeat for 8 min) | `machine-B` | 22 min ago | 2026-08-28 07:05 UTC |
| Alerts (`detect`) | crashed here | `machine-A (this machine)` | 3 min ago | 2026-08-28 06:58 UTC |

How to read it:

* **a runner with no row is free.** Releasing a lease removes its file, so "nothing holds it" and
  "it has never been started" look the same here — which is what you want. The table answers *who is
  holding what*, not *what could be started*; the Running/Stopped labels above it answer that.
* **`running`** — the holder renewed its lease less than one TTL ago. *Last seen* is the age of that
  renewal and should stay below `runner_heartbeat_span` most of the time.
* **`stale (no heartbeat for …)`** — nobody has renewed this lease for longer than its TTL. The
  holder is presumed dead and any machine may now take the runner over. It usually means the machine
  named in *Host* was stopped brutally, is unreachable, or has become too slow to renew. Look at that
  machine before doing anything else.
* **`crashed here`** — a stronger statement than `stale`, and a certainty rather than a presumption:
  the holder was a process of *this very machine* and the operating system says it is gone. It is
  reclaimable immediately, without waiting for the TTL. Restarting the service is the right move.
* **`Host`** is the `EPISOMER_INSTANCE` of the holder, with `(this machine)` appended when it is the
  machine you are reading the app from.
* **`Since`** is when this holder became the holder; it does not move when the lease is renewed.
  A long *Since* next to a short *Last seen* is exactly what a healthy runner looks like. It is shown
  in UTC so that it can be compared with the files and with the logs of the other machines.

Two runners are deliberately kept out of that table, because they are
internal plumbing rather than services a reader would recognise: `fs_mon`, the watchdog that keeps
the episomer database alive, which would read as a second database next to it; and `search`, the
parent lease of the collection. `search_loop()` claims `search` and then spends its life waiting for
its workers, with no iteration left to renew anything, so that lease goes stale a few minutes after a
perfectly healthy start. Its `search.<network>` children are the rows that say whether collection is
actually happening, and they are the rows to trust.

## From the files

Everything the table shows comes from `<data folder>/runners/` on the database machine, and reading
it by hand is often the fastest way to understand a situation:

```sh
ls -l --time-style=full-iso runners/
cat runners/search.bluesky.json
```

```json
{
  "runner": "search.bluesky",
  "service": "search",
  "instance_id": "7f3a1c2e9b",
  "host": "machine-B",
  "pid": 41,
  "episomer_version": "4.0.5",
  "claimed_at": "2026-08-28T07:05:11Z",
  "renewed_at": "2026-08-28T07:05:11Z"
}
```

Three things are worth knowing before drawing conclusions from it:

1. **the freshness of a lease is the file's modification time, not anything inside the JSON.**
   `renewed_at` is only rewritten when the whole file is rewritten, i.e. when the lease is claimed —
   renewing merely touches the file. This is on purpose: the modification time is produced by the
   single machine hosting the database, so no clock difference between the other machines can make a
   dead lease look alive. Use `ls -l` (or the *Last seen* column), never `renewed_at`.
2. **`instance_id` changes at every restart, `host` does not.** `host` is the `EPISOMER_INSTANCE`
   value, i.e. the machine; `instance_id` identifies one *process*. Two lines with the same `host`
   and different `instance_id` are the same machine having restarted.
3. **`pid` is only meaningful on `host` itself**, and only when the two are read together — which is
   what lets a crashed runner be detected instantly on its own machine rather than one TTL later.

`runners/old/` holds the leases that were released, named `<runner>.<instance_id>.json`, with their
modification time as the release time. Nothing reads that folder; it is a trail left for you, and it
is the place to look to answer "when did that machine hand the collection over?".

## Common situations

| Symptom | What it means | What to do |
|---|---|---|
| A service refuses to start, naming another host | That machine holds the lease and is alive | Stop it there, or let it release the lease |
| Same, but naming *this* host | Another process of this machine is registered | The message names the PID to stop |
| A row stays `stale` and nothing takes over | No other machine is configured to run that runner | Start it somewhere, or restart the machine named in *Host* |
| A row is `stale` while the service is clearly working | The service is silent for longer than its TTL | Raise that TTL rather than lowering the heartbeat |
| The app shows a service as running while its machine is off | The lease has not expired yet | Wait for the TTL; it is the failover latency |
| `runners/` contains files but nothing is running | Services stopped without releasing | Normal after a crash; the files disappear when a new holder takes over |
| Collection workers stop with `HTTP 500` and *could not write ... permission denied* | The database cannot rewrite a lease: part of the data folder belongs to another user (often root, after a command run as root on the volume) | Stop the services, give the data folder back to the user named in the message (`chown -R 1000:1000` by default; `fsGroup: 1000` on Kubernetes), restart `fs` first |

# Related documents

-   *episomer: user documentation* — the main document: installation on a
    single machine, the setup wizard, the Shiny app and the methodology.
-   *Add a new social media* — a developer-oriented vignette describing how
    to extend `{episomer}` to a social media platform it does not support yet.
