Skip to main content

Kubernetes Operator

The Kahuna Kubernetes operator takes over the repeatable work of running a Kahuna cluster. Examples are scaling the cluster and scheduling backups, and rolling out new versions. You declare the cluster that you want in a KahunaCluster resource, like a Deployment declares stateless pods. The operator then coordinates the steps across nodes.

The operator is currently alpha (API version kahuna.kahunakv.io/v1alpha1).

What you needWhat you configureWhat the operator handles
More capacity when traffic grows, less when it fallsAn instance count, or autoscaling targets and limitsAdds nodes and waits for catch-up. Before it removes a node, it decommissions the node.
Regular, recoverable backupsBackup schedules and retention, with shared storageFinds the backup coordinator and maintains the chain. It also retries failed attempts and shows the results.
Upgrades that keep the cluster onlineThe server image versionReplaces instances one at a time. It pauses the rollout when membership isn't ready.

You don't have to run a separate membership script or maintain a backup cron job. You also don't stop all servers for an upgrade. Storage and TLS remain deployment choices, and so does workload sizing. The operator automates the cluster lifecycle around them.

Scale to the Capacity You Need​

Choose a fixed number of instances or let Kahuna's write traffic and queue pressure drive scaling within your limits. The operator handles the membership changes in both cases, one node at a time. Its built-in autoscaler doesn't need a separate metrics stack.

For example, this configuration lets a cluster grow from four to nine instances and shrink when demand drops.

spec:
replicas: 4
replication:
factor: 3
autoscaling:
minReplicas: 4
maxReplicas: 9
targetWritesPerSecond: 2000
targetQueueDepth: 32

These are fields to add to the complete cluster definition below. Starting with more instances than the replication factor (copies of each partition) avoids an initial conversion from full replication, where all nodes store all partitions: four instances with three data replicas is a suitable starting topology. Set traffic targets from your workload; they are not throughput guarantees.

For a fixed size, set spec.replicas with autoscaling disabled. Switching back to manual control takes one patch. The operator performs the membership work. You don't resize individual containers or remove cluster members yourself.

Scheduled Full and Incremental Backups​

Set the backup policy once and let the operator run it. Full backups establish a coordinated recovery point. Incrementals capture later changes, and a full copy isn't needed each time.

Add this to your cluster definition, and replace shared-files with a StorageClass that supports a shared ReadWriteMany volume.

spec:
backup:
schedule: "0 2 * * *" # Full backup daily at 02:00 UTC
incrementalSchedule: "*/15 * * * *" # Incremental every 15 minutes
volume:
claim:
size: 100Gi
storageClassName: shared-files
retention:
maxChains: 7

The operator creates and mounts the shared backup volume and configures the servers. It also generates a manifest-signing key if you don't provide one. After the cluster finishes its configuration rollout, the first full backup starts immediately. It doesn't wait for the next daily slot. Later full and incremental backups follow their schedules. Status shows the last successful backup and any failures; failed attempts remain due and are retried.

You don't need to pick the coordinator or find the latest parent, or wire up a recurring backup job. Retention treats each recovery chain as a unit, and the newest chain is always retained. Keep the backup volume and signing-key Secret: both outlive deletion of the cluster resource and are needed for recovery. Restore remains a separate, deliberate operation; see Backups and Point-in-Time Recovery.

Backup storage and failure handling details
  • Multi-node clusters need shared ReadWriteMany storage. You can use an existing claim with volume.claimName instead. A default block-storage class may not support shared mounts. BackupVolumeReady shows binding failures.
  • Backups with replica placement need a server that composes the coordinated image from all partitions even when no single node has the full dataset. See the version requirement. The operator doesn't allow recognized older release tags for this topology; an unknown image tag is not a compatibility check. The example below pins 1.12.8.
  • A backup starts only once the cluster is ready on its requested image/configuration. It executes in the background, and it doesn't block scaling and upgrades. A topology change or unavailable partition capture can require a retry.
  • Full schedules and optional incremental schedules use UTC unless prefixed with CRON_TZ=<zone>. Missed slots collapse into one run. Keep incrementals within the server's retained WAL window; the server can substitute a full if a chain can no longer be extended.
  • Failures back off from one minute up to 30 minutes. Temporary refusals where no node takes the backup retry after 15 seconds; if they persist for five minutes they count as failures. Inspect BackupFailing and status.backup. Don't assume that each scheduled slot produced an artifact.
  • If an incremental parent is missing, the operator starts a new full chain. The operator disables periodic server GC on the shared catalog to avoid deleting another node's in-progress artifacts. Cleanup after backups continues.
  • backup.suspend: true pauses new scheduled backups, but it doesn't cancel a backup in progress. The backup target is shared volume storage. It isn't a built-in GCS integration. Automatic restore and seed-on-scale workflows are separate from scheduled backup support.

Rolling Upgrades That Keep the Cluster Online​

Change the image version, and the operator coordinates the rollout. It replaces instances one at a time, and the remaining replicas serve requests. It pauses when the committed membership is unreadable or hasn't converged. You don't need to stop the cluster and upgrade each machine by hand.

For example, this command requests the current pinned version.

kubectl -n kahuna patch kahunacluster kahuna --type=merge \
-p '{"spec":{"image":"kahunakv/kahuna:1.12.8"}}'
kubectl -n kahuna rollout status statefulset/kahuna --timeout=15m

Upgrades can keep a healthy replicated cluster available, with two conditions. The remaining replicas must form the quorum (a majority of the replicas) of each partition, and the versions must support a rolling transition. Applications should retry transient failures during leader handoff or connection replacement. The operator doesn't guarantee that each request completes without interruption. A standalone instance or a partition with only one replica cannot stay available while that replica restarts. Check the target version's compatibility notes before upgrading.

Get Running​

This setup installs the operator and creates a cluster. It then connects an application. The later reference sections explain the safeguards and troubleshooting details.

Install the Operator​

You need Helm and Kubernetes storage provisioning for the requested PVCs. The operator also needs network access to the Kahuna pods. These commands install the operator from its source chart. They don't create a Kahuna cluster.

git clone https://github.com/kahunakv/kahuna-k8s-operator.git
cd kahuna-k8s-operator
helm install kahuna-operator ./charts/kahuna-operator \
--namespace kahuna-system --create-namespace
kubectl create namespace kahuna

The chart defaults to one operator instance with leader election. watchNamespace can restrict its watched namespace, but RBAC remains cluster-scoped; this is not a security boundary. Optional chart metrics.serviceMonitor exposes operator metrics. It doesn't expose Kahuna's JSON dashboard metrics.

Create a Cluster Ready for Autoscaling​

This example starts with four nodes and a replication factor of three. This means that initial placement can distribute partitions immediately. Kahuna servers can also convert legacy fully replicated partitions to placed replicas. A fully replicated partition is stored on all nodes, which is the default if you don't set a replication factor. Conversion needs a positive factor and the placement rebalancer; the operator enables rebalancing with spec.replication. Growth may wait while conversion and replica movement settle. Older server versions do not have this conversion path. See Migration Notes.

First, supply a PKCS#12 keystore in the cluster's namespace.

kubectl -n kahuna create secret generic kahuna-tls \
--from-file=certificate.pfx=/path/to/certificate.pfx

Use a certificate appropriate for the peer and client DNS names. Alternatively, if cert-manager is installed, replace secretRef below with certManager.issuerRef. The operator then creates the Certificate and the PKCS#12 password Secret, with a wildcard peer SAN. Exactly one TLS source is required.

caution

The example sets insecureSkipVerify: true, which disables inter-node server-certificate verification. That is also the operator's default. This means that a self-signed keystore works out of the box. For production, issue the certificate from an issuer the server image trusts and set insecureSkipVerify: false.

Save this file as kahuna.yaml.

apiVersion: kahuna.kahunakv.io/v1alpha1
kind: KahunaCluster
metadata:
name: kahuna
namespace: kahuna
spec:
replicas: 4
image: kahunakv/kahuna:1.12.8
partitions: 16
replication:
factor: 3
storage:
backend: rocksdb
data:
size: 100Gi
pvcRetentionPolicy: Retain
tls:
secretRef:
name: kahuna-tls
keystoreKey: certificate.pfx
insecureSkipVerify: true
resources:
requests:
cpu: "1"
memory: 2Gi
autoscaling:
minReplicas: 4
maxReplicas: 9
targetWritesPerSecond: 2000
targetQueueDepth: 32
scaleUpStabilizationSeconds: 60
scaleDownStabilizationSeconds: 300
tolerancePercent: 10
kubectl apply -f kahuna.yaml
kubectl -n kahuna get kahunacluster kahuna -w
kubectl -n kahuna wait --for=condition=RosterConverged \
kahunacluster/kahuna --timeout=10m

The sizes and targets are starting examples. They aren't capacity guarantees. Choose partition count and resources for the workload: adding nodes redistributes existing placed partitions, but cannot spread one hot key's writes across leaders. With factor 3, a data partition needs a majority of its three replicas; nine cluster nodes do not give that partition nine copies or tolerance of four replica failures. System membership spans all nodes. See Replica Placement and Leader Balancing.

A password-protected supplied keystore also needs tls.passwordSecretRef: {name: <secret>, key: <key>}. The operator enables plaintext listeners for its probes and management calls; restrict pod and Service access with your network policy. This TLS setup is not node mTLS; see Node Transport Security for that separate server mode.

Connect an Application​

The operator creates a ClusterIP client Service named after the resource, and a headless <name>-peer Service for node identity. Default client ports are HTTP/gRPC 2070 and HTTPS/gRPC 2071; node-to-node Raft traffic uses 8082. In this example, in-cluster clients can use http://kahuna.kahuna.svc.cluster.local:2070 or the TLS client port with a matching trusted certificate.

Use port forwarding for local inspection.

kubectl -n kahuna port-forward service/kahuna 2070:2070
# In another terminal:
curl http://127.0.0.1:2070/v1/cluster/membership
curl http://127.0.0.1:2070/v1/cluster/placement

A client Service can route to any ready node; Kahuna forwards requests to the partition leader. For direct client routing, advertise and map reachable client endpoints. Don't use the peer Raft port. Pod DNS/IP hints generally cannot be followed from outside Kubernetes. See Client Leader-Aware Routing.

Scaling reference: signals and safeguards

How Traffic-Based Scaling Works​

The controller polls GET /v1/dashboard/metrics on all eligible ready pods, with a steady autoscaling resync of 15 seconds. Keep the dashboard enabled and reachable. If you pass --disable-dashboard through spec.extraArgs, the /v1/dashboard/* JSON routes are removed, including this one. Traffic-based scaling then breaks. These signals don't need a metrics-server or an external HPA, or a Prometheus adapter.

Each target is compared with one per-node metric: how many key/value writes the node admits per second, and how many client proposals wait in its Raft queues.

FieldSignal
targetWritesPerSecondAverage per-node rate of kahuna.kv.write.admitted, a cumulative direct key/value write admission counter. It is not total successful requests or transactional write throughput.
targetQueueDepthAverage per-node sum of raft.executor.client_queue_depth across partition executors: pending client proposals, including transactional pressure. It does not measure read latency or CPU utilization.

At least one positive target is required. The controller computes the largest available signal-to-target ratio. Outside the tolerance band, it recommends ceil(current desired replicas × ratio), clamped to minReplicas and maxReplicas. For example, four nodes averaging 4,000 writes/s against a 2,000 target recommend eight. After the scale-up window, it requests five nodes. It waits for membership and readiness, and for replica-placement convergence. Then it measures again. It does not jump straight to eight.

The scale-up and scale-down windows default to 60 and 300 seconds; tolerance defaults to 10%. These are continuous observed direction windows. They aren't a historical maximum-recommendation algorithm. A return to the band clears the corresponding streak. A direction change or a cluster that hasn't converged also clears it. Each step restarts stabilization. Catch-up and placement add time beyond the window, and so do scheduling and draining. This means that the window isn't a scaling completion deadline.

Write rates need two accepted samples at least ten seconds apart. Counter/time resets or a new pod UID require a new baseline; an operator restart also loses rate baselines, while desired count and stabilization timestamps remain in status. Missing metric rows in an otherwise successful response count as zero. Unknown write-rate baselines are different: another known signal can justify growth, but a missing configured signal prevents traffic-driven shrink. If a metrics request fails, the traffic decision is put on hold. Read-only saturation may not trigger either signal. This autoscaler doesn't react to general load signals, such as CPU or read latency.

Before growing, the operator reads replica placement. An unreadable placement view prevents growth. If an active data partition is in legacy full replication, the operator limits autoscaled growth to three nodes, for any configured factor. Autoscaled growth doesn't create more than three data copies. AutoscalingLimited explains the block; current servers can clear pending conversion through the placement rebalancer. With placed partitions, replication.factor can be 1–3; factor 1 sacrifices replica fault tolerance.

While autoscaling is enabled, spec.replicas only initializes the target, clamped to the bounds. Later edits to it do not override the autoscaler. Bounds edits clamp the desired count immediately. Actual membership changes one node at a time, as usual; a traffic sampling failure does not undo that explicit clamp. status.autoscaling.recommendedReplicas is already clamped to the bounds; it is not the uncapped demand.

Scale Manually or Pause Autoscaling​

If spec.autoscaling isn't set, edit spec.replicas. This command switches the example to a fixed size of four in one patch.

kubectl -n kahuna patch kahunacluster kahuna --type=merge \
-p '{"spec":{"autoscaling":null,"replicas":4}}'

If you remove autoscaling and don't update replicas, the old value takes control again. This can start an unexpected scale. Do not attach an HPA to the managed StatefulSet or edit its count directly: the operator reconciles that object from the custom resource.

Scale-up creates one joining node at a time and waits for the expected roster to contain all target endpoints as Voters. Further scaling also waits for replica placement to settle; committed membership alone doesn't prove that data movement finished. This diagram shows one scale-up step.

Scale-down asks the highest-ordinal node to leave through POST /v1/cluster/leave; only a committed removal/already-absent response permits removal of its reachable pod. A refusal or HTTP error leaves the current size unchanged. On a cluster with replica placement, the departing node is drained before its removal commits.

If the departing pod is already missing or doesn't have an IP, the controller can't ask it to leave. It relies on membership eviction; it will not take another step until the roster converges.

replicas: 2 is rejected. A standalone one-node resource cannot transition to or from a multi-node cluster; create a separate resource and migrate. Counts of four or six are valid intermediate/target sizes, but an even-sized fully replicated group has the same failure tolerance as the preceding odd size.

PVCs are retained on scale-down by default. storage.pvcRetentionPolicy: Delete makes Kubernetes reclaim scaled-away PVCs, and loses their local state. Deleting a KahunaCluster retains its PVCs regardless of that scale-down setting; deleting the resource is not a coordinated node-by-node decommission of the entire cluster.

Observe and Troubleshoot​

kubectl -n kahuna get kahunacluster kahuna -o yaml
kubectl -n kahuna get pods,pvc
kubectl -n kahuna describe kahunacluster kahuna
kubectl -n kahuna logs kahuna-0 --tail=100
State or symptomCheck
status.phase: BootstrappingKeystore availability and PVC binding. Also check peer DNS and the founder logs. The peer Service publishes not-ready addresses so quorum can form.
Available=True, RosterConverged=FalseSome capacity is serving, but a membership change is incomplete. Available is a readiness and quorum summary. It doesn't prove that all data partitions are healthy. Inspect status.members and the serving cluster.
AutoscalingLimited=TrueCondition message, for example unavailable metrics or fully replicated partitions.
recommendedReplicas exceeds desiredReplicasStabilization or one-node stepping can delay the next step, and so can a ceiling. Inspect window timestamps and conditions.
A new node remains a Learner (not yet a voter)Catch-up progress and snapshot transfer. Also check placement and the join timeout logs. Readiness alone does not certify roster convergence.
Scale-down doesn't progressDeparting pod reachability and the leave response. Also check the remaining replica placement and the decommission drain timeout. Keep the pod until removal is confirmed.
Backups wait or failBackupVolumeReady and BackupFailing, with status.backup. Check shared storage binding and image compatibility, and the latest attempt outcome.

A joining node goes through two waits, and each wait has a separate timeout. Admission and initialization use --raft-join-timeout (default 60,000 ms). Promotion from learner to voter, which waits for the node to catch up, uses a no-progress timeout (--raft-join-promotion-stall-timeout, default 300,000 ms): it fires when catch-up stops advancing. It doesn't fire when catch-up is slow. Promotion can take longer while catch-up shows progress, for example in commit indexes or snapshot install. The stall timeout must exceed the promotion stable window plus the node-update interval. These timeouts don't have typed operator fields. Use spec.extraArgs when an adjustment is justified.

spec:
extraArgs:
- --raft-join-timeout
- "120000"
- --raft-join-promotion-stall-timeout
- "600000"

Do not add --disable-dashboard to extraArgs on an autoscaled cluster: it removes the metrics endpoint the autoscaler polls.

A post-admission join failure attempts withdrawal from the roster; withdrawal is best-effort and caller cancellation does not invoke it. Verify membership. Don't assume that an exception removed a learner.

Deployment reference: updates and storage limits

Updates, Storage, and Recovery Limits​

Configuration/image changes update the pod template and cause rolling updates; the controller pauses updates when membership is unreadable or hasn't converged. Scaling changes topology outside the template so it does not restart existing nodes merely to change the peer list. TLS Secret contents alone do not change the generated script hash: do not assume certificate rotation automatically rolls pods.

partitions is immutable, and so are the storage and WAL backends and revisions. The reconciler doesn't update existing StatefulSet volume-claim templates. This means that an edit of the requested size in the custom resource doesn't expand the PVC. An optional storage.wal template gives WAL a separate volume. Default anti-affinity is a soft preference; configure affinity or topologySpreadConstraints for the failure-domain placement you require.

When you update the operator CRD, apply it before the Helm upgrade. helm upgrade doesn't replace the chart's crds/ files.

kubectl apply -f charts/kahuna-operator/crds/kahunaclusters.yaml
helm upgrade kahuna-operator ./charts/kahuna-operator --namespace kahuna-system

Scheduled backups are configured through spec.backup, including shared storage mounts and signing-key setup. The operator does not automatically restore a cluster or seed new pods from those backups. New nodes normally use a Raft snapshot plus log catch-up. Kahuna servers can copy and verify a full backup base image before replay and join. However, this requires explicit bootstrap orchestration. The stock server does not register a GCS provider merely through extraArgs. See PITR Bootstrap for the server workflow and Backups for recovery semantics.