Skip to content

MongoDB Replicaset support - #16698

Closed
Artiom Chilaru (artiomchi) wants to merge 9 commits into
microsoft:mainfrom
artiomchi:feat/add-mongodb-replicaset-support
Closed

Artiom Chilaru (artiomchi) wants to merge 9 commits into
microsoft:mainfrom
artiomchi:feat/add-mongodb-replicaset-support

Conversation

@artiomchi

@artiomchi Artiom Chilaru (artiomchi) commented May 2, 2026 •

Copy link
Copy Markdown

Description

This PR modifies the MongoDB Builder to add support for building a single node replica set. This will allow applications using transactions or change streams to use MongoDB in Aspire.

I'm using the same approach as I used when building the Testcontainers.MongoDb library. Instead of building a separate container in a dockerfile, the standard mongo container is used. To start as a replicaset, a keyfile is generated and added to to the container. The healthcheck is used to ensure the replicaset is initialised on server startup. This keeps the implementation clean and doesn't require an additional dockerfile.

  • New WithReplicaSet() Extension Method on the builder
    • Configures Mongo to run as a single node replica set
    • Generates a new keyfile and stores it as a secret parameter
  • New Mongo health check
    • Falls back to simple connection checks for non replica sets
    • Ensures replSetInitiate command runs
    • Verifies primary node election
  • MongoDBServer resource updates
    • Adds ReplicaSetName property
    • Updates connection string to include directConnection=true parameter when replica set is enabled

Fixes #5238

Decision points

New health check

The new health check replaces the simple original health check and will only return healthy once the replica set is initialised. It is also used to call the rs.initiate() call in Mongo to initialise the replicaset.

Alternatives considered:

  • OnResourceReady callback fires after the health check passes - this would mark the resource as healthy before the replica set is ready
  • docker-entrypoint-initdb.d - tried in the past, this won't work as that script runs against a standalone mongod instance, and won't affect the main instance
  • Separate health check - this would require the main health check to pass, and would send conflicting signals
  • Additional resource that initialises the replicaset once the server is ready, then referencing that in applications - works, provides visibility in the dashboard that the replicaset is initialised separately, but adds unnecessary complexity to configuratio for the users in the AppHost, as well as in the dashboard. Doesn't bring any tangible value

Direct connection in connection string

Specifying the replicaset name in the connection string is explicitly discouraged by the MongoDB driver configuration, and can cause behavioural conflicts. Specifying directConnection=true in the connection string tells the MongoDB driver to connect directly to the specified host bypassing topology discovery. Since we only have a single node, this is more than enough. Additionally, the topology discovery would return the internal host address within the container, which wouldn't be accessible by the application.

Note

There may be an issue in Mongo 8.0 - 8.2 that causes Mongo to crash every ~30 seconds if replica set is initiated. Seems to be a compatibility issue with certain linux kernels. Switching to older Mongo versions (7.0) seems to completely bypass the issue. Not related to this PR or Aspire, purely a MongoDB regression.

ref:
bluewave-labs/Checkmate#3444
https://www.mongodb.com/community/forums/t/mongodb-8-x-and-linux-kernel-6-19/337547
stoatchat/self-hosted#268

Checklist

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes
      • If yes, did you have an API Review for it?
        • Yes
        • No
      • Did you add <remarks /> and <code /> elements on your triple slash comments?
        • Yes
        • No
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
      • If yes, have you done a threat model and had a security review?
        • Yes
        • No
    • No
  • Does the change require an update in our Aspire docs?

@github-actions

github-actions Bot commented May 2, 2026 •

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 16698

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 16698"

Minor cleanup
@artiomchi
Artiom Chilaru (artiomchi) force-pushed the feat/add-mongodb-replicaset-support branch from 66c95f0 to 67db131 Compare May 2, 2026 16:57
@artiomchi
Artiom Chilaru (artiomchi) marked this pull request as ready for review May 2, 2026 16:58
Copilot AI balanced review requested due to automatic review settings May 2, 2026 16:58

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds single-node replica set support for hosted MongoDB resources so transaction-dependent scenarios can run against the Aspire MongoDB container, and introduces tests for the new API and connection string behavior.

Changes:

  • Add WithReplicaSet(...) to configure MongoDB as a single-node replica set and expose ReplicaSetName.
  • Replace the default MongoDB health check with a custom health check that initializes the replica set and waits for primary election.
  • Add functional and unit tests covering the new API, container args, and connection string updates.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tests/Aspire.Hosting.MongoDB.Tests/MongoDbFunctionalTests.cs Adds a functional test that verifies transactions succeed against a replica-set-enabled MongoDB resource.
tests/Aspire.Hosting.MongoDB.Tests/MongoDBPublicApiTests.cs Adds public API validation tests for WithReplicaSet and ReplicaSetName.
tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs Adds unit tests for replica set defaults, args, annotations, and connection string behavior.
src/Aspire.Hosting.MongoDB/api/Aspire.Hosting.MongoDB.cs Updates the shipped public API surface with WithReplicaSet and ReplicaSetName.
src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs Extends the resource model and connection string generation for replica set mode.
src/Aspire.Hosting.MongoDB/MongoDBServerHealthCheck.cs Introduces a custom health check that initializes the replica set and checks primary readiness.
src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs Registers the new health check and implements WithReplicaSet.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.

/// <param name="replicaSetName">The name of the replica set. Defaults to <c>rs0</c>.</param>
/// <returns>The <see cref="IResourceBuilder{T}"/>.</returns>
[AspireExport(Description = "Configures the MongoDB container to start as a single-node replica set")]
public static IResourceBuilder<MongoDBServerResource> WithReplicaSet(this IResourceBuilder<MongoDBServerResource> builder, string replicaSetName = "rs0")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My concern is that this design does not allow to extend this feature beyond single-node replica sets.
In my opinion, having a replica set as a separate resource is a better option.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this needed though, for a local development database? This shouldn't be used to deploy a resilient production level database, that would require an entirely different ballgame

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Artiom Chilaru (@artiomchi) Why would that require an entirely different ballgame though? I would agree with fedarovich that we should support this scenario.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the use-case for spinning a multi-node replica set in a local aspire host though?

For local development, the reason to have a replica set is to be able to use transactions in your application. Whether this is running in a single node or multiple - the end result will be the same.

And this would never be used in a production deployment.

Right now Aspire doesn't support this at all. And had 2 PRs rejected with previous implementations. This approach adds the replica set support with minimal changes, no side-effects, simple configuration and transparent usage for the users. And doing it without adding unnecessary complexity.

Changing this to deploy a replica set in a separate resource would mean a more complex configuration for the users. It would also mean they need a different way to get the connection string, as well as depending on the replica set resource instead of the database resource, when building their app host. So now you need to configure your app host dependencies differently depending on whether your mongo instance is a replica set or not.

This can be done, but I just don't see the purpose. Or any reason to overcomplicate the API and diminish the user experience without getting anything tangible in return

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P.S. If you think I'm wrong on this, I would genuinely want to know that and I'm happy to reconsider.

@aradalvand Arad Alvand (aradalvand) Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am actually currently working on a PR that achieves what yours achieves while treating the replica set as its own "logical" resource, thereby enabling multi-node replica sets. I'll ping you once it's ready and you tell me what you think of the approach.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True, but in a cloud environment it would deploy a managed cloud database resource. i.e. in the link you provided, it would deploy a Relational Database Service in AWS or Database for Postgres in Azure. Both are managed resources that are already pre-configured for reliability, uptime, monitoring, resilience and security by DB specialists.

Deploying a stateless application is one thing, but you wouldn't just deploy a database in production in a docker/k8s container from Aspire like that. You need storage configuration, node affinity, networking configuration, backups, credential/key rotation, updates, monitoring and SO much more. So yes, for Aspire I don't see the Mongo component as a production ready deployable resource - in prod it would use a managed MongoDB cloud resource, not a Docker container

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am actually currently working on a PR that achieves what yours achieves while treating the replica set as its own "logical" resource, thereby enabling multi-node replica sets. I'll ping you once it's ready and you tell me what you think of the approach.

I've had something like that implemented in the first iterations of this implementation. It worked (with a couple small caveats), but in the end it just added unnecessary complexity, and didn't really bring any benefits.

But I'm happy to check it out and share my thoughts on it once it's done!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Soo.. What happened as part of your PR? I saw you going through it for a while.. but in the end - you closed it? Why was it closed, and what happens next?

@aradalvand Arad Alvand (aradalvand) Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Artiom Chilaru (@artiomchi) I closed it accidentally; I just reopened it.
It's near complete; only some final touches left: #18196

@artiomchi

Copy link
Copy Markdown
Author

David Fowler (@davidfowl) I noticed the previous PRs that tried to implement this feature were eventually closed, as they needed some internal Aspire refactoring/features.. This one uses a different (and much simpler) approach, and shouldn't be blocked by anything though.

Happy to help in any way to get this reviewed and moved across

@radical Ankit Jain (radical) added area-integrations Issues pertaining to Aspire Integrations packages mongodb Issues related to mongodb integrations labels Jun 25, 2026
@artiomchi

Copy link
Copy Markdown
Author

Mitch Denny (@mitchdenny) David Negstad (@danegsta) Is there any chance this PR could get some eyes on it? It's a simple enough change, can be improved with publish/deployment support in the future (if that's even needed), but would do a LOT to help with local dev experience, and wouldn't detract from any of the existing functionality.

I'm very eager to get any form of replicaset support added to Aspire, and would like to help make it happen. Please just let us know how we can help.

Copilot AI review requested due to automatic review settings August 11, 2026 21:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Suppressed comments (6)

tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:308

  • ContainerFileSystemCallbackContext.Services is required. Assigning the obsolete ServiceProvider alias does not satisfy required-member initialization, so this test does not compile (CS9035) and also uses an obsolete API.
            new() { Model = mongo.Resource, ServiceProvider = app.Services },

tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:353

  • This test is marked async but contains no await, producing CS1998. Make it synchronous so the test project remains warning-free.
    public async Task WithReplicaSetDatabaseConnectionStringIncludesDirectConnection()

src/Aspire.Hosting.MongoDB/api/Aspire.Hosting.MongoDB.cs:43

  • This file is explicitly auto-generated (lines 2–6), and repository convention keeps these API baseline files unchanged in feature PRs because edits can alter the compatibility baseline and are overwritten by regeneration. Revert all additions in this generated file; the release process regenerates API baselines.
        [AspireExport("withReplicaSet", Description = "Configures the MongoDB container to start as a single-node replica set")]
        public static ApplicationModel.IResourceBuilder<ApplicationModel.MongoDBServerResource> WithReplicaSet(this ApplicationModel.IResourceBuilder<ApplicationModel.MongoDBServerResource> builder, string replicaSetName = "rs0") { throw null; }

src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:288

  • This public method explicitly throws three exception types, but its XML documentation omits them. Documenting these exceptions is required for public Aspire APIs so IntelliSense accurately describes the contract.
    /// <param name="builder">The resource builder.</param>
    /// <param name="replicaSetName">The name of the replica set. Defaults to <c>rs0</c>.</param>
    /// <returns>The <see cref="IResourceBuilder{T}"/>.</returns>

src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:142

  • Appending directConnection=true makes the public UriExpression remarks inaccurate: they still document only the optional authentication query segment. Update that format documentation to include the replica-set direct-connection query parameter.
        if (ReplicaSetName is not null)
        {
            builder.AppendLiteral(PasswordParameter is not null ? "&" : "?");
            builder.AppendLiteral("directConnection=true");
        }

tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:321

  • This test is marked async but contains no await, producing CS1998. Make it synchronous so the test project remains warning-free.

This issue also appears on line 353 of the same file.

    public async Task WithReplicaSetServerConnectionStringIncludesDirectConnectionWithAuth()

Copilot AI review requested due to automatic review settings August 11, 2026 22:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

Suppressed comments (13)

src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:295

  • The new public method also throws for a null builder/name, an empty name, and duplicate replica-set configuration, but only publish mode is documented. Add the missing exception contracts so IntelliSense matches the validated behavior.
    /// <exception cref="NotSupportedException">Thrown if called while publishing.</exception>

tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:362

  • This test is marked async but contains no await, producing CS1998 and unnecessary state-machine semantics. Make it synchronous.
    public async Task WithReplicaSetDatabaseConnectionStringIncludesDirectConnection()

src/Aspire.Hosting.MongoDB/api/Aspire.Hosting.MongoDB.cs:43

  • This generated API baseline should not be updated in an individual feature PR. Keeping these edits bypasses the repository's release-time API generation workflow; revert all additions in this api/*.cs file and let the release process regenerate it.
        public static ApplicationModel.IResourceBuilder<ApplicationModel.MongoDBServerResource> WithReplicaSet(this ApplicationModel.IResourceBuilder<ApplicationModel.MongoDBServerResource> builder, string replicaSetName = "rs0") { throw null; }

src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:71

  • KeyFileContentParameter exposes an implementation-only replica-set authentication credential as permanent public API. The only production consumer is the container-file callback in this assembly, so this unnecessarily expands the public and secret-bearing surface; keep it internal unless there is a concrete external customization scenario.
    public ParameterResource? KeyFileContentParameter { get; internal set; }

src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:69

  • The remarks claim this parameter is emitted during publish, but WithReplicaSet always throws in publish mode, so this documented behavior is unreachable. Remove the publish-mode statement so IntelliSense describes the actual API contract.
    /// The value is generated as a high-entropy secret on first use and persisted to the AppHost's user secrets store
    /// in run mode, so it remains stable across runs of the same AppHost. In publish mode the parameter is emitted to
    /// the manifest with a <c>generate</c> directive.

src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:141

  • Appending directConnection=true changes the documented URI format, but the public UriExpression remarks above still describe only the authentication query parameters. Update that format documentation to include the optional direct-connection query parameter for replica-set resources.
        if (ReplicaSetName is not null)
        {
            builder.AppendLiteral(PasswordParameter is not null ? "&" : "?");
            builder.AppendLiteral("directConnection=true");

src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:176

  • The new DirectConnection structured connection property is not exercised by the added tests; they only inspect ConnectionStringExpression. Add a replica-set case to ConnectionPropertiesTests that verifies the key/value and its propagation to database connection properties, otherwise this consumer-facing contract can regress independently of the URI tests.
        if (ReplicaSetName is not null)
        {
            yield return new("DirectConnection", ReferenceExpression.Create($"true"));

tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:330

  • This test is marked async but contains no await, producing CS1998 and unnecessary state-machine semantics. Make it synchronous.

This issue also appears on line 362 of the same file.

    public async Task WithReplicaSetServerConnectionStringIncludesDirectConnectionWithAuth()

tests/Aspire.Hosting.MongoDB.Tests/MongoDbFunctionalTests.cs:451

  • CancellationTokenSource owns a timer and is not disposed, so the timer can remain rooted after the test finishes. Dispose it with the test scope.
        var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));

tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:358

  • These partial positive/negative checks can pass for other malformed connection strings and use the repository-discouraged Assert.DoesNotContain pattern. Assert the complete expression so the separator and full URI shape are covered.
        Assert.Contains("?directConnection=true", mongo.Resource.ConnectionStringExpression.ValueExpression);
        Assert.DoesNotContain("&directConnection=true", mongo.Resource.ConnectionStringExpression.ValueExpression);

tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:375

  • Checking only for the new token does not verify that it is placed in the database URI's query string correctly. Follow the exact connection-string assertions used elsewhere in this file so malformed ordering or separators fail this regression test.
        Assert.Contains("directConnection=true", dbResource.ConnectionStringExpression.ValueExpression);

tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:384

  • This absence-only assertion is explicitly discouraged in this test suite because it does not verify the connection string that is produced. Assert the complete standalone URI instead.
        Assert.DoesNotContain("directConnection", mongo.Resource.ConnectionStringExpression.ValueExpression);

src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:290

  • This new public fluent extension lacks the usage example required for Aspire extension APIs. Add an <example> with a <code> block showing AddMongoDB(...).WithReplicaSet() so the generated API documentation demonstrates the supported run-mode usage.

This issue also appears on line 295 of the same file.

    /// This method is only supported when running the AppHost (F5/<c>aspire run</c>). The manifest publisher
    /// serializes the <c>--keyFile</c> argument without invoking the container file callback that writes the
    /// keyfile, so publishing would produce a container that references a keyfile that never gets created.
    /// </para>
    /// </remarks>

Copilot AI review requested due to automatic review settings August 11, 2026 22:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

Suppressed comments (4)

src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:127

  • Appending directConnection=true makes the public URI documentation inaccurate: MongoDBServerResource.UriExpression and MongoDBDatabaseResource.UriExpression still say query segments are present only when a password is configured and omit the replica-set option. Update both XML comments so generated documentation describes replica-set connection strings.
        if (ReplicaSetName is not null)

src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:294

  • This new public fluent extension has no <example>/<code> usage block, leaving the published API documentation incomplete. Add a minimal AddMongoDB(...).WithReplicaSet(...) example.
    public static IResourceBuilder<MongoDBServerResource> WithReplicaSet(this IResourceBuilder<MongoDBServerResource> builder, string replicaSetName = "rs0")

src/Aspire.Hosting.MongoDB/MongoDBServerHealthCheck.cs:36

  • This server-state check specifically fixes reinitialization after a container is recreated, but the new functional test only initializes a fresh container once. Add a restart/recreation regression test that first reaches healthy, recreates the MongoDB container without its prior replica-set configuration, and verifies the health check initializes it again; otherwise the previously identified stale-state failure can regress unnoticed.
                // The server is the source of truth for replica set state. A node started with
                // --replSet that has not had replSetInitiate run reports no `setName` in `hello`;
                // the same is true after a container is recreated and its prior config is gone.
                if (!hello.Contains("setName"))

src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:296

  • The XML documentation omits the exceptions thrown when builder is null or replicaSetName is null/empty. Document both validation failures so IntelliSense accurately describes this public API.
    /// <exception cref="NotSupportedException">Thrown if called while publishing.</exception>
    /// <exception cref="InvalidOperationException">Thrown if a replica set has already been configured for the resource.</exception>

@ggirard07

Copy link
Copy Markdown

Artiom Chilaru (@artiomchi) Not sure what is the exact intent of CommunityToolkit/Aspire, but do you think there is perhaps a better chance to land your simplified version there first?

@artiomchi

Copy link
Copy Markdown
Author

ggirard07 (@ggirard07) thing is, there are already a couple third party external packages that add replicaset support. The idea is to add this as a first party solution directly into Aspire, avoiding having to import a third party package that you have to trust in your environment.

@artiomchi

Copy link
Copy Markdown
Author

Duplicate of #19961

The new PR superseeds this one

@artiomchi
Artiom Chilaru (artiomchi) deleted the feat/add-mongodb-replicaset-support branch September 6, 2026 09:14
@microsoft-github-policy-service microsoft-github-policy-service Bot added this to the 13.6 milestone Sep 6, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 6, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-integrations Issues pertaining to Aspire Integrations packages mongodb Issues related to mongodb integrations

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MongoDB Transactions requires replicas

6 participants