Profiling kube-apiserver memory consumption and allocation churn in isolation is challenging: microbenchmarks only exercise a single function at a time, while full cluster e2e tests introduce external network jitter, node-agent background noise, and non-deterministic garbage collection timing.
TestAPIServerMemoryIntegration (cmd/kube-apiserver/app/testing/apiserver_mem_bench_test.go) is a self-contained, deterministic in-process kube-apiserver + embedded etcd3 integration benchmark designed to measure both steady-state retained heap memory (pprof inuse_space, HeapInuse, HeapObjects, process RSS) and cumulative request allocation churn (pprof alloc_space, TotalAlloc, Mallocs, NumGC) with zero external dependencies.
- Full In-Process Control-Plane Stack: Boots a real
kube-apiserverviaStartTestServerbacked by an embeddedetcd3server (etcd3testing.NewUnsecuredEtcd3TestClientServer), registering all built-in Kubernetes API groups, watch caches (cacher), admission plugins, and OpenAPI V2/V3 discovery services. - Byte-Exact Allocation Profiling (
runtime.MemProfileRate = 1andGOGC = 50): Settingruntime.MemProfileRate = 1before server startup instructs the Go runtime profiler to record every heap allocation (100%byte-exact sampling instead of the default512 KBstatistical sampling), whiledebug.SetGCPercent(50)enforces a consistent garbage collection target. - Repeated-Measures Aggregation (
N = 5Iterations, Trimmed Mean of Middle 3): Running 5 independent full-server iterations and computing the trimmed mean of the middle 3 iterations (dropping the highest and lowest run) filters out transient scheduling variance.
Each benchmark iteration executes five sequential phases inside the kube-apiserver process:
- Control-Plane Bootstrap and CEL Admission Seeding: Starts
kube-apiserverand creates 10ValidatingAdmissionPolicyobjects and 10ValidatingAdmissionPolicyBindingobjects targetingcore/v1ConfigMaps. Each policy compiles and evaluates a Common Expression Language (CEL) expression (has(object.metadata.name) && !object.metadata.name.startsWith('forbidden-i-') && object.metadata.name.matches('^[a-z0-9-]+$')), exercising CEL environment extension and regular expression evaluation on every write. - System ConfigMap Seeding (
60 x 20 KBObjects): Seeds 60 representativeConfigMapobjects inkube-system, each carrying a20 KBconfiguration payload (~1.25 MBper fullLISTresponse), standard control-plane labels and annotations, andManagedFields(FieldsV1) metadata. - Concurrent Multi-Worker Read/Write Load (
8 Workers x 8 Rounds = 64 Rounds): Spawns 8 concurrent client goroutines. In each of the 8 rounds, every worker executes:- 1 Protobuf
ConfigMapLIST(application/vnd.kubernetes.protobuf,~1.25 MBresponse, exercisingruntime.Allocatorand Protobuf marshaling/unmarshaling). - 1 JSON gzip-compressed
ConfigMapLIST(Accept: application/json,Accept-Encoding: gzip, exercising JSON serialization andresponsewriters). - 3 Protobuf
ConfigMapGETrequests and 3 JSONConfigMapGETrequests (exercisingcacher,etcd3decoding, and(*ConfigMap).Unmarshal). - 1
ConfigMapUPDATErequest with a unique per-workerFieldManager(triggering all 10 bound CELValidatingAdmissionPoliciesandManagedFieldsupdates).
- 1 Protobuf
- Concurrent OpenAPI V3 GroupVersion Discovery (
8 Workers x 2 Rounds x 3 Paths = 48 Requests): Exercises per-GroupVersion OpenAPI V3 discovery across/openapi/v3/api/v1,/openapi/v3/apis/apps/v1, and/openapi/v3/apis/admissionregistration.k8s.io/v1withAccept-Encoding: gzip. - Single Synchronous GC Cycle and In-Process Profile Capture: Runs a single synchronous
runtime.GC()anddebug.FreeOSMemory()cycle before dumpingapiserver_heap.pb.gz(pprof.WriteHeapProfile) and recordingruntime.MemStatsand/proc/self/status(VmRSS) intoapiserver_telemetry.json. Performing one GC cycle collects unreachable request garbage while preserving warmsync.Poolcaches, matching steady-state production behavior under continuous traffic.
From the root of a kubernetes/kubernetes checkout:
# 1. Download the benchmark test into cmd/kube-apiserver/app/testing/
curl -sL https://gist.githubusercontent.com/mauriciopoppe/508635e973bb8795cab2241c9a520edc/raw/apiserver_mem_bench_test.go \
-o cmd/kube-apiserver/app/testing/apiserver_mem_bench_test.go
# 2. Run on baseline (upstream/master)
RUN_APISERVER_MEM_BENCH=1 BENCH_OUT_DIR=/tmp/bench-before \
go test -v -count=1 -timeout=10m \
./cmd/kube-apiserver/app/testing \
-run=^TestAPIServerMemoryIntegration$
# 3. Switch to the target PR branch and run again
RUN_APISERVER_MEM_BENCH=1 BENCH_OUT_DIR=/tmp/bench-after \
go test -v -count=1 -timeout=10m \
./cmd/kube-apiserver/app/testing \
-run=^TestAPIServerMemoryIntegration$
# 4. Compare retained live heap (inuse_space) or cumulative allocations (alloc_space)
go tool pprof -text -inuse_space \
-base=/tmp/bench-before/apiserver_heap.pb.gz \
/tmp/bench-after/apiserver_heap.pb.gz
go tool pprof -text -alloc_space \
-base=/tmp/bench-before/apiserver_heap.pb.gz \
/tmp/bench-after/apiserver_heap.pb.gzUsing TestAPIServerMemoryIntegration as the evaluation harness across 95 candidate trials (v000 baseline through v095), 16 source-level optimizations reduced kube-apiserver memory consumption and allocation churn without degrading request latency:
| Metric (5-Iteration Trimmed Mean) | Baseline (v000) |
Optimized (v095) |
Delta |
|---|---|---|---|
Live Retained Heap (pprof inuse_space) |
79.95 MB |
42.57 MB |
-37.38 MB (-46.75%) |
Active Go Runtime Spans (HeapInuse) |
115.64 MB |
66.19 MB |
-49.45 MB (-42.76%) |
Span Fragmentation Overhead (HeapInuse - HeapAlloc) |
31.38 MB |
18.62 MB |
-12.76 MB (-40.66%) |
Live Heap Objects (HeapObjects) |
418,034 |
273,042 |
-144,992 (-34.68%) |
Cumulative Allocation Churn (TotalAlloc) |
1,026.70 MB |
696.67 MB |
-330.03 MB (-32.14%) |
Process Resident Set Size (VmRSS, Median) |
411.63 MB |
304.90 MB |
-106.73 MB (-25.93%) |
| Mean Per-Round API Latency | 159.87 ms |
135.27 ms |
-24.60 ms (-15.39%) |
Each pull request below was measured both in TestAPIServerMemoryIntegration and in isolation against upstream BenchmarkRequestCost (test/integration/apiserver/flowcontrol/cost/cost_test.go, n=6, with the memory lifecycle metrics added in kubernetes/kubernetes#143469):
| Pull Request | Component | Optimization Summary | Measured Impact in TestAPIServerMemoryIntegration |
Isolated Impact in BenchmarkRequestCost (cost_test.go, n=6) |
Status |
|---|---|---|---|---|---|
| kubernetes/kubernetes#142807 | k8s.io/apiserver (mux, endpoints) |
Share read-only pretty QueryParameter, cache AddObjectParams per reflect.Type, and drop PathRecorderMux.pathStacks map |
-2.17 MB retained heap (inuse_space), -2.51 MB HeapInuse, -12,941 live objects |
-3.04% heap-inuse-B (97.43 -> 94.47 MiB, -2.96 MiB), -2.81% heap-alloc-B, -2.23% runtime-inuse-B, -1.36% setup-alloc-B |
Open |
| kubernetes/kubernetes#142808 | pkg/printers/internalversion |
Hoist 68 []metav1.TableColumnDefinition slices in AddHandlers to package-level variables |
-1.44 MB retained heap in AddHandlers (-98.3%), -1.82 MB HeapInuse, -4,289 live objects |
-1.37% setup-alloc-B (161.9 -> 159.7 MiB, -2.2 MiB), -2.80% heap-alloc-B (-3.0 MiB), -2.81% heap-inuse-B (-4.9 MiB), -2.96% runtime-inuse-B |
Merged (2026-10-13) |
| kubernetes/kubernetes#142811 | k8s.io/apiserver/pkg/endpoints/handlers/responsewriters |
Pool deferredResponseWriter and its bytes.Buffer (512 KiB cap) via sync.Pool and remove dead req.WithContext(ctx) |
-23.66 MB cumulative TotalAlloc in deferredResponseWriter.Write, -80.27% to -81.71% Gzip Protobuf B/op (BenchmarkSerializeObject) |
-0.02% LIST N=100 rv=0 (json) B/op (-0.04% allocs/op), -7.75% DELETECOLLECTION N=100 sec/op (-1.51% suite sec/op geomean) |
Open |
| kubernetes/kubernetes#142814 | k8s.io/apimachinery/pkg/runtime |
Add (*Unknown).UnmarshalRawZeroCopy in types_proto.go so protobuf.Serializer.Decode avoids copying the inner Unknown.Raw envelope slice |
-113.66 MB cumulative TotalAlloc (-11.11%), -50.85% BenchmarkSerializerDecode B/op (-47.15% latency) |
-13.26% DELETECOLLECTION N=100 (protobuf) B/op (70.61 -> 61.25 MiB/op, -12.47% verified live on Prow PerfDash), -2.76% suite B/op geomean |
Merged (2026-10-30) |
| kubernetes/kube-openapi#655 | k8s.io/kube-openapi (builder, builder3) |
Replace reflect.DeepEqual boxing in WrapRefs with hasSiblingElements + copy-on-write walking and defer non-error json.Marshal in findCommonParameters |
4.27x faster BenchmarkWrapRefs (-63.5% B/op, -69.7% allocs/op), 1.44x faster builder3 spec build |
-7.22% setup-alloc-B (159.6 -> 148.1 MiB, -11.5 MiB), -6.24% heap-inuse-B (169.6 -> 159.0 MiB, -10.6 MiB), -5.21% runtime-inuse-B |
Open |
| kubernetes/kube-openapi#656 | k8s.io/kube-openapi (handler3) |
Gzip-compress cached OpenAPI V3 JSON specs in openAPIV3Group.jsonCache and serve pre-compressed bytes on Accept-Encoding: gzip |
-97.3% cached spec memory (604 KB -> 16 KB), 15.0x faster gzip serve latency, -5.51 MB net kube-apiserver live heap (3 GroupVersions) |
N/A (cost_test.go only queries /api/v1/.../pods and does not scrape /openapi/v3/...) |
Open |
| emicklei/go-restful#599 & kubernetes/kubernetes#142849 | github.com/emicklei/go-restful/v3 |
Cache compiled route path *regexp.Regexp state machines in newPathExpression and embed ParameterData by value inside Parameter (v3.14.0 bump in #142849) |
17.1x faster route registration (-95.4% B/op), -50% parameter allocs, -3.54 MB kube-apiserver live heap |
-6.26% setup-alloc-B (170.5 -> 159.8 MiB, -10.7 MiB), -6.43% heap-alloc-B (112.6 -> 105.4 MiB, -7.2 MiB), -4.78% heap-inuse-B (-8.5 MiB) |
Merged (2026-10-08 & 2026-10-16) |