Skip to content

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

Merged
halter73 merged 3 commits into
modelcontextprotocol:mainfrom
MukundaKatta:skip-idle-tracking-stateless
Jun 5, 2026
Merged

perf(server): skip IdleTrackingBackgroundService timer in stateless mode#1531
halter73 merged 3 commits into
modelcontextprotocol:mainfrom
MukundaKatta:skip-idle-tracking-stateless

Conversation

@MukundaKatta
Copy link
Copy Markdown
Contributor

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.

@halter73 halter73 merged commit a4157f3 into modelcontextprotocol:main Jun 5, 2026
10 checks passed
@halter73
Copy link
Copy Markdown
Contributor

halter73 commented Jun 5, 2026

Thanks!

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?

3 participants