Skip to content

vmcp: all VirtualMCPServer instances grow 2-3x in memory over ~24h regardless of client activity #5860

Open

Description

@RaviTharuma

Bug description

All VirtualMCPServer (vmcp) instances we run grow 2-3x in RSS memory over
roughly 24 hours, independent of client connection activity, eventually
threatening node memory headroom (this drove a node-wide OOM incident for
us). A prior working theory - that this was client-side reconnect churn -
is falsified by continued growth measured well after fixing that churn
cause on the client side.

Steps to reproduce

  1. Deploy 2+ VirtualMCPServer instances with different backend counts (we
    ran 4, with 12/13/14/19 backends respectively).
  2. Measure RSS via kubectl top pod at two points ~23h apart, with the
    deployments not restarted and no client-driven reconnect storms in
    between.
  3. Compare growth against the backend MCPServer/MCPRemoteProxy Deployments
    in the same namespace (control group) over the same window.

Expected behavior

Memory should stabilize/plateau. The control-group backend Deployments
show exactly this behavior (flat over the same 23h window).

Actual behavior

instance backends RSS T+0h RSS T+23h growth rate
A 19 476Mi 1476Mi 3.1x ~43 Mi/h
B 14 349Mi 683Mi 2.0x ~14.5 Mi/h
C 13 184Mi 446Mi 2.4x ~11.4 Mi/h
D 12 172Mi 343Mi 2.0x ~7.4 Mi/h

Growth rate scales roughly with backend count, consistent with a
per-backend resource retained per some recurring operation (health-check
tick, session-scoped init, etc.) rather than one fixed leak. A clean pod
restart drops each instance back to a ~35-100Mi baseline immediately.

Control group (same namespace, same 23h window, unrestarted): three
backend proxy Deployments stayed flat (264Mi / 249Mi / 175Mi at both
measurement points).

Environment

  • ToolHive operator + vmcp: v0.34.0
  • Single-node Kubernetes (Talos), 4 independent VirtualMCPServer instances

Additional context

  • Related but distinct: Proxyrunner memory grows monotonically under streamable-http session churn #4062 (closed) fixed a monotonic memory leak in
    thv-proxyrunner under streamable-http session churn - that's the
    individual-backend-proxy component. Our observation is in the
    vmcp/VirtualMCPServer aggregator process itself; our control-group
    backend proxy pods stayed flat over the same window, so this does not
    look like the same code path re-surfacing.
  • We have not isolated which internal resource is growing (no profiling
    access in this deployment). Happy to gather a pprof heap profile across
    a multi-hour window if vmcp exposes one, or to test against specific
    config knobs if pointed at likely candidates.

Activity

  1. added
    needs-triage
    on Jul 17, 2026
  2. ChrisJBurns commented on Jul 30, 2026

    @ChrisJBurns
    Collaborator

    Thanks for the detailed report, @RaviTharuma. The flat control group is a useful control, and growth scaling with backend count does point at something retained per backend on a recurring operation rather than a single fixed leak.

    One correction on your profiling offer: vmcp does not expose a pprof endpoint today, so there is no heap profile for you to collect. Three things would help more:

    • Can you enable telemetry on these VirtualMCPServer resources and share the Go runtime memory series over a few hours? The operator supports a Prometheus metrics endpoint via the telemetry config, which would give us a real growth curve rather than two RSS samples.
    • Does an instance that never has a client session established still grow? That would separate background health-monitor work from session-scoped retention.
    • What is healthCheckInterval set to on these instances, or are they on compiled-in defaults? If you can raise it substantially on one instance, does the Mi/h rate fall roughly in proportion?

    Once we have that we can take a proper look. Leaving this open in the meantime.

  3. added
    needs_more_info
    on Jul 30, 2026
  4. removed
    needs-triage
    on Aug 10, 2026
  5. RaviTharuma commented on Aug 10, 2026

    @RaviTharuma
    ContributorAuthor

    Follow-up (still open on v0.42.1)

    Updating the original report with current environment. No credentials or private hostnames included.

    Environment (now)

    • ToolHive operator + vmcp image: v0.42.1 (was v0.34.0 when filed)
    • Four VirtualMCPServer instances, backend counts 12 / 13 / 17 / 17
    • Single-node Kubernetes (Talos)
    • Still using an out-of-band daily pod restart CronJob as mitigation (not a fix)

    Current RSS sample (kubectl top pod, ~2.5h after last nightly restart)

    instance backends RSS (approx)
    A 17 ~106 Mi
    B 17 ~53 Mi
    C 12 ~30 Mi
    D 13 ~32 Mi

    We have not re-run a full 23h pair of samples on v0.42.1 yet; the original table still stands as the multi-hour growth evidence. If growth continues on 0.42.1 we will post a second 23h table.

    Answers to your questions (2026-07-30)

    1. Telemetry / Prometheus path: we are enabling spec.config.telemetry.enablePrometheusMetricsPath: true on these VirtualMCPServers so Go runtime metrics are available for a multi-hour series. Will share series once scraped (no private labels).
    2. No-client growth: not re-tested since the original report; original control was “no client reconnect storms” while instances still grew. We can try a dedicated idle instance if helpful.
    3. healthCheckInterval: not set on our CRs (compiled-in defaults). Happy to raise it on one instance once we know the field path / default value.

    Still happy to help isolate this. Thanks for the earlier guidance.

  6. RaviTharuma commented on Aug 10, 2026

    @RaviTharuma
    ContributorAuthor

    Follow-up: why telemetry was not scrapable (v0.42.1)

    We enabled what the CRD documents as:

    spec:
      config:
        telemetry:
          enablePrometheusMetricsPath: true

    Observed:

    • VirtualMCPServer CR stored the field
    • Operator-rendered ConfigMap (*-vmcp-config) had no telemetry: block
    • GET /metrics with Accept: text/plain / */* / openmetrics → HTTP 406 JSON-RPC:
      Not Acceptable: Client must accept text/event-stream
    • GET /health → 200 {"status":"ok"} (health is registered; metrics is not)

    Cause: operator converter only honors spec.telemetryConfigRef →
    MCPTelemetryConfig. Inline spec.config.telemetry was a silent no-op after #4819,
    while docs still suggested the inline path. Full write-up: #6276. Fix PR:
    restores deprecated inline fallback + documents preferred MCPTelemetryConfig.

    Workaround (works on v0.42.1 without a new operator):

    apiVersion: toolhive.stacklok.dev/v1beta1
    kind: MCPTelemetryConfig
    metadata:
      name: vmcp-prometheus
    spec:
      prometheus:
        enabled: true
    ---
    # on each VirtualMCPServer:
    spec:
      telemetryConfigRef:
        name: vmcp-prometheus
        serviceName: <unique-per-server>

    Once scrape works we will post a multi-hour go_* / process memory series
    (no private labels). Still happy to raise healthCheckInterval on one idle
    instance if you can confirm the field path defaults (compiled-in default appears
    to be 30s under config.operational.failureHandling.healthCheckInterval).

    No credentials or private hostnames in this comment.

  7. RaviTharuma commented on Aug 15, 2026

    @RaviTharuma
    ContributorAuthor

    Follow-up on v0.43.0 (29h sample)

    Environment now: operator + vmcp v0.43.0. Nightly restart CronJob has been removed.

    kubectl top pod ~29h after the last operator/proxy bounce (2026-08-14 ~16:37 UTC):

    instance backends RSS limit
    A (largest tenant) 11 118 Mi 3 Gi
    B 11 69 Mi 768 Mi
    C 6 35 Mi 768 Mi
    D 5 27 Mi 768 Mi

    This is not a 23h growth pair, so it does not clear or confirm the original leak. It does show that after ~29h on 0.43.0 we are not in the 1+ Gi crisis from the original report. Still happy to post a real go_* series once scrape is stable via MCPTelemetryConfig (#6276).

    Related operational gaps that make mitigation ugly, filed separately:

    No credentials or private hostnames.

  8. alex-feel commented on Sep 24, 2026

    @alex-feel
    Contributor

    On the 2026-07-30 question: on v0.47.1 our instances stay flat without client sessions and grow as clients open them. Two VirtualMCPServers, two backends each, default 30 s health checks (each lists a backend's tools, resources and prompts); cAdvisor working set, no Go metrics scraped.

    • Weekends with no sessions: net change within ~25 MiB a day; one aggregate held 438 MiB through a 14-hour idle night.
    • Working days: the aggregate over a ~6,200-resource backend accumulated 0.8-1.3 GiB a day across restarts and was OOM-killed at the 512Mi default limit 21 times in 2026-09-14..22. With that backend's resources turned off it stayed at 55-66 MiB over 42 sessions; the other aggregate (848 resources) went from 48 to 268 MiB over 56 sessions, ~3.9 MiB a session, ~4.7 KiB per resource.
    • Clients never DELETE: 121 sessions, 0 DELETE, 2026-09-22 17:36 to 09-24 07:49 UTC.

    Sessions get no resources injected (resource_count 0 on every injection log line; authz permits tool calls only), yet the cost tracks the backends' resource count. In v0.47.1 makeBaseSession keeps each backend's raw tools, resources and prompts per session, and the session cache evicts an entry only when a later lookup finds it expired or the 1000-entry LRU fills. Nothing looked those entries up here (no eviction, health change or backend removal logged), and v0.51.1 adds no idle eviction. #6667 prunes the resync registry at the health-change fan-out, which already evicts the expired sessions it looks up, so I don't expect it to change these curves. If it closes this issue I can open one for the session cache; hourly series and log counts are available.

  9. RaviTharuma commented on Sep 25, 2026

    @RaviTharuma
    ContributorAuthor

    @alex-feel thanks — this is exactly the signal we were missing.

    Your v0.47.1 picture (flat idle weekends, growth tied to client sessions / large resource backends, ~0.8–1.3 GiB/day on the ~6,200-resource case with default 30s health listing tools/resources/prompts) matches a session- or catalog-retained path much better than a pure idle leak.

    I will dig next on: (1) whether health-check tool/resource/prompt listing retains catalogs across ticks, (2) session teardown vs open-client growth, and (3) whether Go/pprof heap deltas line up with the cAdvisor working-set curve. Will report back with a redacted repro recipe once I have a tight loop.

  10. RaviTharuma commented on Oct 2, 2026

    @RaviTharuma
    ContributorAuthor

    @ChrisJBurns @alex-feel — alex-feel's v0.47.1 data (flat idle weekends; growth tied to client sessions / large resource catalogs; clients never DELETE) looks like a strong session-cache / catalog-retention signal rather than a pure idle leak.

    If that framing is enough to drop needs_more_info, I am happy to take a focused follow-up PR for idle session-cache eviction (or whatever direction you prefer). Otherwise, please say what remaining measurement you still need and I will prioritize that.

  11. alex-feel commented on Oct 6, 2026

    @alex-feel
    Contributor

    @RaviTharuma one layer of this already has a PR: stacklok/toolhive-core#306 (for stacklok/toolhive-core#305) adds an opt-in WithSessionIdleTimeout to the mcpcompat shim, which closes and drops sessions whose clients never send DELETE. It is open and waiting for review. The vmcp would still need to pass its session TTL to it. That covers only the shim's own session map; the vmcp's per-session state on top of it is a separate matter, so a session-cache eviction PR on the vmcp side would not duplicate that PR. On main, the vmcp's node-local session cache (ValidatingCache in pkg/cache) drops an entry only when that session is read again and found expired, when LRU capacity pushes it out, or when its backend is removed; nothing sweeps idle entries. The makeBaseSession and session-cache reading I posted above comes from reading the source. I have not taken a heap profile, so I have not confirmed where that memory sits.

  12. RaviTharuma commented on Oct 7, 2026

    @RaviTharuma
    ContributorAuthor

    @alex-feel thanks, that split is really helpful. So toolhive-core#306 covers the shim's own session map (once vmcp passes its session TTL into WithSessionIdleTimeout), and the vmcp side still has nothing that sweeps idle ValidatingCache entries in pkg/cache, since they only go on re-read, LRU pressure, or backend removal.

    If maintainers are fine with that direction, I'd scope a vmcp follow-up to (1) a periodic idle sweep of the node-local session cache and (2) passing the session TTL through to the shim after #306 lands, so it complements that PR instead of duplicating it. @ChrisJBurns does that work for you, or would you rather see a heap profile first?

  13. hellouz818 commented on Oct 12, 2026

    @hellouz818
    Contributor

    @RaviTharuma, following @alex-feel's suggestion on #6762, I'd like to confirm the scope split with your proposed follow-up.

    My proposed fix is limited to explicitly terminated sessions: adding ValidatingCache.Remove(key) and calling it from Terminate() after deleting the storage record, so the local backend connections are closed immediately.

    The periodic sweep of cache entries whose storage records have expired (including sessions abandoned without DELETE), as well as passing the session TTL to the mcpcompat shim, would remain in your proposed follow-up here.

    Since both changes touch ValidatingCache, I'm happy to coordinate on the API surface so they don't conflict. Does that scope split match your plan?

  14. JAORMX commented on Oct 12, 2026

    @JAORMX
    Collaborator

    @RaviTharuma @alex-feel @hellouz818, I dug through the current code and the earlier cache changes to double-check this. The scope split makes sense: @hellouz818 is assigned the explicit-termination fix in #6762, while abandoned-session cleanup stays separate here. Thanks for connecting the two reports and for the workload measurements.

    There is some history worth bringing back into the discussion. #4727 called for removing imperative cache deletion and adding a background sweep. The reapplication in #4731 removed the eager cleanup, but the replacement sweep did not land, despite the issue being closed as implemented. So we left a gap between removing one cleanup path and adding the other. That explains why this is coming up again.

    The biggest implementation trap is that our current liveness checks renew the session TTL. checkSession calls DataStorage.Load: Redis uses GETEX, and local storage refreshes its last-access timestamp. A periodic sweep through that path could keep abandoned sessions alive indefinitely. Going through cache Get is also unsuitable, since a miss can restore a session and open backend connections.

    We already have a non-renewing LoadMetadata operation on the ordinary transport Storage interface, so there is a precedent to follow. vMCP uses the separate DataStorage interface, which does not expose an equivalent operation. We should also define what a non-renewing read means for local entries that are past their TTL but have not yet been removed by the storage cleanup worker.

    There is a cache-locking detail to account for too: RemoveMatching currently evaluates its predicate under the cache mutex. We should not put Redis calls there. An off-lock check needs to remove only the entry it inspected, without accidentally deleting a replacement inserted while the check was running. That requires coordinating with the cache-miss insertion path as well.

    On the shim side, stacklok/toolhive-core#306 has landed and is already included in our pinned core v0.0.51. vMCP does not enable its idle timeout yet. Note that this timeout measures POST inactivity on one replica: an in-flight POST pauses it, but an open GET stream does not keep it alive. Shared metadata can therefore remain valid after the local shim session is closed. Our current lazy reinjection covers tools, so I would want coverage for resources/prompts and notification bindings when a session is rehydrated before treating TTL wiring as a complete fix.

    So, I would start by making the intended guarantee explicit: reclaim local cached objects once their authoritative metadata has expired or been deleted, without refreshing that metadata or treating a temporary storage error as expiry. Evicting a locally idle copy while another replica still uses the session is a different policy, and we should not mix the two accidentally.

    None of this needs to hold up the focused DELETE fix. For this follow-up, cache/connection counts and before-and-after heap profiles would help us distinguish backend-session retention from shim and resync-worker retention; RSS alone cannot tell us which objects were reclaimed.

    @RaviTharuma, are you still interested in taking this on, and does metadata-expiry-based cleanup match the scope you had in mind?

  15. RaviTharuma commented on Oct 15, 2026

    @RaviTharuma
    ContributorAuthor

    @hellouz818 @JAORMX yes — that scope split matches my plan.

    Happy to align on the ValidatingCache API surface so the Remove path and the sweep do not fight. The #4727 / #4731 history (eager cleanup removed, replacement sweep never landed) is exactly the gap I want the follow-up to close.

  16. JAORMX commented on Oct 15, 2026

    @JAORMX
    Collaborator

    Thanks @RaviTharuma! I’ve assigned this to you. The DELETE fix has now landed in #6807, so please build on current main for the metadata-expiry sweep.

    Let’s keep shim timeout wiring in a separate PR because of the replica-local expiry and rehydration concerns from my earlier comment. Otherwise, we’re aligned on the scope.

  17. alex-feel commented on Oct 23, 2026

    @alex-feel
    Contributor

    @RaviTharuma a point for the sweep design, read at main 7970d58: a sweep that reclaims cache entries through the existing eviction path leaves the session's health-resync worker registered. healthResyncRegistry (pkg/vmcp/server/serve_health_resync.go:51) loses an entry only on registration failure (server.go:1350), binding failure (serve_handlers.go:570), DELETE via pruneOnTerminateSessionIDManager (serve_health_resync.go:63-74), or a triggered worker finding the session gone (serve_list_changed.go:219-220); the cache's eviction closure (sessionmanager/session_manager.go:161-173) only closes the session, and nothing under pkg/cache or sessionmanager references the registry. That lazy prune runs only inside the health fan-out, which fires only on an advertisability flip or a backend-set change (health/monitor.go:552, :463), so with healthy, unchanging backends a swept session's worker closure (shim ClientSession, registration-time identity and forwarded headers) stays until restart, as the comments at serve_health_resync.go:44-50 and server.go:1408-1414 note. Today the shim's own session map holds that ClientSession anyway until DELETE; once the idle timeout is wired, the registry entry would be the last reference to it. Calling healthResync.remove from the sweep, or from the eviction closure, closes the gap. Whether this holds any of the measured growth I have not confirmed; no heap profile.

  18. alex-feel commented on Nov 16, 2026

    @alex-feel
    Contributor

    A data point from v0.63.0: the 848-resource aggregate from my earlier numbers grew to its 2 GiB memory limit and was OOM-killed about three days after a restart. #6932 reports per-session growth surviving DELETE on v0.55.2, which may matter for the sweep's scope.

    @RaviTharuma, is the metadata-expiry sweep still planned on your side, or would it help if I took it over?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

needs_more_info

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions