Running on Kubernetes

Deploy a StoatFlow application as a single-replica StatefulSet — persistent state volume, termination grace aligned with shutdown, secure licence injection, and a representative manifest.

StoatFlow runs as exactly one active JVM process, so on Kubernetes you deploy it as a single-replica StatefulSet — not a Deployment. A StatefulSet gives you a stable identity, a per-pod persistent volume for the state directory, and an update strategy that tears the old pod down before the new one starts, which is exactly what running one active instance requires. (For a hot-standby cluster, see High availability — a readiness-gated StatefulSet of two or more replicas.)

Why a StatefulSet, not a Deployment

A Deployment with replicas: 1 and the default RollingUpdate strategy will, during a rollout, start the new pod before terminating the old one (maxSurge: 1). For a moment two processes are alive and pointed at the same source topics — which is precisely the data-corruption scenario the engine cannot tolerate. (Hot standby is the supported way to run more than one replica: the standbys are passive, and a RollingUpdate is readiness-gated so they never process concurrently — see High availability.)

A StatefulSet with replicas: 1 does the opposite: on an update it terminates the old pod and waits for it to fully stop before creating the replacement. Combined with podManagementPolicy: OrderedReady, you get an at-most-one-running guarantee across rollouts. That, plus a stable PVC for the state directory, is why StatefulSet is the right primitive here.

Do not deploy StoatFlow as a Deployment, and never set replicas above 1 — unless you are running the opt-in hot-standby cluster (replicas: 2 or more, ha.mode: active-standby), which keeps the standbys passive. Two active instances against the same source topics corrupt state. See one active instance.

The state volume

State stores are RocksDB-backed on local disk under stoatflow.state.dir (default ${java.io.tmpdir}/stoatflow). The state directory is durable, not authoritative — the changelog topics are the source of truth, and on restart the runtime rebuilds from them. A persistent volume doesn't change correctness; it changes restart speed. With a surviving state directory the runtime replays only the changelog records since the last commit (a delta restore) instead of reading the whole changelog from scratch.

Mount a PVC at a fixed path and point stoatflow.state.dir at it:

# In the StatefulSet pod spec
volumeMounts:
  - name: state
    mountPath: /var/lib/stoatflow/state
# In the StatefulSet spec
volumeClaimTemplates:
  - metadata:
      name: state
    spec:
      accessModes: ["ReadWriteOnce"]
      storageClassName: fast-ssd   # SSD/NVMe — RocksDB is latency-sensitive
      resources:
        requests:
          storage: 100Gi

Then set the directory to that mount, either in application.yaml:

stoatflow:
  state:
    dir: /var/lib/stoatflow/state

…or via the environment variable (the YAML path in capitals, every . and - as _):

STOATFLOW_STATE_DIR=/var/lib/stoatflow/state

An image the io.stoatflow Gradle or Maven plugin built already sets the state directory: its STOATFLOW_STATE_DIR (the plugin's stateDir, default /data/state) is stoatflow.state.dir, and like every environment variable it wins over application.yaml. Mount the PVC at /data/state, or move it with stateDir at build time or a STOATFLOW_STATE_DIR entry in the container's env:, which replaces the image's value — a state.dir in the YAML does not move it in such an image.

Size the PVC for your state size plus RocksDB working headroom (compaction, SST overhead) — not for the changelog. Use a fast storageClassName (local SSD or NVMe-backed): RocksDB read/write latency feeds directly into commit-barrier duration. See Resource sizing.

Graceful shutdown and the grace period

On SIGTERM (which Kubernetes sends on pod termination) the runtime stops accepting new records, drains in-flight work, injects one final commit barrier, commits it, and closes the consumer and producer cleanly. That final commit is what keeps the shutdown exactly-once — interrupting it just means the next start resumes from the previous barrier, but letting it finish avoids re-processing on restart.

The runtime bounds its own graceful shutdown with stoatflow.shutdown.timeout-ms (default 25000). Kubernetes bounds it independently with terminationGracePeriodSeconds (default 30): when that elapses, Kubernetes sends SIGKILL regardless of progress.

Align the two so Kubernetes doesn't kill a still-progressing shutdown. Set terminationGracePeriodSeconds comfortably above your shutdown timeout in seconds:

spec:
  template:
    spec:
      terminationGracePeriodSeconds: 60   # > stoatflow.shutdown.timeout-ms / 1000, with margin
stoatflow:
  shutdown:
    timeout-ms: 25000   # default; raise for very large in-flight epochs

If your topology runs large epochs or slow stateful commits, raise both together — stoatflow.shutdown.timeout-ms first, then terminationGracePeriodSeconds so it stays larger. The runtime also has a hard-exit fallback that guarantees a clean process exit if shutdown itself hangs on a stuck lock (stoatflow.shutdown.hard-exit-on-shutdown-hang, default true); leave it on so Kubernetes always observes a clean termination rather than relying solely on SIGKILL. See Configuration reference for the full shutdown key set.

Secure licence injection

StoatFlow verifies the licence offline at startup, so the pod needs it — and no network access for it. The licence is a secret and must never land in the image, a ConfigMap, or source control. Store it in a Kubernetes Secret and surface it one of three ways. All three map onto the licence resolution order: an explicit licence (the YAML key or the env var) beats a licence file, and the env var beats the YAML key.

Mount the Secret at /run/secrets, the runtime's secrets directory; each key of the Secret becomes a file there. application.yaml names the file with ${secret:…}:

kubectl create secret generic my-stream-app-secrets \
  --from-literal=licence="sfl1...your production licence..."
# application.yaml (the ConfigMap)
stoatflow:
  licence:
    key: ${secret:licence}         # the file /run/secrets/licence
    environment: prod-eu-west
# In the pod spec
automountServiceAccountToken: false   # see the note below
volumes:
  - name: secrets
    secret:
      secretName: my-stream-app-secrets
# In the container spec
volumeMounts:
  - { name: secrets, mountPath: /run/secrets, readOnly: true }

The licence is held as a secret value: /config and the logs never show it. The same Secret carries every other credential the application reads — see Secrets from a mounted directory.

Option B — Secret as an environment variable

Project the secret value into STOATFLOW_LICENCE_KEY, the variable for stoatflow.licence.key. No YAML is needed.

# In the container spec
env:
  - name: STOATFLOW_LICENCE_KEY
    valueFrom:
      secretKeyRef:
        name: my-stream-app-secrets
        key: licence
  # Production, enterprise and trial licences REQUIRE an explicit environment label in a class they count — set it per deployment:
  - name: STOATFLOW_LICENCE_ENVIRONMENT
    value: prod-eu-west

Option C — Secret mounted as a licence file

Mount the secret as a file and point STOATFLOW_LICENCE_FILE at it. The licence file has permission rules of its own (below).

# In the container spec
env:
  - name: STOATFLOW_LICENCE_FILE
    value: /etc/stoatflow/licence/licence.key
  - name: STOATFLOW_LICENCE_ENVIRONMENT
    value: prod-eu-west
volumeMounts:
  - name: licence
    mountPath: /etc/stoatflow/licence
    readOnly: true
# In the pod spec
securityContext:
  fsGroup: 1000           # the image's group (it runs as 1000:1000): the mounted file is group-owned and readable by it
volumes:
  - name: licence
    secret:
      secretName: my-stream-app-secrets
      items:
        - key: licence
          path: licence.key
      defaultMode: 0440   # owner and group read-only
Production, enterprise and trial licences require an explicit environment label in a class they count (production, unless the licence lists more). The start is refused if it would have to auto-generate one — the auto-generated name is the pod name, so every redeploy would look like a new deployment. Set stoatflow.licence.environment or STOATFLOW_LICENCE_ENVIRONMENT (e.g. prd-eu, prd-eu-west, stg) per deployment: replicas of one deployment share it. A mounted licence file (option C) must be readable by the runtime user: defaultMode: 0440 with fsGroup set to the image's group, as above. A root-owned Secret file may be group-readable this way; any other licence file must be owner-only, and none may be readable by others or writable by its group. Full details on Licence configuration.

Secrets from a mounted directory

${secret:name} works in every configuration value, so one Secret volume at /run/secrets serves the licence, the Kafka credentials and your own application's passwords alike:

kubectl create secret generic my-stream-app-secrets \
  --from-literal=licence="sfl1...your production licence..." \
  --from-file=jaas=./jaas.conf \
  --from-file=db-password=./db-password.txt
stoatflow:
  licence:
    key: ${secret:licence}
  kafka:
    consumer:
      security.protocol: SASL_SSL
      sasl.mechanism: SCRAM-SHA-512
      sasl.jaas.config: ${secret:jaas}    # propagates to every client StoatFlow builds
payments-db:
  password: ${secret:db-password}         # your own section — see Custom configuration
  • One trailing newline is removed — the one --from-file keeps from a file an editor saved — and nothing else is trimmed.
  • Read once, at start. A rotated Secret takes effect at the next restart; roll the StatefulSet after updating it.
  • A missing key fails the start with an error naming the path (/run/secrets/jaas), never the value — and only when a value the application binds holds the placeholder.
  • Masked. Every value read this way is masked in /config, in logs and in error messages.
  • Another directory. To mount the Secret elsewhere, set STOATFLOW_SECRETS_DIR to the mount path.
Kubernetes mounts the pod's service-account token at /var/run/secrets/kubernetes.io/serviceaccount, and in Debian- and Ubuntu-based images /var/run is a link to /run — so that mount would land inside the Secret volume at /run/secrets. StoatFlow does not call the Kubernetes API: set automountServiceAccountToken: false in the pod spec, as the examples here do, or mount the Secret at another path and point STOATFLOW_SECRETS_DIR at it.

Kafka's own config.providers (DirectoryConfigProvider, FileConfigProvider) work as well, configured per client — see Kafka client configuration. The full placeholder rules are on How configuration works.

Environment variables in a pod

Every configuration key has an environment variable: its YAML path with every . and - as _, upper-cased — STOATFLOW_LANES_COUNT, STOATFLOW_HA_MODE, RUNTIME_HTTP_PORT. Two things about a pod's environment are worth knowing:

  • Service links are skipped. Kubernetes adds <NAME>_SERVICE_HOST, <NAME>_SERVICE_PORT, <NAME>_PORT=tcp://… and their siblings to every pod for each Service in the namespace. StoatFlow ignores them, so a Service named runtime-http does not set runtime.http.port, and a RUNTIME_HTTP_PORT=9090 you set yourself is kept. enableServiceLinks: false is not needed.
  • A variable that names no key WARNs once at start, with the closest valid name when there is one (STOATFLOW_LANSE_COUNT suggests STOATFLOW_LANES_COUNT). This covers every variable under STOATFLOW_, RUNTIME_ or LOGGING_. A ConfigMap shared with other tools and imported with envFrom — one carrying Spring's LOGGING_CONFIG, say — therefore WARNs at every start; give StoatFlow's container only its own variables to keep the log quiet.

Licence registry topics

Every instance registers in the licence registry, the compacted topic __stoatflow_licence in the application's own Kafka cluster, and heartbeats every 30 seconds; StoatFlow also creates __stoatflow_licence_history (usage history, kept 400 days). The count of running services comes from there, so a start past the licensed count is refused with SERVICE_LIMIT — the pods of that deployment crash-loop on it while the running fleet is unaffected.

  • ACLs. Grant the application's principal DESCRIBE, READ and WRITE on both topics, plus CREATE if StoatFlow is to create them, and DESCRIBE_CONFIGS so the start can check the topic's timestamp type. The registry's clients authenticate like the application's own: the producer with producer.*, the admin client with admin.*, the consumer with restore.consumer.* (each falling back to consumer.*).
  • Locked-down clusters. Where the application may not create topics, pre-create both with the exact settings in the licence registry topics, then restart. The error at start prints them too.
  • One registry per tenant. On a shared cluster set stoatflow.licence.registry.topic (env STOATFLOW_LICENCE_REGISTRY_TOPIC) to a different topic per team; the history topic follows as <topic>_history.
  • Registry unavailable. A paid licence keeps running with status UNVERIFIED (readiness stays UP, the count is not checked) and retries in the background; a trial refuses to start. Alert on stoatflow_licence_registry_available == 0.

Resource sizing

StoatFlow scales vertically — give the one process the CPU, memory, and disk it needs. Rough starting points for the CPU and disk, not measured sizes — for memory, start from Right-sizing memory:

WorkloadCPUMemoryDisk
Light (~10K events/sec, ~1 GiB state)4 cores8 GiB20 GiB SSD
Medium (~100K events/sec, ~10 GiB state)16 cores64 GiB100 GiB SSD
Heavy (~500K events/sec, ~50 GiB state)32 cores128 GiB500 GiB NVMe

The container's memory limit drives the memory plan: the image's entrypoint sizes the heap from it, and the engine gives RocksDB what the JVM, the heap and a headroom leave (The memory plan). Set the limit, not -Xmx, and pick a memory profile with STOATFLOW_MEMORY_PROFILE when the default balanced split does not suit the application. Without a memory limit there is no plan: RocksDB runs on one 256 MiB cache.

  • Small, low-rate applications fit small pods. With the lean profile the smallest documented limits are 256 MiB for a stateless JVM app and 512 MiB for a stateful one with a few stores; a native image needs 128 and 256 MiB, and is the better fit at 256 MiB and below. Below these limits, or with more stores than the cache holds, the engine WARNs at start. See Tuning → Small pods.
  • Set the memory requests equal to the limits, for the Guaranteed QoS class: the plan fills the limit — the block cache grows to whatever the container leaves it — so a pod scheduled on its request alone can be evicted or OOM-killed under node pressure long before it reaches its limit.
  • Do not put the state directory on an emptyDir with medium: Memory. A tmpfs volume's bytes count against the container's memory limit, and the plan does not reserve them; the engine WARNs at start when it finds one. Use a persistent volume, or a disk-backed emptyDir.
  • One JVM per container. The plan is per process: several JVMs in one container — a sidecar JVM in the same cgroup, test forks in a CI container — each plan against the whole limit. Nothing corrects this; the memory report's container verdict, which reads the cgroup's memory, shows the overcommit.

These are starting points; Right-sizing memory is the procedure for finding the memory limit an application needs, and Tuning → Sizing memory shows how to read the memory report (GET /memory) under load and step the limit down to what the application needs, and Tuning covers lane count, commit cadence and the heap's caps.

A representative manifest

A complete single-replica StatefulSet: ConfigMap for application.yaml, a Secret volume at /run/secrets for the licence, persistent state volume, grace period aligned with shutdown, and both health probes. Adjust image, topic/broker config, resources, and the licence-injection option to your environment.

apiVersion: v1
kind: ConfigMap
metadata:
  name: stoatflow-config
data:
  application.yaml: |
    stoatflow:
      application-id: my-stream-app
      bootstrap-servers: kafka-broker:9092
      state:
        dir: /data/state                 # the PVC's mount path; set for any image (a plugin-built one defaults to it)
      shutdown:
        timeout-ms: 25000
      licence:
        key: ${secret:licence}           # /run/secrets/licence, from the Secret volume below
        environment: prod-eu-west
    runtime:
      http:
        enabled: true
        port: 8080
      metrics:
        enabled: true
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: my-stream-app
spec:
  replicas: 1                      # exactly one — never more
  serviceName: my-stream-app
  podManagementPolicy: OrderedReady
  updateStrategy:
    type: RollingUpdate            # StatefulSet rolling update stops the old pod before starting the new
  selector:
    matchLabels:
      app: my-stream-app
  template:
    metadata:
      labels:
        app: my-stream-app
    spec:
      terminationGracePeriodSeconds: 60   # > stoatflow.shutdown.timeout-ms / 1000, with margin
      automountServiceAccountToken: false # StoatFlow does not call the Kubernetes API; keeps the token mount out of /run/secrets
      containers:
        - name: app
          image: my-registry/my-stream-app:latest
          ports:
            - name: http
              containerPort: 8080
          env:
            # application.yaml is loaded from the mounted ConfigMap:
            - name: STOATFLOW_CONFIG_FILES
              value: /etc/stoatflow/application.yaml
          startupProbe:             # holds liveness off until the restore is done: 180 × 10 s = 30 min
            httpGet:
              path: /health/ready
              port: http
            periodSeconds: 10
            timeoutSeconds: 3
            failureThreshold: 180
          readinessProbe:
            httpGet:
              path: /health/ready
              port: http
            periodSeconds: 10
            timeoutSeconds: 3
          livenessProbe:
            httpGet:
              path: /health/live
              port: http
            periodSeconds: 30
            timeoutSeconds: 3       # a busy restore on few CPUs answers slowly; Kubernetes' default is 1 s
          resources:
            requests:
              cpu: "16"
              memory: 64Gi
            limits:
              cpu: "16"
              memory: 64Gi          # match requests → Guaranteed QoS; the memory plan splits this limit
          volumeMounts:
            - name: config
              mountPath: /etc/stoatflow
              readOnly: true
            - name: secrets
              mountPath: /run/secrets       # ${secret:…} reads from here
              readOnly: true
            - name: state
              mountPath: /data/state        # the image's STOATFLOW_STATE_DIR
      volumes:
        - name: config
          configMap:
            name: stoatflow-config
        - name: secrets
          secret:
            secretName: my-stream-app-secrets   # keys: licence (and any other secret the app reads)
  volumeClaimTemplates:
    - metadata:
        name: state
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: fast-ssd
        resources:
          requests:
            storage: 100Gi
STOATFLOW_CONFIG_FILES points the runtime at the mounted application.yaml. The container image is the one built by the StoatFlow build conventions (Jib, on Gradle or Maven) — it already sets the required JVM flag (--enable-native-access=ALL-UNNAMED) and runs as a non-root user. The image's entrypoint carries that flag and the main class, so a container's args: are your application's own arguments; don't set command:, which would replace the entrypoint. See Docker for image build details.

Verify the rollout

After applying the manifests, confirm the single pod comes up and reports ready:

kubectl rollout status statefulset/my-stream-app
kubectl get pods -l app=my-stream-app          # exactly one pod, 1/1 Running

# Port-forward the HTTP port and check readiness:
kubectl port-forward statefulset/my-stream-app 8080:8080 &
curl -s localhost:8080/health/ready            # {"status":"UP", ...} once state restoration completes

During cold start /health/ready returns 503 until state restoration finishes — that's expected and is exactly why the readiness probe gates traffic. On a rolling update, watch that the old pod reaches Terminating and stops before the replacement is created; the StatefulSet guarantees this ordering, but it's worth confirming on first deploy.

The rollout you should observe, end to end — for the multi-replica hot-standby roll, where readiness additionally enforces the redundancy floor, see High availability:

Next steps

  • High availability — the opt-in hot-standby cluster: a multi-replica StatefulSet for near-instant failover.
  • Probes — liveness vs. readiness, the JSON each returns, and how to tune probe timings.
  • Observability — scraping /metrics, the key metrics to alert on, and structured logs.
  • Tuning — lane count, commit cadence, memory caps, and sizing the container with the memory report.
  • Production checklist — everything to verify before going live.
  • Licence configuration — the full licence reference, including CI/CD.