Running Flagnetic on Kubernetes
The Helm chart in deploy/helm/flagnetic runs Flagnetic on Kubernetes: two replicas behind a Service, a PodDisruptionBudget, a Job that migrates the database before every install and upgrade, and, when you turn them on, an Ingress or Gateway API route, Prometheus rules, an autoscaler and a network policy. This guide takes you from an empty cluster to a running instance and through its upgrades. The chart’s README lists every value; Installing Flagnetic covers Docker Compose and the binary, and Operations covers running the server once it is up.
Prerequisites
- Kubernetes: the three newest minor versions (1.35, 1.36 and 1.37 as this is written). Newer ones are not refused.
- Helm: 3.18 or newer, or 4.
- PostgreSQL 16 or newer that the cluster can reach, with the
pg_trgmextension available (see What it needs). The chart installs no database; a managed service is the simplest choice, and the next section shows one you run in the cluster. - A secret key, generated once and kept for the life of the instance:
openssl rand -base64 32. The chart never generates one, because a key made when the chart renders would change underhelm templateand Argo CD, and the server refuses to start under a key other than the one it first stored. See The secret key. - TLS in front, for production: the server speaks plain HTTP, and the console’s session cookie is
Secureanywhere butlocalhost. See Routes.
PostgreSQL
Use your cloud’s managed PostgreSQL if you have one, and skip to The Secret. To run PostgreSQL in the cluster, CloudNativePG is one way: it manages the instances, failover and backups. With its operator installed, this Cluster creates a database flagnetic owned by a role of the same name, and the extension Flagnetic needs:
apiVersion: postgresql.cnpg.io/v1kind: Clustermetadata: name: flagnetic-db namespace: flagneticspec: instances: 3 storage: size: 20Gi bootstrap: initdb: database: flagnetic owner: flagnetic # The owner may not create an extension, so the superuser does it once. postInitApplicationSQL: - CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA publicThe operator writes the owner’s credentials to the Secret flagnetic-db-app, whose uri key is a connection string for the read-write Service flagnetic-db-rw. Backups, a PostgreSQL version and the rest are the operator’s to configure; see its documentation. Every replica of Flagnetic holds its own connection pool, so keep the replicas’ total within the database’s max_connections (see PostgreSQL connections).
The Secret
Keep the database URL and the secret key in a Secret of your own and name it with secrets.existingSecret. With CloudNativePG’s uri:
kubectl create namespace flagnetickubectl create secret generic flagnetic -n flagnetic \ --from-literal=DATABASE_URL="$(kubectl get secret flagnetic-db-app -n flagnetic -o jsonpath='{.data.uri}' | base64 -d)" \ --from-literal=FLAGNETIC_SECRET_KEY="$(openssl rand -base64 32)"With another database, give DATABASE_URL its connection string, for example postgres://flagnetic:PASSWORD@db.example.com:5432/flagnetic?sslmode=require. Back the secret key up outside the cluster: with a lost key the stored secrets (SSO client secrets, sink and SMTP credentials) cannot be read again.
The Secret may have other key names; set secrets.databaseUrlKey and secrets.secretKeyKey. For a tool that keeps secrets in git, an external secrets operator or a sealed secret produces the same Secret. Without an existingSecret, secrets.databaseUrl and secrets.secretKey make the chart render a Secret of its own from your values: convenient for a trial, but the values then sit in your release’s configuration. With neither, rendering fails with a message.
Install
helm install flagnetic oci://ghcr.io/azverinus/charts/flagnetic -n flagnetic \ --version <version> --timeout 20m \ --set secrets.existingSecret=flagnetic \ --set config.base_url=https://flags.example.comconfig.base_url is the address the console is reached at; set it to the public URL even before the route exists. Pass --version to pin the chart: its version is the server’s, and it installs the image of its own version.
Every other setting is a value under config, named by its file key in the configuration reference: config.log_level: debug becomes FLAGNETIC_LOG_LEVEL. Keep your values in a file and pass it with -f values.yaml:
replicaCount: 2secrets: existingSecret: flagneticconfig: base_url: https://flags.example.comThe release waits for the migration Job, then rolls out the pods. Check it, then create the first instance admin once, which prints a password and an API token:
helm test flagnetic -n flagnetickubectl exec -n flagnetic deploy/flagnetic -- flagnetic admin bootstrap --email you@example.comhelm test asks the Service for /readyz. Until a route is set up, kubectl port-forward -n flagnetic svc/flagnetic 8080:8080 reaches the console at http://localhost:8080.
Migrations
migrations.mode decides who migrates the database:
| Mode | What happens | Pick it when |
|---|---|---|
hook (default) |
A Job runs flagnetic migrate before every install and upgrade, and the pods start with auto-migration off. A failed migration stops the upgrade before any pod is replaced, and the Job’s log says why. |
Helm runs the release: helm install and helm upgrade. |
initContainer |
Every pod runs flagnetic migrate before its server starts. Replicas take turns through a PostgreSQL lock, and each migration is applied once. |
The tool applying the chart does not run Helm hooks: helm template output applied with kubectl, or a renderer that drops hooks. |
auto |
The server migrates when it starts, before it listens. | A single replica where you accept that a long migration delays startup. The startup probe allows 120 seconds by default, less than the five minutes the server may wait for the migration lock: a migration that outlives the probe is killed by the kubelet on every restart. Raise probes.startup.failureThreshold so that its product with probes.startup.periodSeconds covers the lock wait and the longest migration: 400 at the default period of 2 seconds allows 800 seconds. The install notes warn below 600. |
Argo CD renders the chart with helm template and runs Helm hooks as PreSync hooks on every sync, so the default works: the Job runs before each sync, which is harmless because migrate is idempotent and takes a lock. If you would rather not run a Job on every sync, use initContainer. The chart’s own Secret, when you let it render one, is a hook too, so under Argo CD keep the secrets in an existingSecret.
helm template output applied with kubectl creates the hook Job as an ordinary resource, at the same time as the pods rather than before them, so render with --set migrations.mode=initContainer (or run flagnetic migrate yourself first and use auto).
A migration the new version brings only moves the schema forward, in a way the previous minor still runs against, which is what makes the rolling upgrade below safe.
Routes
Neither route is on by default; turn on the one your cluster uses. An SDK holds a ruleset stream open for up to 65 minutes, and the ruleset stream and the console’s change stream send a heartbeat every 15 seconds. The proxy in front must therefore not buffer those streams, must time out an idle connection above 15 seconds, and must not end a request before the stream does; an hour is a safe idle timeout.
Ingress, here for ingress-nginx, with the timeouts and TLS:
ingress: enabled: true className: nginx hosts: [flags.example.com] annotations: nginx.ingress.kubernetes.io/proxy-read-timeout: "3600" nginx.ingress.kubernetes.io/proxy-send-timeout: "3600" nginx.ingress.kubernetes.io/proxy-buffering: "off" tls: - secretName: flagnetic-tls hosts: [flags.example.com]Gateway API: attach an HTTPRoute to your Gateway, and raise the Gateway’s idle timeout above 15 seconds and its request timeout above 65 minutes (or turn the request timeout off) in your implementation’s own way, since the route cannot:
httpRoute: enabled: true parentRefs: - name: public namespace: gateways hostnames: [flags.example.com]Trusted proxies. Set config.trusted_proxies to the addresses of the ingress controller’s pods or of the Gateway, for example config.trusted_proxies: 10.244.0.0/16 (comma-separated CIDR prefixes or addresses; list only proxies you control). Without it the server ignores X-Forwarded-For and sees every request as coming from the controller: all the browsers of a project share one client-key budget per replica, one script spraying passwords trips the source throttle for every member, a handful of wrong SDK keys makes the replica refuse every key it does not already hold, and the audit log records the controller’s address for everyone. The server logs a warning (X-Forwarded-For from a peer that is not a trusted proxy) once per replica when it sees the header from a peer that is not listed, and the install notes warn while a route is on and config.trusted_proxies is not set.
Where a Service of type LoadBalancer or NodePort sits in front of the controller, externalTrafficPolicy: Cluster, the default, replaces the client’s address with a node’s by source NAT before the controller sees it, so the controller forwards the node’s address however it is configured. Set externalTrafficPolicy: Local on that Service, or the clients the server learns are the nodes.
The metrics are on a Service of their own that neither route reaches. Behind a proxy, also read Behind a reverse proxy.
Metrics
The metrics Service exposes the server’s Prometheus metrics on port 9090 (see Metrics). With the Prometheus Operator’s CRDs installed, the chart renders the scrape configuration and four alerts:
serviceMonitor: enabled: true labels: release: prometheus # whatever your Prometheus selects ServiceMonitors byprometheusRule: enabled: true labels: release: prometheusThe alerts are FlagneticListenerDown, FlagneticRulesetPropagationSlow (the 99th percentile above prometheusRule.propagationSeconds, 2 s by default), FlagneticSinkDeadLetters and FlagneticWebhookDeliveriesFailing. They select the series of this release’s metrics Service, so they rely on the ServiceMonitor or on a scrape job of the same name. Without the Operator, point your own scrape job at the metrics Service.
Scaling
The chart runs two replicas, which every API and background worker is identical on, with no sticky sessions: any number of replicas works against one database. Spread over zones and hosts is on by default as a soft constraint, so a cluster with one node still schedules them. A PodDisruptionBudget lets one pod be unavailable during a voluntary disruption such as a node drain.
To scale by load, replace the fixed count with a HorizontalPodAutoscaler on CPU:
autoscaling: enabled: true minReplicas: 2 maxReplicas: 6 targetCPUUtilizationPercentage: 70The target is a share of resources.requests.cpu (100m by default), so size the request to the pod’s real use. Each replica holds its own PostgreSQL pool, so keep maxReplicas times the pool size plus 7 (the listener and protection connections outside the pool) within max_connections; The connection budget has the formula. Turning the autoscaler on in an upgrade removes the Deployment’s replica count, which Kubernetes may reset to one until the autoscaler scales back up. The memory request and limit (256 Mi and 512 Mi) are sized for password hashing, which takes 64 MiB per sign-in in flight.
Network policy
With a network plugin that enforces them, networkPolicy.enabled restricts the server’s pods: ingress to the http port from the sources you list (every source when none), to the metrics port only from the sources you list, and egress to DNS, PostgreSQL and the rules you add. List everything the instance reaches in networkPolicy.egress.rules: webhook receivers, sinks, SMTP servers and identity providers (OIDC and SAML).
networkPolicy: enabled: true ingress: http: from: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: ingress-nginx metrics: from: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: monitoring egress: postgresql: to: - podSelector: matchLabels: cnpg.io/cluster: flagnetic-db rules: - to: - ipBlock: cidr: 0.0.0.0/0 except: [10.0.0.0/8] ports: - port: 443The example admits the ingress controller to the console and the monitoring namespace to the metrics, restricts PostgreSQL to the CloudNativePG pods, and lets the server call HTTPS endpoints outside the cluster’s private range: the shape webhook receivers, sinks and identity providers usually have. Narrow the last rule to the hosts you use. The migration Job and the helm test Pod are not selected by the policy; because networkPolicy.ingress.http.from is set, the chart admits the helm test Pod to the http port by its label, so helm test still reaches the Service.
Upgrading
Read the release notes of every version between yours and the new one; a change that needs you to act is marked there. Back up the database first. Then upgrade the release:
helm upgrade flagnetic oci://ghcr.io/azverinus/charts/flagnetic -n flagnetic \ --version <new version> --timeout 20m -f values.yaml--timeout matters: Helm waits for the migration Job within it, five minutes unless set, while the Job may run for migrations.activeDeadlineSeconds (15 minutes). A migration longer than five minutes would fail the upgrade while the Job runs on, and upgrading again deletes the running Job, which kills the migration and rolls it back; pass a --timeout above the deadline, as above.
Until 1.0, stop every replica first. 0.x does not promise that two versions serve side by side, so the rolling upgrade below does not apply to an upgrade between 0.x versions (0.6 to 0.7, say): follow From 0.x to 1.0, which scales the Deployment to zero before helm upgrade and back after it. With autoscaling.enabled the Deployment has no replica count of its own and an autoscaler does nothing at zero, so scale it back yourself once the upgrade has finished.
Pass your values file again rather than --reuse-values, which would keep the old release’s defaults for values the new chart adds. From 1.0, the hook Job migrates the database, and only when it succeeds does Helm roll the Deployment, replacing the pods one at a time while the others keep serving. A stopping pod answers /readyz with 503 for the drain, then finishes its requests, so the Service stops routing to it before it goes and no request is refused; the 30-second terminationGracePeriodSeconds covers both (see Stopping). A failed migration fails the upgrade with every pod still on the old version; read the Job’s log with kubectl logs -n flagnetic job/flagnetic-migrate, fix the cause and upgrade again.
helm rollback returns the chart to a previous revision but not the database. Migrations only move forward and there are no down migrations, so to go back after a migration, restore the backup taken before the upgrade. The rest of the policy, and the note for each release, is in Upgrading Flagnetic and Compatibility.
Uninstalling
helm uninstall flagnetic -n flagneticThis removes the workloads and Services but not your data: it is in PostgreSQL, which the chart does not own. The chart’s own Secret, when you let it render one, is a Helm hook and so is left behind with the database URL and the secret key; delete it yourself when the instance is gone. An existingSecret, the CloudNativePG Cluster and its volumes are yours and stay until you delete them.
Verifying the chart
Each release publishes the chart to GHCR with a build attestation made by the release workflow. Check it before installing, with the GitHub CLI:
helm pull oci://ghcr.io/azverinus/charts/flagnetic --version <version>gh attestation verify oci://ghcr.io/azverinus/charts/flagnetic:<version> --repo azverinus/flagneticVerifying a release covers cosign too, and the image and the SDK packages.
The chart is also listed on Artifact Hub.