Skip to content

APISIX memory leak crashlooping VictoriaMetrics

Date: 2026-06-16 Severity: High Duration: 7 days undetected Status: Resolved


Incident Summary

Two VictoriaMetrics pods in the monitoring namespace were in CrashLoopBackOff for 7 days with 84 restarts each. The root cause was an APISIX memory leak with no memory limits, causing node memory pressure, disk I/O failures, and corrupted Longhorn storage replicas.

Affected pods: - vmselect-vm-stack-victoria-metrics-k8s-stack-0 - vmstorage-vm-stack-victoria-metrics-k8s-stack-1


Timeline

Time Event
7 days before discovery APISIX memory leak consumed 7.6GB RAM
7 days before discovery Node memory pressure — only 800MB free on 16GB node
7 days before discovery Disk write buffers failed to flush
7 days before discovery sdd and sdf filesystem journals aborted, remounted read-only
7 days before discovery Longhorn replicas on bad disks corrupted
7 days before discovery vmselect-0 and vmstorage-1 entered CrashLoopBackOff
2026-06-16 Incident discovered and fully resolved

Root Cause Analysis

Root Cause Chain

APISIX memory leak (no memory limits set)
→ 7.6GB RAM consumed on 16GB node
→ Node memory pressure (800MB free)
→ Disk write buffers could not flush
→ sdd/sdf filesystem journals aborted
→ EXT4 remounted read-only
→ Longhorn replicas corrupted
→ vmselect-0 and vmstorage-1 CrashLoopBackOff

APISIX Memory Leak Detail

  • APISIX 3.16.0 on OpenResty/LuaJIT with 0 routes configured
  • 8 nginx worker processes each consuming ~600MB
  • LuaJIT GC not collecting due to no memory pressure
  • No memory limits set — grew unchecked over 4+ days
  • Memory before fix: 7.6GB across 3 pods
  • Memory after fix: 355MB across 3 pods (95% reduction)

Disk Failure Detail

Disks sdd and sdf on ubuntu-24-04-lts-control-plane showed critical errors:

FATAL: cannot create lock file /vm-data/flock.lock: input/output error
EXT4-fs: Aborting journal on device sdd-8
EXT4-fs: Remounting filesystem read-only
critical medium error, dev sdf, sector 7440

Investigation Steps

1. Find Failing Pods

kubectl get pods -A | grep -iv running

2. Check Pod Logs

kubectl logs -n monitoring vmstorage-vm-stack-victoria-metrics-k8s-stack-1 --previous

Found: input/output error on storage paths.

3. Check Node Disk Health

dmesg | grep -iE "critical|unrecovered|offline"

Found: sdd and sdf with unrecovered read errors and aborted journals on ubuntu-24-04-lts-control-plane.

4. Verify etcd Safety

ls -la /var/lib/rancher/k3s/server/db/
df -h /var/lib/rancher/k3s/server/db/
k3s etcd-snapshot ls

etcd was safe on vda1 (main OS disk). Fresh snapshot confirmed.

5. Check Longhorn Replicas

kubectl get replicas.longhorn.io -n longhorn-system \
  -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeID,VOLUME:.spec.volumeName,STATE:.status.currentState'

Found: Bad replicas on failed disks showing stale running status.

6. Confirm Healthy Replicas on Other Nodes

kubectl get volumes.longhorn.io -n longhorn-system \
  -o custom-columns='NAME:.metadata.name,REPLICAS:.spec.numberOfReplicas,ROBUSTNESS:.status.robustness' \
  | grep -E "pvc-83488d0f|pvc-4f4eaf6e"

Confirmed 2 healthy replicas per volume on other nodes — safe to proceed.

7. Identify Memory Root Cause

kubectl top pods -A --sort-by=memory | head -20

Found: APISIX consuming 7.6GB with no memory limits set.


Resolution Steps

Step 1 — Delete Bad Longhorn Replicas

kubectl delete replica.longhorn.io \
  pvc-4f4eaf6e-998f-442a-a7e1-ad9a6f99c29e-r-26064cca \
  pvc-83488d0f-2be8-4506-9dcf-b4dab7d22e2c-r-a2bba56e \
  -n longhorn-system

Longhorn automatically rebuilt fresh replicas on healthy nodes.

Step 2 — Recover Monitoring Stack

kubectl scale statefulset vmselect-vm-stack-victoria-metrics-k8s-stack -n monitoring --replicas=0
kubectl scale statefulset vmstorage-vm-stack-victoria-metrics-k8s-stack -n monitoring --replicas=0

kubectl scale statefulset vmselect-vm-stack-victoria-metrics-k8s-stack -n monitoring --replicas=3
kubectl scale statefulset vmstorage-vm-stack-victoria-metrics-k8s-stack -n monitoring --replicas=3

All 6 pods recovered successfully.

Step 3 — Restart APISIX

kubectl rollout restart deployment apisix -n ingress-apisix

Memory dropped from 7.6GB to 355MB immediately.

Step 4 — Set APISIX Memory Limits via Helm

Updated apisix-values-update.yaml:

apisix:
  resources:
    requests:
      memory: 256Mi
      cpu: 100m
    limits:
      memory: 1Gi
      cpu: 1000m
  readinessProbe:
    enabled: true
    initialDelaySeconds: 10
    periodSeconds: 10
    failureThreshold: 6
    timeoutSeconds: 5
  livenessProbe:
    enabled: true
    initialDelaySeconds: 30
    periodSeconds: 15
    failureThreshold: 3
    timeoutSeconds: 5
  startupProbe:
    enabled: true
    initialDelaySeconds: 10
    periodSeconds: 5
    failureThreshold: 12
    timeoutSeconds: 5
  podDisruptionBudget:
    enabled: true
    minAvailable: 2
etcd:
  livenessProbe:
    enabled: false
  readinessProbe:
    enabled: false
  resources:
    requests:
      memory: 128Mi
      cpu: 50m
    limits:
      memory: 512Mi
      cpu: 500m

Applied with:

helm upgrade apisix apisix/apisix \
  -n ingress-apisix \
  -f apisix-values-update.yaml \
  --version 2.14.1 \
  --no-hooks

Note: --no-hooks is required because pre-upgrade hooks expect bitnami entrypoint scripts not present in quay.io/coreos/etcd.

Step 5 — Create Weekly Restart CronJob

kubectl apply -f - << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
  name: apisix-restart-sa
  namespace: ingress-apisix
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: apisix-restart-role
  namespace: ingress-apisix
rules:
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "patch", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: apisix-restart-rolebinding
  namespace: ingress-apisix
subjects:
- kind: ServiceAccount
  name: apisix-restart-sa
  namespace: ingress-apisix
roleRef:
  kind: Role
  apiGroup: rbac.authorization.k8s.io
  name: apisix-restart-role
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: apisix-restart
  namespace: ingress-apisix
spec:
  schedule: "0 2 * * 0"
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 3
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: apisix-restart-sa
          containers:
          - name: restart
            image: bitnami/kubectl:latest
            command:
            - kubectl
            - rollout
            - restart
            - deployment/apisix
            - -n
            - ingress-apisix
          restartPolicy: OnFailure
EOF

Step 6 — Clean Orphaned Longhorn Replicas

kubectl delete replica.longhorn.io \
  pvc-5810a8e4-b444-4400-9534-32509ca07df0-r-ada644d4 \
  pvc-841fe9f1-2a5e-4a5a-a2e8-86bb8b663e5e-r-8dc38e8a \
  pvc-dca24e67-2f2f-4c97-9c03-9627b5b2fb6d-r-cfe053e2 \
  pvc-e08a0006-4e2c-44e8-9f14-3d329cd12396-r-cc722af5 \
  -n longhorn-system

Step 7 — Reduce Replica Count for Over-Provisioned Volumes

Node ubuntu-24-04-lts-control-plane had 56GB scheduled against 82GB max leaving no room for 3rd replica placement.

for vol in \
  pvc-5810a8e4-b444-4400-9534-32509ca07df0 \
  pvc-841fe9f1-2a5e-4a5a-a2e8-86bb8b663e5e \
  pvc-dca24e67-2f2f-4c97-9c03-9627b5b2fb6d \
  pvc-e08a0006-4e2c-44e8-9f14-3d329cd12396; do
  kubectl patch volume.longhorn.io $vol \
    -n longhorn-system \
    --type=merge \
    -p '{"spec":{"numberOfReplicas":2}}'
done

Prevention Measures Applied

Measure Detail Status
APISIX memory limit 1GB hard limit — OOMKills before node starves Applied
APISIX readiness probe Removes unhealthy pod from load balancer Applied
APISIX liveness probe Restarts pod if it hangs or deadlocks Applied
APISIX startup probe Gives APISIX time to initialize Applied
Pod Disruption Budget Keeps minimum 2/3 pods during updates Applied
Weekly restart CronJob Prevents memory accumulation Applied
APISIX helm upgraded 2.14.0 to 2.14.1 Applied
etcd probes disabled Incompatible with coreos/etcd image Fixed
Orphaned replicas cleaned Removed stale stopped replicas Done
Volume replica count adjusted 3 to 2 for over-provisioned node Done

Final Cluster State

Node Memory

ubuntu-24-04-lts-control-plane   66%
ubuntu-mashup-gitlab-haproxy     59%
worker-node-a                    60%

APISIX Memory After Fix

Pod 1:   179Mi
Pod 2:    68Mi
Pod 3:   103Mi
Total:   350Mi  (was 7.6GB)

Monitoring Stack

vmselect-0   1/1 Running
vmselect-1   1/1 Running
vmselect-2   1/1 Running
vmstorage-0  1/1 Running
vmstorage-1  1/1 Running
vmstorage-2  1/1 Running

Pending Tasks

Task Priority Reason
Add disk to ubuntu-24-04-lts-control-plane Medium Allow 3 replicas again for affected volumes
Set up Longhorn volume health alerts Medium Get notified of degraded volumes immediately
Set up node memory alerts above 80% High Early warning before next memory pressure
Monitor APISIX memory weekly Medium Confirm limit is working as expected
Audit all pods without memory limits Medium Prevent similar incidents on other pods

Check pods without memory limits:

kubectl get pods -A -o json | jq -r '
  .items[] |
  select(.spec.containers[].resources.limits == null) |
  "\(.metadata.namespace)/\(.metadata.name)"'

Lessons Learned

1. Always Set Memory Limits

Every pod must have resources.limits.memory. Without limits a single leaking pod consumes all node RAM and cascades into storage failures affecting the entire cluster.

2. Longhorn Does Not Auto-Detect Underlying Disk Failures

Longhorn shows replica as running even when the underlying filesystem has aborted its journal. Manual investigation via dmesg on the correct node is required to detect actual disk health issues.

3. Memory Pressure Cascades Into Disk Failures

The failure chain is not obvious: node memory pressure causes disk write buffer failures, which cause filesystem journal aborts, which cause application crashes. What looks like a disk problem is actually a memory problem.

4. Always Check etcd Safety First

Before making any changes to a degraded cluster, verify etcd is on a healthy disk and has recent snapshots. If etcd is compromised, all other actions are secondary.

5. SSH to the Correct Node

Always SSH to the specific node where failing pods are scheduled before running dmesg. Running diagnostics on the wrong node gives misleading results.

6. Two Replicas Is Acceptable for Three-Node Clusters

With 3 nodes, losing 2 makes the cluster non-functional regardless of replica count. Match replica count to actual schedulable capacity rather than fighting over-provisioning warnings.

7. Investigate Before Acting

Check etcd, disk health, replica health, and node resources fully before taking any remediation action. Rushing to fix without understanding the scope can make things worse.


Key Commands Reference

# Find non-running pods
kubectl get pods -A | grep -iv running

# Check Longhorn volume health
kubectl get volumes.longhorn.io -n longhorn-system | grep -iv healthy

# Check Longhorn replicas with node assignment
kubectl get replicas.longhorn.io -n longhorn-system \
  -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeID,VOLUME:.spec.volumeName,STATE:.status.currentState'

# Check node disk errors
dmesg | grep -iE "critical|unrecovered|offline|error" | tail -30

# Check top memory consumers
kubectl top pods -A --sort-by=memory | head -20

# Check node memory
kubectl top nodes

# Restart APISIX manually
kubectl rollout restart deployment apisix -n ingress-apisix

# Check etcd snapshots
k3s etcd-snapshot ls

# Scale statefulset down and up
kubectl scale statefulset <name> -n <namespace> --replicas=0
kubectl scale statefulset <name> -n <namespace> --replicas=3

Document generated: 2026-06-16 Next review: 2026-07-16