Skip to content

perf(server): skip IdleTrackingBackgroundService timer in stateless mode#1531

Open
MukundaKatta wants to merge 2 commits intomodelcontextprotocol:mainfrom
MukundaKatta:skip-idle-tracking-stateless
Open

perf(server): skip IdleTrackingBackgroundService timer in stateless mode#1531
MukundaKatta wants to merge 2 commits intomodelcontextprotocol:mainfrom
MukundaKatta:skip-idle-tracking-stateless

Conversation

@MukundaKatta
Copy link
Copy Markdown

Why

Closes #1515.

IdleTrackingBackgroundService runs a PeriodicTimer every 5 seconds to prune idle sessions and enforce MaxIdleSessionCount. In stateless mode (HttpServerTransportOptions.Stateless = true), the StatefulSessionManager is never populated — StreamableHttpSession returns early without storing the session — so there is nothing to prune.

Running the timer regardless wastes CPU on every server instance and clutters shutdown paths with a DisposeAllSessionsAsync that has nothing to dispose. With 1.2.0 leaning into stateless-by-default, this is wasted work on most servers.

What

  • Override BackgroundService.StartAsync to early-return Task.CompletedTask when _options.Value.Stateless is true. The timer loop in ExecuteAsync is never started, and the BackgroundService.ExecuteTask stays null. This was the fix proposed by the issue author and matches the architectural seam exactly: options have been bound by the time StartAsync runs, so we don't need to re-plumb DI.

Tested

  • Added two unit tests in HttpMcpServerBuilderExtensionsTests.cs:
    • IdleTrackingBackgroundService_DoesNotStartTimer_WhenStateless asserts ExecuteTask is null after StartAsync when Stateless = true.
    • IdleTrackingBackgroundService_StartsTimer_WhenStateful asserts the inverse for the default stateful mode.
  • Tests look the service up by type name from IServiceProvider.GetServices<IHostedService>() since IdleTrackingBackgroundService is internal sealed and the test project has no InternalsVisibleTo.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Can we avoid running IdleTrackingBackgroundService if HTTP Server transport is configured as stateless?

2 participants