Documentation
General documentation for this declarative self-hosted platform repository.
Repository layout
infra/— infrastructure configurationplatform/— shared platform services and deployment-specific compositionapps/— workload configurationappsets/— workload selection by deploymentdocs/— guides and reference materialscripts/— operational helper scripts used by Makefile targets
Infrastructure
The NixOS module deploys K3s to an already-booted Incus VM. It relies on the image’s existing ESP and nixos filesystem labels and does not repartition or format the disk. See the NixOS deployment guide for prerequisites, Terragrunt inputs, deployment steps, and kubeconfig handling.
The root Nix flake provides a development shell with infrastructure and Kubernetes tools.
Documentation scope
General guidance describes common practices; repository configuration remains authoritative for implementation details. Keep credentials and recovery material out of Git and documentation.
Productive
System Architecture
Purpose
This repository contains declarative configuration for a self-hosted platform. It separates infrastructure provisioning, shared platform services, application workloads, and operational documentation. Configuration is organized so common components can be reused while deployment-specific differences remain isolated.
Repository map
| Path | Purpose |
|---|---|
infra/ | Infrastructure modules, deployment configuration, and protected-input references. |
platform/base/ | Shared services required by the platform. |
platform/<deployment>/ | Deployment-specific platform composition and overrides. |
apps/<workload>/<deployment>/ | Workload resources and deployment-specific configuration. |
appsets/<deployment>/ | Selection of workloads for a deployment. |
docs/ | Architecture, operational guidance, and specialist procedures. |
Names and directory structures are descriptive: a configuration directory is not necessarily active. The deployment entry point determines which components are included.
Configuration layers
The system has four conceptual layers:
- Infrastructure creates and configures the underlying runtime environment.
- Shared platform services provide capabilities used by multiple workloads, such as networking, identity, secrets, observability, and storage support.
- Workloads define individual services, their configuration, storage, and network exposure.
- Deployment composition selects shared services and workloads and applies necessary overrides.
DEPLOYMENT COMPOSITION
selects components and overrides
|
+------------+------------+
| |
v v
SHARED PLATFORM SERVICES WORKLOADS
common capabilities service configuration
| |
+------------+------------+
|
v
INFRASTRUCTURE
runtime and connectivity
Prefer placing reusable behavior in a shared layer and deployment-specific differences in the corresponding override layer. Keep credentials out of ordinary configuration and source control; use the repository’s protected secret-management process.
Reconciliation and configuration delivery
The repository uses declarative desired state. An initial provisioning stage connects the runtime environment to published configuration. A reconciliation system applies selected platform resources before dependent workloads. Platform and workload configuration may be packaged and published separately; deployment entry points select the relevant configuration from each package.
Repository changes
|
v
Review and validation
|
v
Publish configuration packages
| |
v v
Platform package Workload package
| |
v v
Platform selection Workload selection
| |
+------ dependencies-+
|
v
Runtime resources
|
v
Reconcile desired/current state
|
+-----> Health and status
Before relying on a change, verify that its configuration is included by the relevant deployment entry point and that the intended package version is available. Removing a resource from an active composition can cause it to be removed from the runtime environment, depending on reconciliation policy.
Component boundaries
- Infrastructure owns lifecycle and connectivity of the runtime environment.
- Platform services provide shared capabilities and establish dependencies for workloads.
- Workloads own application-specific configuration and persistent data declarations.
- Secret management supplies sensitive values without embedding them in ordinary manifests.
- Backup and recovery protect selected persistent data and require recovery credentials to remain available independently of the system being recovered.
Consult the configuration adjacent to a component for its authoritative settings and dependencies. This document intentionally avoids binding the architecture to a specific deployment, application, or implementation tool.
Quick Start
This guide covers the development setup, deployment sequence, Makefile targets, and WSL local-certificate workflow.
1. Enter the development environment
Install Nix, open a terminal at the repository root, and run:
nix develop
The development shell is defined in flake.nix and provides the command-line dependencies used by repository workflows.
2. Prepare a deployment
- Choose the intended deployment and inspect its configuration under
infra/env/. - Review the corresponding infrastructure and bootstrap inputs, including protected secrets and external dependencies.
- Resolve the Kubernetes access file from that deployment’s cluster configuration. Use it explicitly for all cluster commands; do not rely on an implicit current context.
- Provision the runtime environment and bootstrap its connection to repository configuration using the approved infrastructure workflow.
- Ensure the intended platform and workload configuration packages have been published through the repository’s established process.
- Confirm platform services reconcile successfully before dependent workloads, then verify workload health.
The repository Makefile provides plan, apply, destroy, formatting, and artifact-push targets. Review the selected environment and target before running commands that change infrastructure.
Push platform and app artifacts
Use make push env=<environment> to publish both OCI artifacts, or run make platform env=<environment> and make apps env=<environment> separately. The registry defaults to the current k3s-vm IPv4 on enp5s0 with port 30500 when Incus VM is available; otherwise it falls back to localhost:30500. Override the detected endpoint with REGISTRY_URL, for example:
make push env=prod REGISTRY_URL=localhost:30500
Refresh Incus kubeconfig endpoint
When DHCP changes k3s-vm address, update kubeconfig API server address using current VM IPv4:
make update-kubeconfig
This defaults to .kube/prod.yaml. Set KUBECONFIG to update another file, for example:
make update-kubeconfig KUBECONFIG=.kube/incus.yaml
3. Troubleshoot local HTTPS certificates
If Firefox reports SEC_ERROR_BAD_SIGNATURE, first compare the current CA, Gateway certificate, and Firefox’s imported CA fingerprint. Follow the local certificate troubleshooting guide before changing cluster resources.
4. Trust the local WSL certificate
This workflow applies when the local deployment has created the local-ca certificate Secret in the certificate-management namespace.
- Read the local deployment’s cluster configuration and set
KUBECONFIGto its declared kubeconfig file. - Export the CA certificate to a local file. The certificate is public, but keep generated files outside the repository unless there is a deliberate reason to store them there.
kubectl --kubeconfig .kube/local.yaml -n cert-manager get secret local-ca -o jsonpath='{.data.tls\.crt}' | base64 -d > "$HOME/local-ca.crt"
- Import
local-ca.crtinto the browser or operating-system trust store used by WSL-hosted browsing, following that platform’s certificate-import procedure. - Verify that the local HTTPS endpoint is trusted. If certificate retrieval fails, confirm the selected deployment, kubeconfig path, and certificate Secret before changing cluster state.
The local deployment configuration uses loopback-resolving hostnames. Consult its manifests for the current hostnames and routing behavior; do not assume these settings apply to other deployments.
Operations Guide
This guide describes safe, repeatable practices for maintaining a declarative platform. Follow your organization’s approval, access-control, and incident procedures for operational changes.
Before making a change
- Identify the target deployment and confirm its configuration entry point.
- Determine whether the change belongs in shared configuration or a deployment-specific override.
- Check dependencies and confirm the affected resources are selected for that deployment.
- Confirm required protected inputs are available without exposing their values.
- Assess whether the change can replace, delete, or interrupt existing resources or data.
Configuration change workflow
- Make the smallest change that expresses the intended desired state.
- Keep sensitive values out of source files, examples, logs, and documentation. Reference the established secret-management mechanism instead.
- Validate syntax and references, and review rendered or composed configuration where practical.
- Review the complete change set for unintended resource selection, deletion, or exposure.
- Obtain required review and approval before applying or publishing changes.
- Observe reconciliation and service health after rollout. Confirm expected behavior and persistence, not only successful configuration acceptance.
- Record operationally relevant outcomes and update documentation when procedures or interfaces change.
Adding a workload
- Create a directory for the workload and intended deployment scope.
- Add the minimum resources needed to run it, such as namespace or isolation settings, workload definition, internal service, and external route if required.
- Declare persistent storage and secret references explicitly; do not embed credentials in workload configuration.
- Add the workload directory to the appropriate deployment composition so it is selected for reconciliation.
- Validate resource names, namespaces, selectors, ports, routes, dependencies, and secret references as a set.
- Review the resulting change, publish through the established release process, and confirm workload readiness and access after reconciliation.
A workload directory by itself does not activate a workload. Selection by the deployment composition is required.
Diagnosis
Begin with read-only inspection. Confirm the target deployment and access context before querying runtime state. Examine the relevant reconciliation status, workload health, recent events, dependencies, network paths, and persistent storage state.
Do not guess when the target deployment or access configuration is ambiguous. Stop and confirm the intended target. Avoid changing active context or relying on implicit defaults when that could direct an operation to the wrong system.
During diagnosis, do not apply, delete, patch, restart, or otherwise mutate resources without explicit authorization. Capture only non-sensitive diagnostic information; do not expose credentials, secret values, or private access configuration.
Release and rollback
Use the repository’s established release process to publish or apply reviewed desired state. Where configuration is delivered as separate packages, publish only the package or packages affected by the change; publish all affected packages when a change crosses their boundary. Confirm which configuration version is active before and after a release. For rollback, restore a known-good desired state using the normal review and deployment controls; assess data compatibility before reverting stateful workloads.
Removal of resources from an active composition may trigger automated deletion. Review reconciliation and pruning behavior before removing declarations.
Data protection and recovery
Identify which workloads hold persistent data, what recovery objectives apply, and where independent backups and recovery credentials are maintained. Verify backup completion and periodically test restoration using an isolated or otherwise approved recovery process.
Recovery instructions must clearly distinguish preparation, verification, and restoration. Keep recovery credentials and key material outside the system they are intended to recover. See the specialist backup and restore guide for the repository’s current procedure.
Security checklist
- Confirm the target system before every operational action.
- Prefer read-only inspection during diagnosis.
- Keep credentials, private access configuration, and recovery key material out of source control and documentation.
- Review access scope and network exposure when changing service configuration.
- Understand persistence, deletion, and rollback effects before applying changes.
- Obtain approval for changes that affect live systems or data.
Troubleshooting
Local HTTPS certificate: Firefox SEC_ERROR_BAD_SIGNATURE
This Firefox error can mean Firefox is validating the server certificate against a different local-ca certificate than the one that signed it. Importing the server certificate (wildcard-tls) as a CA is not the fix; import the current public CA certificate instead.
For the local environment, use its configured kubeconfig explicitly: .kube/local.yaml. These checks read public certificates only; never retrieve or share tls.key.
Run from the repository root. The Nix shell supplies OpenSSL:
nix shell nixpkgs#openssl -c bash -s <<'EOF'
set -euo pipefail
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
kubectl --kubeconfig .kube/local.yaml -n cert-manager \
get secret local-ca -o jsonpath='{.data.tls\.crt}' |
base64 -d > "$tmp/local-ca.crt"
kubectl --kubeconfig .kube/local.yaml -n gateway-system \
get secret wildcard-tls -o jsonpath='{.data.tls\.crt}' |
base64 -d > "$tmp/wildcard-tls.crt"
printf '%s\n' 'Current CA:'
openssl x509 -in "$tmp/local-ca.crt" -noout -subject -fingerprint -sha256
printf '%s\n' 'Gateway certificate:'
openssl x509 -in "$tmp/wildcard-tls.crt" -noout -issuer -fingerprint -sha256
printf '%s\n' 'Verify Gateway certificate against current CA:'
openssl verify -CAfile "$tmp/local-ca.crt" "$tmp/wildcard-tls.crt"
printf '%s\n' 'Certificate served by local endpoint:'
openssl s_client -connect auth.127.0.0.1.nip.io:443 \
-servername auth.127.0.0.1.nip.io </dev/null 2>/dev/null |
openssl x509 -noout -issuer -fingerprint -sha256
EOF
Interpret the results:
wildcard-tls.crt: OKmeans the Kubernetes Gateway certificate verifies against the currentlocal-cacertificate.- The endpoint fingerprint should match the Gateway certificate fingerprint. If not, the endpoint is serving a different certificate.
- In Firefox, inspect the imported CA certificate’s SHA-256 fingerprint. It must match the
Current CAfingerprint. If it differs, remove the stalelocal-caauthority and import the current CA certificate.
Export only the CA’s public certificate for Firefox import:
kubectl --kubeconfig .kube/local.yaml -n cert-manager \
get secret local-ca -o jsonpath='{.data.tls\.crt}' |
base64 -d > "$HOME/local-ca.crt"
Import $HOME/local-ca.crt under Firefox’s Authorities and trust it to identify websites. Do not import wildcard-tls.crt as an authority. The local CA can sign certificates; keep its private key secret and never distribute it.
VolSync Restic lock blocks forget
A VolSync Restic mover can save a snapshot successfully, then fail during forget because Restic cannot acquire the exclusive repository lock. The snapshot remains in the repository, but retention pruning does not complete. Repeated failed mover pods may each save another snapshot before hitting the same lock.
Use the kubeconfig configured for the target environment. For prod, repository cluster config writes .kube/prod.yaml. Inspect ReplicationSource status and mover pods:
kubectl --kubeconfig .kube/prod.yaml -n miniflux \
describe replicationsource backup
kubectl --kubeconfig .kube/prod.yaml -n miniflux get pods -o wide
kubectl --kubeconfig .kube/prod.yaml -n miniflux \
logs <volsync-src-backup-pod> --all-containers --tail=200
If logs show a saved snapshot followed by lock failure, backup data was written; forget failed. Last Sync Time and Last Pruned help distinguish latest successful replication from latest pruning. A lock age alone does not prove it is stale. Confirm its owner pod is gone and no backup, restore, or prune is still using the same repository before requesting unlock. Never remove a live lock.
VolSync supports a one-time unlock trigger on the affected ReplicationSource. In its desired manifest, add a new unique value under spec.restic:
spec:
restic:
unlock: "stale-lock-YYYYMMDD"
For this repo, update the source definition (for example apps/backup/prod/miniflux.yaml) and let Flux reconcile it. VolSync runs restic unlock before a subsequent replication; changing the field alone does not start a backup. Check status.restic.lastUnlocked and the next mover result. Reuse of the same value does not request another unlock; use a new value only for a later confirmed stale lock. Do not add unlock values to every backup source as routine prevention: unlock does not prevent future locks or fix overlapping jobs, and each source can target a different repository.
Kubernetes and K3s upgrades
This repository runs K3s in both k3d and an Incus NixOS VM. Upgrade paths differ: a k3d image change can replace the cluster, while the Incus NixOS module upgrades the K3s service on the existing VM.
Pick a target K3s release first. Review its release notes, Kubernetes API removals, and supported upgrade path. Pin an explicit version; avoid floating tags such as latest. Upgrade local/test first, verify workloads and storage, then proceed to higher-risk environments.
k3d
The k3d module gets the K3s release from the image input in each environment’s infra/env/<env>/cluster/terragrunt.hcl, for example:
image = "rancher/k3s:v1.36.1-k3s1"
Set the desired rancher/k3s:v<version>-k3s<revision> image in the target environment. Local, test, and prod each have their own input.
Treat an image change as potentially destructive. k3d does not provide an in-place cluster upgrade command; changing a node image may require recreating nodes or the cluster. Review the Terraform plan and stop if it proposes replacement until you have a migration plan. This module’s volumes input defaults to an empty list, so do not assume node-local files survive recreation. In particular, local-path PersistentVolume contents live on cluster nodes and are separate from Git/Flux configuration.
For data preservation, prefer a blue/green migration:
- Back up application data using each application’s supported procedure. For local-path PVs, back up the volume contents separately and store backups outside the cluster.
- Create a second cluster with the target K3s image and a different cluster name. Avoid host-port conflicts with the existing cluster; this module currently maps host ports
80,443, and30500. - Bootstrap the new cluster, restore application data, and verify workloads and services.
- Switch clients or traffic only after verification. Keep the old cluster and backups until the new cluster is proven healthy.
- Remove the old cluster only after confirming recovery and data persistence.
Do not expect changing the image input alone to migrate Kubernetes objects or PV data.
Incus NixOS K3s
infra/modules/nixos/profiles/k3s-server.nix enables services.k3s but does not set services.k3s.package. NixOS therefore uses the K3s package from the nixpkgs revision pinned by infra/modules/nixos/flake.lock. system.stateVersion is not the K3s version.
Update the pinned K3s package
From the NixOS flake directory:
cd infra/modules/nixos
nix flake lock --update-input nixpkgs
nix eval --raw .#nixosConfigurations.k3s-vm.config.services.k3s.package.version
Review flake.lock changes and the evaluated K3s package version before deployment. Updating nixpkgs can change other NixOS packages too. If the selected nixpkgs revision does not provide the desired K3s version, keep the lock unchanged and explicitly select a supported K3s package exposed by that pinned nixpkgs; verify the selected package version with nix eval.
Back up and deploy
K3s package upgrade through nixos-rebuild switch updates the service on the existing VM; it does not intentionally recreate the VM or uninstall K3s. Still, back up before upgrading. This profile configures one K3s server and no external datastore, so K3s uses its embedded datastore by default. Follow K3s backup guidance for the datastore and server token, and store the backup securely off the VM. Back up local-path PV contents separately; datastore backup does not contain application files.
Then review and apply only the Incus cluster stack:
cd infra/env/incus/cluster
terragrunt run --tf-path tofu plan
terragrunt run --tf-path tofu apply
The NixOS module hashes the local flake files. A changed flake.lock triggers its nixos-rebuild switch deployment, then the module re-exports the kubeconfig to .kube/incus.yaml.
Verify the deployed node version and workloads using the configured kubeconfig:
kubectl --kubeconfig .kube/incus.yaml get nodes \
-o custom-columns=NAME:.metadata.name,KUBELET:.status.nodeInfo.kubeletVersion
kubectl --kubeconfig .kube/incus.yaml get pods -A
Do not skip supported K3s/Kubernetes upgrade steps or assume downgrade is safe. If the upgrade fails, use the tested backup and recovery procedure rather than uninstalling K3s or deleting its data directories.
PVC Backup and Restore with VolSync
This guide describes backing up a PersistentVolumeClaim (PVC) to a Restic repository with VolSync, then restoring it to a PVC.
Requirements
- VolSync installed in the cluster. This repository installs it from
platform/base/volsync/. - A Restic-compatible remote repository, such as the S3-compatible repository used by the test backup.
- A Kubernetes Secret in the workload namespace containing Restic settings. VolSync expects
RESTIC_REPOSITORYandRESTIC_PASSWORD; S3 repositories also need provider credentials, such asAWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY. - Source PVC exists and is mounted by the workload.
Keep the Restic password and repository credentials outside the cluster being protected. For disaster recovery, do not rely on OpenBao to supply the credentials needed to restore OpenBao itself. Preserve OpenBao’s unseal material outside the cluster too.
Define a backup
Create a ReplicationSource in the same namespace as the source PVC and repository Secret:
apiVersion: volsync.backube/v1alpha1
kind: ReplicationSource
metadata:
name: app-backup
namespace: app-namespace
spec:
sourcePVC: app-data
trigger:
manual: backup-001
restic:
repository: backup-secret
copyMethod: Direct
retain:
daily: 7
weekly: 4
monthly: 3
repository names the Kubernetes Secret containing Restic settings. For a manual backup, change trigger.manual to a new value to request another backup. Alternatively, configure a schedule, for example schedule: "0 2 * * *".
copyMethod: Direct reads the source PVC while the application may be running. It does not create a point-in-time snapshot. Use an application-consistent backup method or a supported CSI snapshot copy method when the workload requires consistency.
Set moverSecurityContext when the mover needs specific filesystem permissions. Match it to the source data ownership; do not copy another workload’s UID/GID blindly. OpenBao’s test data was owned by UID 100 and GID 1000, so its backup uses:
moverSecurityContext:
runAsUser: 100
runAsGroup: 1000
fsGroup: 1000
Verify a backup
Check the ReplicationSource status. A completed backup should report a successful result, a last sync time, and a Restic snapshot ID. Do not treat repository initialization alone as a completed backup.
Example read-only command:
kubectl -n app-namespace describe replicationsource app-backup
Restore to a PVC
A ReplicationDestination restores into a PVC that already exists. destinationPVC names the claim; it does not create it. Create the destination PVC first, with suitable storage class, access mode, and capacity.
Example destination resource:
apiVersion: volsync.backube/v1alpha1
kind: ReplicationDestination
metadata:
name: app-restore
namespace: app-namespace
spec:
trigger:
manual: restore-001
restic:
repository: backup-secret
destinationPVC: app-data-restored
copyMethod: Direct
The destination PVC and ReplicationDestination must be in the same namespace. The repository Secret must be present before the restore starts. During disaster recovery, create that Secret from credentials stored outside the lost cluster; do not depend on the application being restored to provide it.
For a workload with restricted file permissions, set the restore mover’s security context to match the file ownership in the backup. The OpenBao restore example uses UID 100 and GID 1000.
OpenBao System Disaster Recovery
OpenBao stores cluster secrets in its Raft data PVC. If the cluster is lost, restore that PVC into a fresh cluster before starting OpenBao. This is a cold restore, not an in-place restore while OpenBao is running.
Prepare backups
Back up the OpenBao data PVC with a VolSync ReplicationSource:
apiVersion: volsync.backube/v1alpha1
kind: ReplicationSource
metadata:
name: openbao-backup
namespace: vault-system
spec:
sourcePVC: openbao-data
trigger:
manual: backup-001
restic:
repository: backup-secret
copyMethod: Direct
moverSecurityContext:
runAsUser: 100
runAsGroup: 1000
fsGroup: 1000
retain:
daily: 7
weekly: 4
monthly: 3
Change trigger.manual to a new value to request another backup. Confirm the ReplicationSource reports a successful sync and Restic snapshot before relying on it. copyMethod: Direct reads live files; it does not create a point-in-time snapshot.
Keep these recovery items outside the cluster:
- Restic password and repository credentials. OpenBao cannot provide its own restore credentials after it is lost.
- The
openbao-unsealSecret, required to unseal restored data. - Any bootstrap values needed to start and configure OpenBao.
Export the unseal Secret before disaster:
kubectl -n vault-system get secret openbao-unseal -o yaml \
> /secure/offline/openbao-unseal.yaml
The unseal Secret contains sensitive key material. Store this file in encrypted offline storage, never in Git; base64 in a Kubernetes YAML file is not encryption. Confirm the active kubectl context targets the intended cluster before running commands.
Restore manually to a fresh cluster
-
Provision the fresh cluster and install VolSync. Keep OpenBao stopped until PVC restore completes. Temporarily exclude the
platform-vaultFlux Kustomization in the environment overlay:patches: - patch: |- $patch: delete apiVersion: kustomize.toolkit.fluxcd.io/v1 kind: Kustomization metadata: name: platform-vault namespace: flux-system -
Confirm the active kubectl context targets the fresh cluster. Ensure the
vault-systemnamespace exists; create it if needed. Createbackup-secretin that namespace using credentials saved outside the lost cluster. Do not get these values from OpenBao during recovery. A protected local env file avoids placing credentials in shell history:kubectl create secret generic backup-secret \ --namespace=vault-system \ --from-env-file=/secure/offline/backup-secret.envThe env file must define
RESTIC_REPOSITORY,RESTIC_PASSWORD,AWS_ACCESS_KEY_ID, andAWS_SECRET_ACCESS_KEYfor this S3 example. Keep it out of the repository. -
Create the destination PVC manually before restore:
apiVersion: v1 kind: PersistentVolumeClaim metadata: name: openbao-data namespace: vault-system spec: accessModes: - ReadWriteOnce resources: requests: storage: 10GiSave this manifest locally, then apply it with
kubectl apply -f <pvc-manifest>. Ensure storage class and capacity match the replacement cluster. -
Apply this
ReplicationDestinationmanually.destinationPVCnames the existing claim; it does not create one:apiVersion: volsync.backube/v1alpha1 kind: ReplicationDestination metadata: name: openbao-restore namespace: vault-system spec: trigger: manual: restore-001 restic: repository: backup-secret destinationPVC: openbao-data copyMethod: Direct moverSecurityContext: runAsUser: 100 runAsGroup: 1000 fsGroup: 1000Save the manifest locally and apply it with
kubectl apply -f <restore-manifest>. Wait for theReplicationDestinationto report successful completion. Remove the temporaryReplicationDestinationafter restore; leave the PVC in place. -
Recreate the
openbao-unsealSecret from its securely stored backup withkubectl apply -f /secure/offline/openbao-unseal.yaml. Then re-enableplatform-vault. Patchvault-configso it does not try to create a secondopenbao-dataPVC:patches: - patch: |- - op: remove path: /spec/values/persistence/data target: group: helm.toolkit.fluxcd.io version: v2 kind: HelmRelease name: vault-config namespace: flux-systemThe PVC was created manually, so keep this patch while OpenBao uses it. Then start OpenBao, verify it is healthy and unsealed, and start dependent applications.
The Vault resource in platform/base/vault/openbao.yaml mounts openbao-data at /openbao/data. If using a different PVC name, update both ReplicationDestination.spec.restic.destinationPVC and spec.volumes[].persistentVolumeClaim.claimName to match.
Destroy prod while keeping the B2 backup
The infra/env/prod/backup Terragrunt unit owns the B2 bucket, VolSync application key, Restic password, and backup credential object. Keep this unit intact until recovery is complete and restored data is verified. Do not run an unfiltered make destroy env=prod; that includes the backup unit.
From the repository root, first preview destruction of the other prod units:
cd infra/env/prod
terragrunt run --tf-path tofu --all --filter '!./backup' -- plan -destroy -parallelism=3
Review the plan and confirm it does not include resources from ./backup. The backup unit may still be read for dependency outputs; the filter excludes it from the operation queue. Once the restore is verified and the plan is correct, destroy the other units:
terragrunt run --tf-path tofu --all --filter '!./backup' --non-interactive -- destroy -parallelism=3
This leaves the B2 bucket and its Terragrunt state in place. After backups are no longer needed, destroy that unit separately and review the confirmation prompt:
cd infra/env/prod/backup
terragrunt run --tf-path tofu -- destroy
Destroying backup removes the managed B2 bucket and backup credentials; do this only after deciding the stored recovery data is no longer needed.
Kubernetes Resource Right-Sizing Summary
Source: https://oneuptime.com/blog/post/2026-01-06-kubernetes-right-size-resources/view
Short summary
Resource requests and limits should be based on real usage, not copied defaults. Requests control scheduling and guaranteed capacity. Limits cap runtime usage. Bad values cause wasted money, CPU throttling, OOM kills, and poor scheduling.
Right-sizing should be a continuous process: observe usage, compare against requests and limits, adjust, then repeat.
Requests vs limits
| Setting | CPU behavior | Memory behavior |
|---|---|---|
| Request | Used by scheduler for placement; guaranteed minimum | Used by scheduler for placement; guaranteed minimum |
| Above request | Can burst if spare CPU exists | Can use available memory |
| At or above limit | CPU throttled | Container can be OOMKilled |
Main problems
Over-provisioned resources
Requests are much higher than actual usage.
Impact:
- Nodes look full while mostly idle.
- Cluster autoscaler adds unnecessary nodes.
- Cloud cost increases.
Under-provisioned resources
Requests or limits are much lower than actual usage.
Impact:
- Scheduler packs too many pods onto nodes.
- CPU throttling causes latency spikes.
- Memory pressure causes OOM kills and restarts.
Recommended sizing rules
| Resource | Recommended baseline |
|---|---|
| CPU request | P95 of normal CPU usage |
| CPU limit | 2x to 5x CPU request, or no CPU limit for bursty workloads |
| Memory request | P99 memory usage plus 10 percent to 20 percent buffer |
| Memory limit | Same as request or slightly higher |
Workload patterns
Web API
- Latency-sensitive.
- CPU limit should allow bursts.
- Memory should be stable.
Typical pattern:
resources:
requests:
cpu: 200m
memory: 512Mi
limits:
cpu: 1000m
memory: 512Mi
Background worker
- Throughput-focused.
- CPU limit can be removed to allow full node burst.
- Memory limit still useful to prevent runaway usage.
Typical pattern:
resources:
requests:
cpu: 500m
memory: 1Gi
limits:
memory: 1Gi
Batch job
- Predictable resource usage.
- Request can equal limit for stable performance.
Typical pattern:
resources:
requests:
cpu: 1000m
memory: 2Gi
limits:
cpu: 1000m
memory: 2Gi
PromQL examples
CPU P95 per pod
Use this for CPU request comparison.
quantile_over_time(0.95, (
sum by (namespace, pod) (
max by (namespace, pod, container) (
rate(container_cpu_usage_seconds_total{
container!="",
container!="POD",
image!=""
}[$__rate_interval])
)
)
)[$__range:])
To keep only pods that currently exist:
quantile_over_time(0.95, (
sum by (namespace, pod) (
max by (namespace, pod, container) (
rate(container_cpu_usage_seconds_total{
container!="",
container!="POD",
image!=""
}[$__rate_interval])
)
)
)[$__range:])
and on (namespace, pod)
max by (namespace, pod) (kube_pod_info)
Memory P99 per pod
Use this for memory request comparison.
quantile_over_time(0.99, (
sum by (namespace, pod) (
max by (namespace, pod, container) (
container_memory_working_set_bytes{
container!="",
container!="POD",
image!=""
}
)
)
)[$__range:])
To keep only pods that currently exist:
quantile_over_time(0.99, (
sum by (namespace, pod) (
max by (namespace, pod, container) (
container_memory_working_set_bytes{
container!="",
container!="POD",
image!=""
}
)
)
)[$__range:])
and on (namespace, pod)
max by (namespace, pod) (kube_pod_info)
CPU throttling ratio
Use this to detect CPU limits that are too low.
sum by (namespace, pod, container) (
rate(container_cpu_cfs_throttled_periods_total{
container!="",
container!="POD",
image!=""
}[$__rate_interval])
)
/
clamp_min(
sum by (namespace, pod, container) (
rate(container_cpu_cfs_periods_total{
container!="",
container!="POD",
image!=""
}[$__rate_interval])
),
0.001
)
Values above 0.1 mean more than 10 percent of CPU scheduling periods were throttled.
Kubernetes QoS classes
| QoS class | Resource config | Eviction priority |
|---|---|---|
| Guaranteed | Request equals limit for all CPU and memory fields | Last evicted |
| Burstable | Requests set, limits different or missing | Middle |
| BestEffort | No requests and no limits | First evicted |
BestEffort should be avoided for important workloads.
Useful tools
- VPA in recommendation-only mode: gives request recommendations without applying them.
- Goldilocks: creates VPA recommendations and shows sizing dashboard.
- Kubecost: shows wasted cost and over-provisioning.
- kube-capacity / resource-capacity plugin: shows cluster and namespace resource usage.
Dashboard impact
Recommended dashboard columns:
CPU table
pod | cpu request | p95 cpu usage | cpu limit | cpu request / p95 | cpu throttling %
Memory table
pod | mem request | p99 mem usage | mem limit | mem request / p99 | restarts / oom
Overview
pods | all cpu requests | all cpu limits | all memory requests | all memory limits | current cpu usage | current memory usage
Practical guidance
- Use CPU P95 as baseline for CPU request.
- Use memory P99 plus buffer as baseline for memory request.
- Avoid very high CPU limits compared to CPU requests.
- Consider removing CPU limits for bursty workloads if cluster policy allows it.
- Keep memory limits close to realistic high-water usage because exceeding memory limit causes OOMKilled.
- Track CPU throttling and OOM/restarts before changing production resource values.
Flux CD Platform vs Apps Architecture
Overview
This repository uses Flux CD to continuously deploy two logical layers:
- Platform – shared infrastructure (cert‑manager, kgateway, dex, reflector, cloudflared). Implemented as a Flux
Kustomizationthat points to./platform/<env>and contains only HelmRelease resources. - Apps – user applications (miniflux, glance, stump, …). Implemented as a Flux
Kustomizationthat points to./appsets/<env>which aggregates per‑app Kustomizations underapps/<app>/<env>.
Both layers live under the same Git repository but are kept separate so that platform components are guaranteed to be healthy before any application resources are reconciled.
Current Approach (Platform + Apps with appsets)
infra/env/<env>/k3d/
├─ platform.yaml # Flux Kustomization → ./platform/<env>
└─ apps.yaml # Flux Kustomization → ./appsets/<env>
appsets/<env>/kustomization.yaml
└─ resources:
├─ ../../apps/glance/<env>
├─ ../../apps/miniflux/<env>
└─ ../../apps/stump/<env>
apps/<app>/<env>/
├─ ns.yaml
├─ app.yaml
├─ config.yaml (optional)
└─ httproute.yaml
appsKustomization hasdependsOn: platform→ platform must be reconciled first.platformKustomization useswait: trueand health checks for dex, guaranteeing a ready ingress before apps are applied.- Adding a new app means:
- Create the manifests under
apps/<app>/<env>. - Add a reference to the new app in
appsets/<env>/kustomization.yaml.
- Create the manifests under
- Removing an app from the
appsetslist prunes all its resources. The manifests stay in Git.
Advantages
| Item | Benefit |
|---|---|
| Clear separation | Platform and apps are isolated – a failure in one does not automatically affect the other. |
| Dependency control | dependsOn guarantees that the gateway, TLS certs and Dex are ready before any app routes are created. |
| Prune safety | Removing an app from appsets deletes only that app’s resources; platform stays untouched. |
| Scalable | Adding more apps does not increase the number of Flux Kustomizations – only the appsets list grows. |
| Environment aware | Separate appsets/local and appsets/test allow per‑environment app selection. |
| Git‑single source of truth | All manifests remain version‑controlled; you never edit live cluster objects. |
Disadvantages
| Issue | Impact |
|---|---|
| Manual list management | Every new app requires an entry in appsets/<env>/kustomization.yaml. |
| Extra indirection | Two levels of Kustomization (appsets → per‑app) adds a small learning curve. |
| Slower roll‑out | apps waits for platform on each reconciliation, adding a few seconds latency. |
| Limited health checks | Current platform Kustomization only checks Dex; other platform components are not explicitly verified. |
| No per‑app suspend | Flux cannot pause a single app without removing it from appsets. |
Alternative Approaches (for reference only)
- One giant Kustomization – combine platform and apps in a single Flux resource.
- Simpler file layout but loses the platform‑first guarantee and makes debugging harder.
- Per‑app Kustomizations with
suspend: true– each app has its own FluxKustomization.- Gives fine‑grained pause/resume but introduces many small Kustomization files, cluttering the repo.
- Patch‑based pause (replicas: 0) – keep all manifests but add a replica‑scale patch.
- Leaves services and routes in the cluster, which may cause unwanted traffic.
Recommendation
For this repo the current platform + appsets split is the preferred pattern because it balances safety, scalability, and simplicity. If you need a per‑app pause in the future, consider adding a lightweight overlay folder (e.g., appsets/<env>/disabled) and moving unwanted apps there, keeping the same single‑Kustomization design.
Controlling App Deployment
- Enable an app: Add its path to
appsets/<env>/kustomization.yaml. - Disable an app: Remove its entry from the same file – Flux will prune the resources, leaving the manifests untouched in Git.
- No resource creation: When an app is not listed, no Deployment, Service, HTTPRoute, ConfigMap, or PVC is created in the cluster.