KONG-40 POC: Apache APISIX Kubernetes Service Discovery, Load Balancing, and Health Checking Validation

KONG-40 POC: Apache APISIX Kubernetes Service Discovery, Load Balancing, and Health Checking Validation

Overview

This POC validates that Apache APISIX, using its Kubernetes service discovery plugin, can:

  1. Discover sidecar pods, while remaining blind to the modules which sit behind them.

  2. Load balance across discovered sidecar instances using multiple strategies (round robin, lead connections, etc.)

  3. Detect changes (unhealthy/new) sidecars and make the necessary adjustments when routing/load balancing requests.

Environment: local minikube cluster, Apache APISIX + etcd deployed via the official Helm chart, module/sidecar pods deployed via a custom Helm chart.NOTE: plain old Apache APISIX was used for this PoC, as folio-apisix was not ready when this was worked on.

Summary of Findings

Area

Finding

Area

Finding

Discovery scoping

Excluding the module container from discovery is achieved entirely through Kubernetes Service design — the sidecar's Service declares only the sidecar's port. The module's port is never referenced in any Service, so it never appears in an Endpoints object, regardless of any discovery-side filtering. This matches FOLIO/Eureka’s architecture. namespace_selector/label_selector are coarse pre-filters, not the exclusion mechanism.

Discovery mechanism

APISIX uses Kubernetes' native List-Watch pattern (a one-time List for a full picture at startup, then a persistent Watch stream for incremental changes) — this is a push model, and does not rely on polling. Node-list updates in APISIX typically reflect cluster changes quickly - within ~1-2 seconds.

Load balancing

roundrobin (smooth weighted) verified evenly distributing traffic across 3 replicas over a various request sample sizes (50, 100, 1000, etc.) chash, least_conn, and ewma are also available (see Appendix A).

Health checking

Two layers here:

(1) APISIX active health checks: HTTP probe through the full sidecar→module path; on failure, the node stays visible in the discovery dump but is excluded from routing (/v1/healthcheck shows it as unhealthy). Detection/recovery is fast and fully internal to APISIX, and only affects APISIX's own routing.

(2) Kubernetes readiness probes: on failure, the pod is removed from the Endpoints object entirely, so it disappears from APISIX's discovered node set altogether. This affects every consumer of that Service (not just APISIX), and propagates through more hops (kubelet → Pod status → Endpoint controller → APISIX's watch), so it's typically a bit slower/less deterministic than APISIX’s active health checks.

Recommendation: run both — these cover different failure classes and different consumers, and the overhead of both is negligible.

Container crash recovery

Kubernetes' default restartPolicy: Always restarts any container that exits, with zero configuration required — this alone recovers a genuinely crashed process for both containers. Liveness probes extend this to catch a hung-but-not-exited process, but are only safe to use where the check has no downstream dependency: the module container's /healthz is self-contained, so it safely carries both readinessProbe and livenessProbe. The sidecar intentionally has no livenessProbe (to match the real sidecar's aggregate health signal), reusing it for liveness would cause Kubernetes to repeatedly kill and restart a perfectly healthy sidecar any time its module happens to be down. The sidecar's crash recovery therefore relies on restartPolicy: Always alone, with readinessProbe (not liveness) handling the "can't currently serve traffic" case.

Namespace separation

While not necessary, it makes sense to run APISIX/etcd in a separate namespace (apisix in the PoC) from the module/sidecar pods (poc in the PoC) — independent lifecycle (teardown/redeploy either side without touching the other). This is not mandatory and is ultimately a choice system operators will need to make. It’s included here because there are implications for configuration. The main cost of using separate namespaces in this way is that APISIX's ServiceAccount needs a cluster-scoped ClusterRole rather than a namespace-scoped Role to watch pod Endpoints across namespaces — largely unavoidable anyway given that it’s common to have more than one module namespace. For instance the etesting rancher env has several namespaces (sprint, snapshot, etc.) This may also come into play when running multiple versions of FOLIO in the same deployment.

Observability gap

Neither the APISIX Dashboard nor kubectl expose a unified "live discovered nodes" view. The APISIX Dashboard only manages Admin API config (routes/upstreams/checks settings); the actual resolved node list and live health status live exclusively on the separate Control API (port 9090), queried directly for all verification in this PoC.

Architecture at a Glance

image-20260716-173325.png

 

Namespace

Component

Purpose

Namespace

Component

Purpose

apisix

APISIX (2 replicas) + etcd

API Gateway data/control plane, discovers and load-balances across sidecars

poc

mod-foo (module + sidecar containers)

Sample module, path prefix /mod-foo

poc

mod-bar (module + sidecar containers)

Sample module, path prefix /mod-bar

Traffic flow: Client → APISIX Gateway → sidecar container → module container (same pod, proxy_pass to 127.0.0.1). APISIX never sees the module container directly.


Prerequisites

  • minikube, kubectl, helm installed

  • A running minikube cluster: minikube start

Optional:

  • yq is the yaml equivalent to jq and can be helpful for working with yaml, especially pulling out just the parts of responses you’re interested in.

Directory Structure

The PoC requires several files (helm charts, templates, configuration, etc.) The following depicts what the directory structure looks like after following all of the required steps outlined below.

. ├── rbac.yaml ├── sidecar-module │   ├── Chart.yaml │   ├── templates │   │   ├── configmap-module.yaml │   │   ├── configmap-sidecar.yaml │   │   ├── deployment.yaml │   │   └── service.yaml │   └── values.yaml ├── values-apisix.yaml ├── values-bar.yaml └── values-foo.yaml

Note: For the sake of brevity, heredocs have been used throughout these instructions.


Part 1: APISIX + etcd Setup

1.1 Add and pull the official Helm chart

helm repo add apisix https://charts.apiseven.com helm repo update

1.2 RBAC for Kubernetes discovery

The chart's own rbac.create only creates a namespace-scoped Role. Discovery needs a ClusterRole to watch endpoints/endpointslices across namespaces. :

cat > rbac.yaml <<'EOF' apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: apisix-discovery rules: - apiGroups: [""] resources: [endpoints] verbs: [get, list, watch] - apiGroups: ["discovery.k8s.io"] resources: [endpointslices] verbs: [get, list, watch] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: apisix-discovery roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: apisix-discovery subjects: - kind: ServiceAccount name: apisix namespace: apisix EOF kubectl apply -f rbac.yaml

It should look someting like this:

clusterrole.rbac.authorization.k8s.io/apisix-discovery created clusterrolebinding.rbac.authorization.k8s.io/apisix-discovery created

1.3 Helm values

cat > values-apisix.yaml <<'EOF' replicaCount: 2 etcd: enabled: true serviceAccount: create: true rbac: create: true discovery: enabled: true registry: kubernetes: watch_endpoint_slices: true nginx: envs: - KUBERNETES_SERVICE_HOST - KUBERNETES_SERVICE_PORT apisix: admin: enabled: true credentials: admin: edd1c9f034335f136f87ad84b625c8f1 viewer: 4054f7cf07e344346cd3f287985e76a2 service: type: ClusterIP externalTrafficPolicy: "" EOF

Note: admin_key above is APISIX's well-known example key — rotate it via a Secret before using this beyond a throwaway POC.

Note: externalTrafficPolicy: "" is required specifically because service.type: ClusterIP is incompatible with the chart's default externalTrafficPolicy: Cluster (that field is only valid for NodePort/LoadBalancer).

1.4 Install

helm install apisix apisix/apisix -f values-apisix.yaml \ --namespace apisix --create-namespace --atomic

1.5 Verify

kubectl -n apisix get pods kubectl -n apisix rollout status deployment/apisix

it should look something like this:

NAME READY STATUS RESTARTS AGE apisix-659599b4f4-6x8gh 1/1 Running 1 (21h ago) 23h apisix-659599b4f4-zzthk 1/1 Running 1 (21h ago) 23h apisix-etcd-0 1/1 Running 1 (21h ago) 23h apisix-etcd-1 1/1 Running 1 (21h ago) 23h apisix-etcd-2 1/1 Running 1 (21h ago) 23h deployment "apisix" successfully rolled out

Part 2: Module + Sidecar Helm Chart

One reusable chart, installed twice (once per module).

2.1 Chart skeleton

mkdir -p sidecar-module/templates cat > sidecar-module/Chart.yaml <<'EOF' apiVersion: v2 name: sidecar-module description: Generic module+sidecar pod for the APISIX k8s-discovery POC version: 0.1.0 EOF cat > sidecar-module/values.yaml <<'EOF' name: mod-foo message: "hello, i'm mod-foo" pathPrefix: /mod-foo modulePort: 8080 sidecarPort: 8081 image: nginx:1.27-alpine probes: periodSeconds: 2 failureThreshold: 2 successThreshold: 1 EOF

2.2 Module container config (static JSON response + health check)

cat > sidecar-module/templates/configmap-module.yaml <<'EOF' apiVersion: v1 kind: ConfigMap metadata: name: {{ .Values.name }}-module-conf data: nginx.conf: | user nginx; worker_processes 1; pid /var/run/nginx.pid; events { worker_connections 1024; } http { server { listen {{ .Values.modulePort }}; location = /healthz { return 200 "ok"; } location = /msg { default_type application/json; add_header X-Pod-Name $hostname; return 200 "{\"message\": \"{{ .Values.message }}\"}"; } } } EOF

Note: X-Pod-Name is added here to help show how traffic is being distributed. The $hostname variable, which is built-into nginx, resolves to the pod name. This is not required for the routing itself to work.

2.3 Sidecar container config (health check passthrough + path-prefix proxy)

cat > sidecar-module/templates/configmap-sidecar.yaml <<'EOF' apiVersion: v1 kind: ConfigMap metadata: name: {{ .Values.name }}-sidecar-conf data: nginx.conf: | user nginx; worker_processes 1; pid /var/run/nginx.pid; events { worker_connections 1024; } http { server { listen {{ .Values.sidecarPort }}; location = /healthz { proxy_pass http://127.0.0.1:{{ .Values.modulePort }}/healthz; } location {{ .Values.pathPrefix }}/ { rewrite ^{{ .Values.pathPrefix }}/(.*)$ /$1 break; proxy_pass http://127.0.0.1:{{ .Values.modulePort }}; } } } EOF

Note: The sidecar's /healthz deliberately passes health checks through to the module (via proxy_pass), modeling the real sidecar's behavior — see Appendix B for additional information on what was simplified.

2.4 Deployment (both containers, with liveness/readiness probes)

cat > sidecar-module/templates/deployment.yaml <<'EOF' apiVersion: apps/v1 kind: Deployment metadata: name: {{ .Values.name }} spec: replicas: 1 selector: matchLabels: app: {{ .Values.name }} template: metadata: labels: app: {{ .Values.name }} spec: containers: - name: module image: {{ .Values.image }} ports: - containerPort: {{ .Values.modulePort }} volumeMounts: - name: module-conf mountPath: /etc/nginx/nginx.conf subPath: nginx.conf readinessProbe: httpGet: path: /healthz port: {{ .Values.modulePort }} periodSeconds: {{ .Values.probes.periodSeconds }} failureThreshold: {{ .Values.probes.failureThreshold }} successThreshold: {{ .Values.probes.successThreshold }} livenessProbe: httpGet: path: /healthz port: {{ .Values.modulePort }} periodSeconds: {{ .Values.probes.periodSeconds }} failureThreshold: {{ .Values.probes.failureThreshold }} - name: sidecar image: {{ .Values.image }} ports: - name: sidecar-http containerPort: {{ .Values.sidecarPort }} volumeMounts: - name: sidecar-conf mountPath: /etc/nginx/nginx.conf subPath: nginx.conf readinessProbe: httpGet: path: /healthz port: {{ .Values.sidecarPort }} periodSeconds: {{ .Values.probes.periodSeconds }} failureThreshold: {{ .Values.probes.failureThreshold }} successThreshold: {{ .Values.probes.successThreshold }} volumes: - name: module-conf configMap: name: {{ .Values.name }}-module-conf - name: sidecar-conf configMap: name: {{ .Values.name }}-sidecar-conf EOF

Note: The sidecar has no livenessProbe block. This is intentional, per the finding above.

2.5 Sidecar-only Service (So only the Sidecar pod Endpoints are discoverable)

cat > sidecar-module/templates/service.yaml <<'EOF' apiVersion: v1 kind: Service metadata: name: {{ .Values.name }}-sidecar labels: app.kubernetes.io/component: sidecar spec: selector: app: {{ .Values.name }} ports: - name: http port: {{ .Values.sidecarPort }} targetPort: {{ .Values.sidecarPort }} EOF

2.6 Per-module values and deploy

kubectl create namespace poc cat > values-foo.yaml <<'EOF' name: mod-foo message: "hello, i'm mod-foo" pathPrefix: /mod-foo EOF cat > values-bar.yaml <<'EOF' name: mod-bar message: "hello, i'm mod-bar" pathPrefix: /mod-bar EOF helm install mod-foo ./sidecar-module -f values-foo.yaml -n poc helm install mod-bar ./sidecar-module -f values-bar.yaml -n poc

2.7 Verify sidecar-only visibility

kubectl -n poc get pods # you should only see the sidecar port here... kubectl -n poc get endpointslices -l kubernetes.io/service-name=mod-foo-sidecar -o yaml | grep port kubectl -n poc get endpointslices -l kubernetes.io/service-name=mod-bar-sidecar -o yaml | grep port

It should look something like this:

NAME READY STATUS RESTARTS AGE mod-bar-7cddf5867-xcvlc 2/2 Running 2 (22h ago) 23h mod-foo-7f9559bb68-m5tsq 2/2 Running 2 (22h ago) 23h ports: port: 8081 ports: port: 8081

Part 3: Register in APISIX

3.1 Port-forward (gateway, admin, and control ports, in one command)

POD=$(kubectl -n apisix get pods -l app.kubernetes.io/name=apisix -o jsonpath='{.items[0].metadata.name}') kubectl -n apisix port-forward pod/$POD 9080:9080 9180:9180 9090:9090 &

Note: You may want to do this in a separate terminal as the text emitted from the port forwarding can pollute your output causing confusion.

3.2 Create upstreams (discovery + active health check)

curl http://127.0.0.1:9180/apisix/admin/upstreams/mod-foo \ -H "X-API-KEY: $APISIX_KEY" -XPUT -d ' { "type": "roundrobin", "discovery_type": "kubernetes", "service_name": "poc/mod-foo-sidecar:http", "checks": { "active": { "type": "http", "http_path": "/healthz", "healthy": { "interval": 2, "successes": 1 }, "unhealthy": { "interval": 1, "http_failures": 2 } } } }' curl http://127.0.0.1:9180/apisix/admin/upstreams/mod-bar \ -H "X-API-KEY: $APISIX_KEY" -XPUT -d ' { "type": "roundrobin", "discovery_type": "kubernetes", "service_name": "poc/mod-bar-sidecar:http", "checks": { "active": { "type": "http", "http_path": "/healthz", "healthy": { "interval": 2, "successes": 1 }, "unhealthy": { "interval": 1, "http_failures": 2 } } } }'

3.3 Create routes (path-based, no rewrite needed)

The sidecar itself strips the path prefix before proxying to the module, so APISIX's route just needs a plain prefix match:

curl http://127.0.0.1:9180/apisix/admin/routes/mod-foo \ -H "X-API-KEY: $APISIX_KEY" -XPUT -d ' { "uri": "/mod-foo/*", "upstream_id": "mod-foo" }' curl http://127.0.0.1:9180/apisix/admin/routes/mod-bar \ -H "X-API-KEY: $APISIX_KEY" -XPUT -d ' { "uri": "/mod-bar/*", "upstream_id": "mod-bar" }'

3.4 End-to-end test

curl http://127.0.0.1:9080/mod-foo/msg # {"message": "hello, i'm mod-foo"} curl http://127.0.0.1:9080/mod-bar/msg # {"message": "hello, i'm mod-bar"}

Part 4: Verification & Demo Script

4.1 Confirm APISIX only sees sidecars

curl -s http://127.0.0.1:9090/v1/discovery/kubernetes/dump | jq '.'

Only poc/mod-foo-sidecar:http and poc/mod-bar-sidecar:http entries should appear — never a module port.

4.2 Manual scaling

kubectl scale deployment/mod-foo --replicas=3 -n poc kubectl -n poc get pods -l app=mod-foo

Note: Replica count is managed imperatively via kubectl scale (not templated in the chart) for this POC — re-run 4.1/4.2 after scaling to confirm the new replicas are discovered and receiving traffic.

4.3 Confirm even load-balancing distribution

for i in {1..100}; do curl -s -D - -o /dev/null http://127.0.0.1:9080/mod-foo/msg | grep -i x-pod-name done | sort | uniq -c

With equal weights and roundrobin, counts should be roughly even across all mod-foo replicas.

Example output:

34 X-Pod-Name: mod-foo-7f9559bb68-6nz2s 33 X-Pod-Name: mod-foo-7f9559bb68-lvz69 33 X-Pod-Name: mod-foo-7f9559bb68-m5tsq

4.4 List pod status

kubectl -n poc get pods -o wide # container states, probe config, Events section kubectl -n poc describe pod <pod-name> # live-watch state changes kubectl -n poc get pods -w

4.5 Simulate a module crash

kubectl -n poc get pods -l app=mod-foo kubectl -n poc exec <pod-name> -c module -- nginx -s stop

This kills only the module container (PID 1 inside it) — the sidecar container is unaffected. Kubernetes automatically restarts the crashed container (restartPolicy: Always, no config needed).

Observe both detection layers reacting independently (Hint: running these in loops which check every second, in separate terminals will help you see the actual state changes):

# APISIX active health check: node stays known, flagged unhealthy curl -s http://127.0.0.1:9090/v1/healthcheck | jq '.' # Kubernetes readiness: pod vanishes from Endpoints and from APISIX's discovered set entirely kubectl -n poc get endpoints mod-foo-sidecar -o yaml curl -s http://127.0.0.1:9090/v1/discovery/kubernetes/dump | jq '.endpoints[].endpoints[] | select(.name == "poc/mod-foo-sidecar").value' -r | jq .

Note: Regarding repeated crashes: A single, isolated crash restarts near-instantly. But if you run this simulation multiple times in quick succession on the same pod (e.g. re-testing for a demo), Kubernetes applies exponential backoff between restarts — CrashLoopBackOff — starting around 10s and doubling up to a 5-minute cap. If a restart seems to be taking longer than expected, check kubectl get pod <pod-name> for a CrashLoopBackOff status and rising RESTARTS count before assuming something's actually broken. Waiting it out, or deleting the pod outright (kubectl -n poc delete pod <pod-name>) to force a fresh backoff timer, resets this.

Example:

NAME READY STATUS RESTARTS AGE mod-foo-7f9559bb68-6nz2s 2/2 Running 0 15h mod-foo-7f9559bb68-lvz69 0/2 CrashLoopBackOff 7 (4s ago) 15h mod-foo-7f9559bb68-m5tsq 2/2 Running 2 (5d14h ago) 6d16h

4.6 Simulate a full pod crash (contrast with 4.5)

kubectl -n poc delete pod <pod-name>

Exercises Endpoints removal via actual pod deletion (Deployment/ReplicaSet creates a full replacement pod with a new IP) rather than just a readiness-probe failure on an existing pod.

Note: From what I’ve see pod replacement can happen pretty quickly. The loop to check the discovery info may need to be fairly tight to see this (e.g. sleep for 0.5s between iterations).


Conclusion

This PoC confirms that the Kubernetes Service Discovery functionality in Apache APISIX is compatible with Eureka’s architecture and will provide greater control over load balancing in Kubernete’s deployments.

Next Step: Once APISIX support is more complete in FOLIO (folio-apisix), engage Kitfox team to validate the approach in a real FOLIO environment (Rancher). See ____TBD____ (JIRA to be created).


Appendix A: Alternate Load-Balancing Strategies

Current config uses roundrobin. To switch (PUT to /apisix/admin/upstreams/mod-foo, keeping discovery_type/service_name/checks unchanged):

Type

Behavior

Config

Type

Behavior

Config

roundrobin (current)

Smooth weighted round-robin, even spread

"type": "roundrobin"

chash

Consistent hashing — same key always → same node (sticky routing)

"type": "chash", "hash_on": "header", "key": "x-client-id"

least_conn

Routes to node with fewest active connections

"type": "least_conn" (needs real concurrent load to observe difference)

ewma

Routes to node with lowest recent latency

"type": "ewma" (needs real concurrent load to observe difference)

Example request to change strategies:

curl http://127.0.0.1:9180/apisix/admin/upstreams/mod-foo \ -H "X-API-KEY: $APISIX_KEY" -XPUT -d ' { "type": "least_conn", "discovery_type": "kubernetes", "service_name": "poc/mod-foo-sidecar:http" }'

Appendix B: Troubleshooting / Gotchas Encountered

Symptom

Cause

Fix

Symptom

Cause

Fix

helm install fails: spec.externalTrafficPolicy: Invalid value: "Cluster"

externalTrafficPolicy: Cluster (chart default) is only valid for NodePort/LoadBalancer, but the values override service.type to ClusterIP

Explicitly set service.externalTrafficPolicy: "" alongside service.type: ClusterIP

curl .../v1/discovery/kubernetes/dump returns HTML 404 Not Found

Hit the Admin API port (9180) instead of the separate Control API port (9090) — different subsystem, no X-API-KEY needed

Port-forward/query port 9090 instead

helm upgrade fails: conflict ... field manager "kubectl-client-side-apply"

A ConfigMap was previously edited directly via kubectl apply, bypassing Helm, which claimed field ownership

helm upgrade ... --force, or delete the specific ConfigMap and let Helm recreate it

Load-balancing distribution looked skewed (e.g. one pod missing from early requests)

Test was run before a rollout/scale-out had fully settled — a newly-created pod hadn't yet become Ready/propagated into Endpoints

Confirm kubectl rollout status / all pods Ready before sampling; re-test with a larger sample (50-100+ requests)

Known simplification: sidecar health check scope

The real folio-module-sidecar implements a single health endpoint via a SmallRye Health aggregate of multiple independent @Readiness checks: Module reachability (an HTTP GET against the module's own health path, e.g. /admin/health) AND sidecar-internal state (e.g. Kafka connectivity). A RemoveChecksFilter strips the per-check breakdown before exposing the result, so externally the response is a simple {"status": "UP"}/"DOWN" — but internally there’s an AND across multiple checks.

This POC's sidecar /healthz only reproduces the module-reachability part (proxy_pass to the module's own /healthz). It does not simulate a "sidecar-internal-only" failure (e.g. Kafka down, module fine) as a distinct scenario, since plain nginx has no easy way to implement this logic without scripting. Given the scope of this PoC this simplification seemed like a reasonable choice.


Appendix C: Teardown

# APISIX + etcd helm uninstall apisix -n apisix kubectl delete clusterrolebinding apisix-discovery kubectl delete clusterrole apisix-discovery kubectl delete namespace apisix # Module/sidecar pods (optional — leave in place to iterate further) helm uninstall mod-foo -n poc helm uninstall mod-bar -n poc kubectl delete namespace poc

Check for any Released PersistentVolumes (PVs) left behind by etcd's PersistentVolumeClaim (PVC - kubectl get pv) — the chart's bundled etcd is documented as dev/test-only and may leave volumes depending on reclaim policy. If etcd's storage class uses Retain (or minikube's default), deleting the apisix namespace won't actually free that storage. In that case you'd see a Released PV lingering in kubectl get pv output, still consuming disk space on the node. Use kubectl delete pv <name> to actually reclaim it.


Appendix D: Reference Links