mongo-csharp-driver / Core
AGENTS.md3.2k starsChanged 4 months agoApache-2.0View on GitHub
This file covers the Server Discovery And Monitoring (SDAM) topology layer, connection pooling, wire protocol, and supporting infrastructure under src/MongoDB.Driver/Core/. Scoped subdirectories: Clusters/, Servers/, Connections/, ConnectionPools/, WireProtocol/, Compression/, Configuration/, Misc/. (Core/Authentication/ and Core/Bindings/ also live under Core/ but are out of scope for this reviewer — see the auth-area and operations-area AGENTS.md.) Ownership boundary: the Operations layer (Core/Operations/, Core/Bindings/) sits above this and owns retry, session attachment, and cursor lifecycle. Events and Logging have their own AGENTS.md files. Authentication mechanisms…
Trending
Quiet since September.about the whole repository
Who's talking about mongodb/mongo-csharp-driver
- jbogard/MongoDB.Driver.Core.Extensions.DiagnosticSources“Support for latest MongoDB library with signing”GitHub · Jul 28, 2024 · 13 reactions
- opensearch-project/opensearch-net“[FEATURE] Add LINQ Support to the OpenSearch C# Client”GitHub · Sep 18, 2023 · 5 reactions
- nopSolutions/nopCommerce“MongoDB database support”GitHub · Apr 30, 2019 · 4 reactions
- microsoft/aspire“MongoDB.Driver v3 breaks Aspire.MongoDB.Driver integration”GitHub · Oct 18, 2024 · 3 reactions
- jbogard/MongoDB.Driver.Core.Extensions.DiagnosticSources“Deprecate this package”GitHub · Apr 21, 2026 · 2 reactions
The biggest 5 of 40 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 40
Talked about on GitHub (40 times).
On GitHub · 40
- Jul 28, 2024Support for latest MongoDB library with signing — jbogard/MongoDB.Driver.Core.Extensions.DiagnosticSources13 reactions · 5 comments
- Sep 18, 2023[FEATURE] Add LINQ Support to the OpenSearch C# Client — opensearch-project/opensearch-net5 reactions · 1 comment
- Apr 30, 2019MongoDB database support — nopSolutions/nopCommerce4 reactions · 24 comments
- Oct 18, 2024MongoDB.Driver v3 breaks Aspire.MongoDB.Driver integration — microsoft/aspire3 reactions · 9 comments
- Apr 21, 2026Deprecate this package — jbogard/MongoDB.Driver.Core.Extensions.DiagnosticSources2 reactions · 1 comment
35 more on GitHub
- Nov 5, 2025Corrected Membership Session Handling — OrleansContrib/Orleans.Providers.MongoDB2 reactions · 2 comments
- Jun 4, 2016Support .NET Core — tugberkugurlu/AspNetCore.Identity.MongoDB2 reactions · 1 comment
- Jul 12, 2026Upgrade MongoDB.Driver to 3.9.0 to fix Snappier and SharpCompress vulnerabilities — madelson/DistributedLock1 reaction
- May 28, 2026Upgrade MongoDB.Driver to 3.9.0 — abpframework/abp1 reaction · 1 comment
- May 12, 2026Upgrade MongoDB.Driver to 3.8.1 — abpframework/abp1 reaction
- Mar 19, 2026bump MongoDB.Driver to 3.7.1 — abpframework/abp1 reaction
- Jan 18, 2026Update MongoDB.Driver package version to 3.6.0 — abpframework/abp1 reaction · 1 comment
- Nov 20, 2025Update MongoDB.Driver to version 3.5.1 — abpframework/abp1 reaction
- Jan 30, 2023Hangfire.Mongo is incompatible with the MongoDB.Driver LINQ3 provider — gottscj/Hangfire.Mongo1 reaction · 1 comment
- Jun 6, 2022Mongo Driver Compatibility — alirezanet/Gridify1 reaction · 3 comments
- Mar 31, 2015Support for 2.0 async driver — RobThree/MongoRepository1 reaction · 35 comments
- Sep 29, 2026Bump MongoDB.Driver from 2.11.5 to 2.19.0 — ramonaoldf/run-devops0 reactions
- Sep 15, 2026Bump the nuget group with 1 update — ApurvSinghal/ApurvXam0 reactions
- Aug 2, 2026Bump MongoDB.Driver from 2.8.1 to 2.19.0 — mohaom/TailwindTraders-Website0 reactions
- Jan 12, 2025Bump MongoDB.Driver from 2.14.1 to 2.19.0 in /src/Infrastructure — vigovlugt/LeagueOfItemsBackend0 reactions
- Aug 6, 2024Update dependency MongoDB.Driver to 2.19.0 [SECURITY] — MrDariusAD/DynamicFilter0 reactions
- Aug 6, 2024Update dependency MongoDB.Driver to 2.12.2 [SECURITY] — ShamKarthikS-Hexaware/recicd0 reactions
- Aug 6, 2024Update dependency MongoDB.Driver to 2.12.2 [SECURITY] — MrDariusAD/GirlfriendAdventskalender0 reactions
- Jan 15, 2024Bump MongoDB.Driver.Core and MongoDB.Bson — kravvya/GardenLog.V20230 reactions
- Nov 17, 2023build(deps): bump MongoDb_Version from 2.19.0 to 2.22.0 — AntonioFalcaoJr/EventualShop0 reactions
- Mar 28, 2023Bump MongoDB.Driver from 2.19.0 to 2.19.1 — eincioch/dotnet-microservices-boilerplate0 reactions
- Mar 27, 2023Bump MongoDB.Driver from 2.19.0 to 2.19.1 — niaz-ali-khan/microservise0 reactions
- Mar 3, 2023Bump MongoDB.Driver from 2.13.1 to 2.19.0 in /DotNet/POC/DatabaseBenchmark — AdamNagy/Nadam.Tryouts0 reactions
- Mar 3, 2023Bump MongoDB.Driver from 2.12.3 to 2.19.0 in /Esiur.Stores.MongoDB — esiur/esiur-dotnet0 reactions
- Oct 17, 2022Bump MongoDB.Driver from 2.17.1 to 2.18.0 in /src/backend — ScottishTapWater/OrderBook0 reactions
- Oct 17, 2022fix(deps): bump MongoDB.Driver from 2.16.1 to 2.18.0 — Manu0912/doppler-push-contact0 reactions
- Oct 17, 2022Bump MongoDB.Driver from 2.13.0 to 2.18.0 — uruk-project/uruk-server0 reactions
- Oct 17, 2022Bump MongoDB.Driver from 2.15.1 to 2.18.0 — joelbyford/ApiPatternsClient0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.13.1 to 2.18.0 in /examples/AspNetCoreMvc — brucehu123/opentelemetry-dotnet-instrumentation0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.12.4 to 2.18.0 in /services/common/Platform.Common — frogsbreath-games/eucre0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.12.4 to 2.18.0 in /services/lobby/Platform.Lobby.Tests — frogsbreath-games/eucre0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.12.4 to 2.18.0 in /services/eucre-game/Games.Eucre.Api — frogsbreath-games/eucre0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.12.4 to 2.18.0 in /services/weather/Weather.Api — frogsbreath-games/eucre0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.12.4 to 2.18.0 in /services/library/Platform.Library.Api — frogsbreath-games/eucre0 reactions
- May 24, 2022Bump MongoDB.Driver from 2.13.1 to 2.15.1 in /examples/AspNetCoreMvc — brucehu123/opentelemetry-dotnet-instrumentation0 reactions
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository35 other files it gives its agents.
- AGENTS.mdAGENTS.md
- src/MongoDB.Bson/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Authentication/AGENTS.mdAGENTS.md
- src/MongoDB.Driver.Authentication.AWS/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Core/Bindings/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Core/Events/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Core/Logging/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Core/Operations/AGENTS.mdAGENTS.md
- src/MongoDB.Driver.Encryption/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Encryption/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/GeoJsonObjectModel/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/GridFS/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Linq/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Search/AGENTS.mdAGENTS.md
- tests/MongoDB.Driver.TestHelpers/AGENTS.mdAGENTS.md
- tests/MongoDB.Driver.Tests/Specifications/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- src/MongoDB.Bson/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver.Authentication.AWS/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Authentication/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Core/Bindings/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Core/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Core/Events/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Core/Logging/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Core/Operations/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver.Encryption/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Encryption/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/GeoJsonObjectModel/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/GridFS/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Linq/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Search/CLAUDE.mdCLAUDE.md
- tests/MongoDB.Driver.TestHelpers/CLAUDE.mdCLAUDE.md
- tests/MongoDB.Driver.Tests/Specifications/CLAUDE.mdCLAUDE.md
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
15 rules. About 0 are common, 5 are distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 83
Streaming heartbeat: If the server supports awaitable: true, the monitor reuses the same connection across heartbeats and waits for the …
- Very specific: line 187
Document sections (type 1): bulk write payloads (insert/update/delete).
- Very specific: line 254
Trigger: When the scheme is mongodb+srv://, the cluster performs SRV resolution.
- Very specific: line 257
TTL caching: Not persistently cached by the driver.
- Distinctive: line 263
Only one endpoint is expected.
- Very specific: line 299
If MaxConnections is too low and many threads call CheckOut() concurrently, the wait queue will block.
- Very specific: line 313
Default is 10s interval; the heartbeat timeout (ServerSettings.HeartbeatTimeout) defaults to Timeout.InfiniteTimeSpan, with the underlying …
- Very specific: line 320
Best practice: Never fork after creating a MongoClient.
- Distinctive: line 327
If you change DNS records, the next monitor run picks up the change.
- Distinctive: line 332
If the server advertises a compressor the client doesn't have (e.g., zstd), the connection falls back to no compression.
- Distinctive: line 344
Issue: If the server goes down while waiting for a streamed response, the TCP connection hangs.
- Very specific: line 345
Fallback: If awaitable: true is not supported, the monitor falls back to polling.
- Very specific: line 346
Race condition: If a server topology changes (primary to secondary) while a response is streaming, the monitor may receive a stale response.
- Very specific: line 352
When changing this layer, verify the OperationContext is propagated unchanged — wrapping or replacing it loses the deadline.
- Distinctive: line 358
Consequence: If a connection is dropped mid-operation, the operations layer decides whether to retry.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
MongoDB.Driver / Core — AGENTS.md (Connection & Transport / SDAM)
This file covers the Server Discovery And Monitoring (SDAM) topology layer, connection pooling, wire protocol, and supporting infrastructure under src/MongoDB.Driver/Core/. Scoped subdirectories: Clusters/, Servers/, Connections/, ConnectionPools/, WireProtocol/, Compression/, Configuration/, Misc/. (Core/Authentication/ and Core/Bindings/ also live under Core/ but are out of scope for this reviewer — see the auth-area and operations-area AGENTS.md.)
Ownership boundary: the Operations layer (Core/Operations/, Core/Bindings/) sits above this and owns retry, session attachment, and cursor lifecycle. Events and Logging have their own AGENTS.md files. Authentication mechanisms live in Authentication/ — but this layer drives the auth handshake during connection establishment.
1. Clusters / SDAM Topology
Key files: Cluster.cs, ClusterDescription.cs, ClusterType.cs, ClusterFactory.cs, MultiServerCluster.cs, LoadBalancedCluster.cs, SingleServerCluster.cs, DnsMonitor.cs, ServerSelectors/. Plus supporting ID/state types — ClusterClock.cs, ClusterId.cs, ClusterState.cs, ElectionId.cs, ReplicaSetConfig.cs — and the various I* interfaces.
Topology types and state machine
ClusterTypeenum:Unknown,Standalone,ReplicaSet,Sharded,LoadBalanced. (Direct-connection mode is a connection-string option, not aClusterTypevalue — it's expressed viaClusterSettings.DirectConnectionand produces aSingleServerCluster.) Determines selector behavior and read/write affinity.ClusterDescriptionimmutable snapshot of cluster state: holds a list ofServerDescriptions, the cluster type, and computed properties likeLogicalSessionTimeout. Updated atomically when servers report topology changes.Clusterabstract base; concrete implementationsMultiServerCluster(standard SDAM for Standalone/ReplicaSet/Sharded),SingleServerCluster(direct-connection mode),LoadBalancedCluster(LB mode with single virtual endpoint).
Cluster initialization and lifecycle
- Initialization:
Cluster.Initialize()triggers server creation and monitoring threads.MultiServerClusterspawns a background DNS monitor thread (for SRV resolution) and per-server monitor threads.LoadBalancedClustercreates one virtual server and a DNS monitor. - Disposal: Cancels all monitoring threads and closes pooled connections. Cluster remains queryable briefly during disposal for graceful shutdown.
- Topology updates:
ClusterDescriptionChangedEventArgspublished whenever a server's description changes. Listeners update read preference routing and failover logic.
Server selection (IServerSelector chain)
IServerSelector: Single responsibility — filter servers by one criterion (read preference, latency, writable, etc.).CompositeServerSelector: Chains selectors; later selectors filter the result of earlier ones.- Built-in selectors:
ReadPreferenceServerSelector— applies the read preference mode (Primary, Secondary, Nearest, etc.) and filters by tags.WritableServerSelector— returns only writable servers (Primaries in RS, all in Standalone/Sharded).LatencyLimitingServerSelector— filters servers withinLocalThresholdof the fastest server, reducing tail latency.EndPointServerSelector— filters a specific server by endpoint (used internally for pinned connections).DeprioritizedServersServerSelector— deprioritizes known bad servers. Aninternal sealedcomposing selector: it wraps anotherIServerSelectorand filters that selector's output, removing deprioritized endpoints on sharded clusters. Despite the name, it has nothing to do with replica-set priorities.OperationsCountServerSelector— load-balances by operation count (for load-balanced deployments).RandomServerSelector— random tie-breaker when multiple servers are equally good.DelegateServerSelector— wraps an arbitraryFunc<…>for ad-hoc selection logic (rarely used in production code; useful for tests and bespoke deployments).
Selection flow: SelectServer(selector, timeout) blocks until a suitable server is found or timeout expires. Internally it waits on the cluster's DescriptionChanged event (via an internal TaskCompletionSource) and re-runs the selector each time topology changes. (The MaxServerSelectionWaitQueueSize setting on ClusterSettings bounds the number of waiters, but there is no public ServerSelectionWaitQueue type.)
SDAM state machine and monitoring loop
- Heartbeat interval: Configurable, default 10 seconds. In polling mode the server monitor sends an
isMaster/hellocommand on each interval; in streaming mode (used against servers that advertisehelloOk) the monitor instead holds an awaitablehelloopen and processes responses as the server pushes them — the interval bounds polling fallback and idle-keepalive only. The choice between polling and streaming is governed byServerMonitoringMode(Auto/Stream/Poll;Autois the default and resolves to streaming on supported servers). FaaS polling override: FaaS environments force polling mode under
Autoregardless of server support — streaming heartbeats and short-lived FaaS invocations don't mix. Detection lives inServerMonitor.IsRunningInFaaS(Core/Servers/ServerMonitor.cs), and the env vars actually checked are:- AWS Lambda:
AWS_EXECUTION_ENV(must start withAWS_Lambda_) andAWS_LAMBDA_RUNTIME_API. - Azure Functions:
FUNCTIONS_WORKER_RUNTIME. - GCP:
K_SERVICE(set by Cloud Run and the Cloud Functions Gen2 runtime, which is Cloud Run under the hood — this is doc-author interpretation; the source comment says only "gcp.func") andFUNCTION_NAME(Cloud Functions Gen1). - Vercel:
VERCEL.
See
Core/Servers/ServerMonitor.csfor the authoritative list.- AWS Lambda:
- Topology version: Servers embed a
TopologyVersion(process ID + counter) in heartbeat responses. Stale responses are ignored; newer topology versions trigger faster invalidation. - Streaming heartbeat (awaitable hello): Servers that advertise
helloOksupport the"awaitable": trueoption, allowing the server to hold the heartbeat response until the topology changes. Reduces latency on failover. - Polling heartbeat: Fallback for older servers. The monitor thread sleeps between intervals.
- State invalidation: On error or topology change, the cluster updates generation counters in the connection pool (forcing reconnection) and marks the offending server as unknown.
2. Servers / Per-server abstractions
Key files: Server.cs, DefaultServer.cs, ServerDescription.cs, ServerType.cs, ServerMonitor.cs, RoundTripTimeMonitor.cs, TopologyVersion.cs, LoadBalancedServer.cs. Plus per-server state and ID types — ServerMonitorSettings.cs, ServerMonitoringMode.cs, ServerState.cs, ServerId.cs, SelectedServer.cs, ServerChannel.cs.
Server types
ServerType:Unknown,Standalone,ShardRouter,ReplicaSetPrimary,ReplicaSetSecondary,ReplicaSetPassive(still public, but[Obsolete]),ReplicaSetArbiter,ReplicaSetOther,ReplicaSetGhost,LoadBalanced.ServerDescriptionimmutable: endpoint, type, round-trip time (RTT), tags, setName, electionId, and health. Computed during heartbeat, never mutated.
Server monitoring
IServerMonitor— spawns a background thread that periodically contacts the server.ServerMonitor— concrete implementation. Manages a single connection for heartbeat probes; creates and destroys it as needed.- In polling mode, sends
hello(or legacyisMaster) on each heartbeat interval; in streaming mode, holds a single awaitablehelloopen and processes pushed responses (the interval bounds polling fallback and idle-keepalive). - Interprets response via
HelloResult, updatingServerDescription. - On error, classifies the exception (network, auth, incompatible version, etc.) and updates the server state accordingly.
- Publishes
ServerDescriptionChangedEventArgswhen state changes.
- In polling mode, sends
RoundTripTimeMonitor— the instance is always constructed alongside theServerMonitor, but is onlyStart()-ed as a separate background thread in streaming mode; in that mode it measures latency via a dedicated heartbeat connection so the streaming connection isn't disturbed. Computes exponentially-weighted moving average (EWMA) of RTT. Polling-mode monitors don't start the dedicated RTT thread; they add RTT samples directly from each heartbeat round-trip.- Streaming heartbeat: If the server supports
awaitable: true, the monitor reuses the same connection across heartbeats and waits for the server to push updates.
Error classification and SDAM recovery
- On a failed command, the driver inspects the error to decide whether the server is still writable, readable, or unknown.
- Examples:
NotPrimaryError→ server markedUnknown; the nexthelloreclassifies it (commonly toReplicaSetSecondary).ShutdownInProgressError→ server becomes Unknown.- Network timeouts → server becomes Unknown.
- Auth failures → server becomes Unknown; client stops retrying.
- Error recovery is not immediate. The next heartbeat after an error confirms the server's new state.
3. Connections / Single-connection abstractions
Files: BinaryConnection.cs, ConnectionDescription.cs, ConnectionId.cs, ConnectionInitializer.cs, IConnection.cs, HelloResult.cs, ClientDocumentHelper.cs, HelloHelper.cs, TcpStreamFactory.cs, SslStreamFactory.cs, Socks5ProxyStreamFactory.cs.
Connection lifecycle
BinaryConnection— wraps a TCP/TLS stream. OnOpen():- Opens the underlying stream (TCP or TLS).
- Sends a
hellocommand —ConnectionInitializerbuilds it viaHelloHelper.AddCompressorsToCommand(compressor list embedded) and the authenticator'sCustomizeInitialHelloCommand(often embeddingspeculativeAuthenticate). Both compression negotiation and the first auth step ride on this single hello. - Authenticates the rest of the way if credentials are supplied and speculative auth didn't complete.
- Updates
ConnectionDescriptionwith negotiated parameters (compressor, max BSON size, max wire version, …) from the hello reply.
ConnectionId— unique identifier combining server ID and a local counter. Used in SDAM events and logging.ConnectionDescription— immutable snapshot of negotiated connection state: hello result, compression type, auth mechanism, etc.
isMaster / hello handshake
HelloResultwraps thehello(or legacyisMaster) command response.- Contains: topology version, server type, replica set info, compressor list, max BSON size, max wire version, etc.
- Hello vs isMaster selection: Drivers send
helloagainst servers that advertisehelloOkin their initial reply and fall back toisMasterfor older servers. The two responses are payload-compatible; only the command name differs. The gate is the runtimeHelloOkflag (seeServerMonitor.csandHelloResult.HelloOk), not a hardcoded server-version floor — past versions of this file cited "5.0+" and then "4.4.2+"; both are misleading and should not be re-introduced. - Speculative authentication: The hello may carry an embedded
"speculativeAuthenticate"payload, allowing the first SASL step to ride on the handshake — see the auth-areaAGENTS.mdfor which mechanisms speculate.
Compression negotiation
- During connection initialization, the driver sends a list of supported compressors.
- The server responds with its preference.
- Both sides agree on a single compressor type; messages are compressed after that point.
- See also
Compression/subdirectory.
Stream factories and TLS/SOCKS5
IStreamFactory— creates the underlying I/O stream.TcpStreamFactory— opens aTcpClient, applies keep-alive, then wraps it.SslStreamFactory— wraps the TCP stream in anSslStreamfor TLS. Validates certificates and handles SNI. Validation is configured viaSslStreamSettings.ServerCertificateValidationCallback; the user-facing "trust anything" toggle isMongoClientSettings.AllowInsecureTls(there is noSslStreamSettings.AllowInvalidCertificatesproperty).Socks5ProxyStreamFactory— wraps anotherIStreamFactoryand performs the SOCKS5 handshake first, so any TLS layer sits on top of the proxied stream.
Command monitoring at the connection level
CommandEventHelper— firesCommandStartedEventbefore sending a command andCommandSucceededEvent/CommandFailedEventafter.- Events include command text, database, operation ID, and timing.
- Encryption:
CommandMessageFieldEncryptor/CommandMessageFieldDecryptormodify command BSON before/after the wire.
4. ConnectionPools / Pool implementation
Files: ExclusiveConnectionPool.cs, ExclusiveConnectionPool.Helpers.cs, ConnectionPoolSettings.cs, MaintenanceHelper.cs, ServiceStates.cs, CheckOutReasonCounter.cs.
CMAP (Connection Monitoring And Pooling)
ExclusiveConnectionPool— single pool per (server, endpoint) pair. Follows the CMAP spec.- Pool state:
PoolStatetracks open/closed status and event logging. - Maintenance thread:
MaintenanceHelperperiodically removes idle connections and checks for stale generation.
Pool generation and fork detection
- Generation counter: Incremented when the pool is cleared (e.g., after topology change or connection error).
ServiceStates: Tracks per-service (load-balanced service) generation and connection count. The pool generation is incremented on cluster-driven invalidation events (e.g.,Clear()after topology change, error classification, or LB service-id rollover); stale connections are then discarded and new ones are created on next checkout.
Connection management
CheckOutReasonCounter— categorizes checkout reasons (explicit, implicit, pool exhaustion, etc.) for observability.- Wait queue: Async-friendly semaphore that blocks callers when the pool is at max connections or max connecting.
- Semaphores:
_maxConnectionsQueue— enforcesMaxConnectionslimit._maxConnectingQueue— enforcesMaxConnectinglimit (concurrent TCP handshakes).
- Idle eviction: Connections unused for longer than
MaxIdleTimeare removed during maintenance.MaxIdleTimelives onConnectionSettings(notConnectionPoolSettings) — the pool reads it off each connection during the maintenance sweep.
Settings
ConnectionPoolSettings:MaxConnections,MaxConnecting,MinConnections,MaintenanceInterval,WaitQueueTimeout,WaitQueueSize(onlyWaitQueueSizeis[Obsolete]). Note:MaxIdleTimeis onConnectionSettings, notConnectionPoolSettings— the pool reads it from each connection during maintenance.- The maintenance loop in
MaintenanceHelperproactively brings the pool up toMinConnectionson each maintenance tick (the actual min-size top-up runs via private helpers — there is no publicEnsureMinSizeAPI). Warm-up runs on the background maintenance thread, not at client construction: if the first checkout happens before maintenance has caught up, that checkout still synchronously creates a connection (subject to theMaxConnectingsemaphore).
5. WireProtocol / OP_MSG and command messaging
Files: CommandWireProtocol.cs, CursorBatch.cs, Messages/, WireProtocolMessageEncoders/.
Command wire protocol layers
IWireProtocol<TResult>— abstract interface for a single request–response exchange.CommandWireProtocol<T>— sends commands as OP_MSG. It also owns the streamable state (_moreToCome/_previousRequestId) for exhaust/streaming responses, resetting it when executed against a different connection. The legacy OP_QUERY path was removed when the minimum supported server version exceeded 3.6, and the formerCommandUsingCommandMessageWireProtocolwas merged into this single class.
OP_MSG
CommandWireProtocol— sends commands as OP_MSG (opcode 2013).- Message format:
- Header: flag bits, opcode, message length, request ID.
- Payload sections:
- Body section (type 0): the command document itself.
- Document sections (type 1): bulk write payloads (insert/update/delete).
- Compressed payloads: if compression is negotiated, the entire message is compressed.
moreToCome: A bidirectional OP_MSG flag bit. Inbound (server-set on a response): more responses will follow on the same request — used by exhaust cursors (see alsoCore/Operations/AGENTS.mdfor cursor lifecycle) and the streaminghelloheartbeat. Outbound (client-set on a request): tells the server not to reply at all — used by unacknowledged writes (w: 0) and other fire-and-forget command shapes. It is not a way for clients to batch outboundgetMorerequests — outbound batching uses cursorbatchSizeinstead.- Both request and response messages extend the common
CommandMessagebase type.IConnection.SendMessageis typed asRequestCommandMessage;IConnection.ReceiveMessagereturnsResponseCommandMessage.
Cursor batching
CursorBatch<T>— immutable result: cursor ID, document list, and optional post-batch resume token (for change streams).- Cursor ID 0 means the cursor is exhausted;
CursorBatchcan be iterated to get all documents. - getMore command repeated until cursor ID is 0.
Messages subdirectory
CommandMessage— the single wire message type for both requests and responses (OP_MSG, opcode 2013).CommandMessageSection,BatchableCommandMessageSection— payload sections within OP_MSG.CompressedMessage— OP_COMPRESSED wrapper (opcode 2012). The wire format is a standard message header with opcode 2012, followed by theoriginalOpcodeof the wrapped message, acompressorId, and the compressed payload. It is a distinct message type, not a flag on OP_MSG.
Encoders
WireProtocolMessageEncoders/BinaryEncoders/— encode/decode wire messages from/to BSON.- Each message type has an encoder. Encoders handle endianness, section encoding, compression/decompression.
6. Compression / Wire compression
Files: ICompressor.cs, SnappyCompressor.cs, ZlibCompressor.cs, ZstandardCompressor.cs, NoopCompressor.cs, CompressorSource.cs, CompressorTypeMapper.cs.
Compressor types
CompressorTypeenum:Noop(0),Snappy(1),Zlib(2),ZStandard(3).- Each type has a numeric wire protocol ID (as defined in the spec).
ICompressor interface
Typeproperty: the compressor type.Compress(Stream input, Stream output)— compress input to output.Decompress(Stream input, Stream output)— decompress input to output.
Compressor implementations
SnappyCompressor— wraps the Snappier library (using Snappier;).ZlibCompressor— wrapsSharpCompress.Compressors.Deflate.ZlibStream.ZstandardCompressor— wraps the ZstdSharp library.NoopCompressor— pass-through (for testing or no compression).
Negotiation
CompressorSource— holds the pool of supported compressors based onConnectionSettings.Compressors.- During
hellohandshake, the server advertises its supported compressors. The connection picks the first one in the client's list that the server also supports. - Compression is per-connection and negotiated during initialization.
7. Configuration / Connection string and settings hierarchy
Files: ConnectionString.cs, ClusterBuilder.cs, ClusterSettings.cs, ServerSettings.cs, ConnectionPoolSettings.cs, ConnectionSettings.cs, TcpStreamSettings.cs, SslStreamSettings.cs, Socks5ProxyStreamSettings.cs, CompressorConfiguration.cs.
ConnectionString parsing
ConnectionString— parsesmongodb://andmongodb+srv://URIs.- Supports query parameters:
heartbeatIntervalMS,serverSelectionTimeoutMS,maxPoolSize,tls,tlsInsecure,tlsDisableCertificateRevocationCheck,compressors,loadBalanced,directConnection,srvMaxHosts,srvServiceName, among others. (Note:tlsCertificateKeyFileis not parsed by the C# driver — supply client certificates programmatically viaSslSettings.ClientCertificates.) - Performs DNS-SRV resolution for
mongodb+srv://(seeDnsClientWrapperinMisc/). - Returns a normalized list of endpoints and a dictionary of options.
DNS-SRV resolution
- Trigger: When the scheme is
mongodb+srv://, the cluster performs SRV resolution. - Format:
_mongodb._tcp.example.com→ resolves to a list of (host, port) pairs. - TXT records: Optional TXT records may override options like compressors and auth source.
- TTL caching: Not persistently cached by the driver;
DnsMonitorholds the latest resolved endpoints in memory between rescans, but each rescan re-queries DNS. Caching across processes is the OS resolver's job. DnsMonitor— background thread that periodically re-resolves SRV and detects topology changes in the DNS records (e.g., nodes added/removed).
Load-balanced mode
- Enabled via the
loadBalanced=truequery parameter on a standardmongodb://ormongodb+srv://URI — there is no distinctmongodb+srv+lb://scheme; onlymongodb://andmongodb+srv://are recognised by the driver. - Only one endpoint is expected; the LB proxy handles server routing internally.
LoadBalancedClustercreates a single virtual server and does not perform server selection.- In LB mode the driver runs no background server monitor —
LoadBalancedServerhas noIServerMonitor(only the regularDefaultServerdoes), so there are no periodic background heartbeats. A handshake-timehellois still sent per connection during initialization (negotiatinghelloOk,maxBsonObjectSize, etc.); what's absent is the background server monitor and its periodic heartbeats. The cluster type isClusterType.LoadBalancedand the server type isServerType.LoadBalanced.
Settings hierarchy
ClusterSettings— cluster-wide:LoadBalanced,ReplicaSetName,DirectConnection,EndPoints, heartbeat intervals, etc.ServerSettings— per-server defaults for heartbeat timeout.ConnectionPoolSettings— per-pool:MaxConnections,MaxConnecting,MinConnections,MaintenanceInterval,WaitQueueTimeout, and the[Obsolete]WaitQueueSize.ConnectionSettings— per-connection:MaxIdleTime, compressors, application name, server API version, max BSON size negotiation.TcpStreamSettings— socket-level:AddressFamily,ConnectTimeout,ReadTimeout,WriteTimeout,ReceiveBufferSize,SendBufferSize,SocketConfigurator(callback for arbitrarySockettuning, e.g. setting keep-alive orNoDelay).SslStreamSettings— TLS: certificate validation, SNI, client certificate.
ClusterBuilder
- Fluent builder to compose cluster settings. Chains methods like
ConfigureCluster(),ConfigureConnectionPool(),ConfigureConnection(), etc. - Final call:
BuildCluster()creates the cluster instance.
8. Misc / Cross-cutting utilities
Files: Ensure.cs, EndPointHelper.cs, DnsClientWrapper.cs, Feature.cs, ExceptionMapper.cs, EnvironmentVariableProvider.cs, and more.
Ensure— precondition checks (NotNull, IsGreaterThanZero, etc.).DnsClientWrapper— async DNS resolver. The implementation uses theDnsClientNuGet package (notSystem.Net.Dns) so SRV/TXT queries work consistently across platforms. BothIDnsResolverandDnsClientWrapperareinternal; there is no public seam for plugging in a custom resolver. The interface exists so in-assembly tests (viaInternalsVisibleTo) can substitute a fake — production code always goes throughDnsClientWrapperfromDnsMonitor. Past versions of this file claimed users could substitute a customIDnsResolver; do not re-introduce that claim.ExceptionMapper— classifies wire exceptions (network error, timeout, server error) into semantic types.Feature— checks server version for feature availability (e.g., "does this server support client bulk write?"). Only features whose support varies across the server versions this driver supports belong here; once the driver's minimum server version passes a feature's floor, the entry is removed rather than left as a tautology.EnvironmentVariableProvider— abstraction overEnvironment.GetEnvironmentVariablefor testing.
Common pitfalls & design notes
1. Connection-pool starvation under load
- If
MaxConnectionsis too low and many threads callCheckOut()concurrently, the wait queue will block. - Diagnostics: subscribe to the CMAP events in
Core/Events/— e.g.ConnectionPoolReadyEvent,ConnectionPoolClearedEvent, andConnectionPoolCheckedOutConnectionEvent(the last one carries the waitDuration) — to see wait times and pool state transitions. MaxConnectinglimits concurrent TCP handshakes; tuning is workload-dependent.
2. TLS / SNI / certificate validation
- SNI: The driver sends the hostname in the TLS ClientHello (via
System.Net.Security.SslStream). Servers must support SNI for multi-tenant deployments. - Certificate validation:
MongoClientSettings.AllowInsecureTlsis a "trust anything" toggle — it bypasses both certificate-chain validation and hostname/SAN matching (testing only). Invalid certs otherwise causeAuthenticationException. The connection-string optiontlsInsecure=trueis equivalent toAllowInsecureTls;tlsDisableCertificateRevocationCheckis narrower (only disables CRL/OCSP). - Custom client certificates / CA validation: configured via the public
MongoClientSettings.SslSettings.ClientCertificatesandMongoClientSettings.SslSettings.ServerCertificateValidationCallback(the publicMongoDB.Driver.SslSettingstype at the driver root, distinct from the internalMongoDB.Driver.Core.Configuration.SslStreamSettings; the latter is the form the Core layer passes down toSslStreamFactory). The C# driver does not parse the connection-stringtlsCertificateKeyFileoption — client certificates must be supplied programmatically viaMongoClientSettings.SslSettings.ClientCertificates. TheSslStreamuses the system CA store unless overridden by a custom validation callback.
3. Heartbeat misconfiguration causing flapping
- Setting
HeartbeatIntervalMStoo low floods the server with heartbeats. - Setting the heartbeat timeout too low causes spurious timeouts and server flapping. There is no
heartbeatTimeoutMSconnection-string option — the timeout is set programmatically viaClusterBuilder.ConfigureServer(ServerSettings.HeartbeatTimeout), not via the URL. - Default is 10s interval; the heartbeat timeout (
ServerSettings.HeartbeatTimeout) defaults toTimeout.InfiniteTimeSpan, with the underlying socket I/O bounded byconnectTimeoutMS. Tuning should be conservative.
4. Forking a process after MongoClient init
- The driver caches server descriptions and connection pools. A fork inherits these caches.
- On the child process, all cached connections and file descriptors are stale.
- The C# driver does not implement explicit fork detection; topology errors on the next operation will eventually invalidate the affected server's pool, but the user can observe spurious failures and shared-FD weirdness in the meantime.
- Best practice: Never fork after creating a
MongoClient. If you must, callDispose()on the parent's client before forking, and create a new client in the child.
5. DNS-SRV TTL and txn-record overrides
- DNS-SRV results are not cached by the driver; the OS resolver caches them.
DnsMonitorre-queries periodically; the rescan interval starts at 60 seconds andDnsMonitor.ComputeRescanDelayonly lengthens the delay when the min TTL returned in the SRV response exceeds 60s — a sub-60s TTL is floored at 60s, never shorter (DnsMonitor.cs).- TXT records can override compressors and auth source. The driver does not cache TXT records either.
- If you change DNS records, the next monitor run picks up the change.
6. Compression incompatibilities
- Both client and server must support the negotiated compressor.
- If the server advertises a compressor the client doesn't have (e.g., zstd), the connection falls back to no compression.
- Network errors during compression/decompression are fatal to the connection.
7. isMaster vs hello
- The driver sends
helloagainst servers that advertisehelloOkin their initial reply, and falls back toisMasterotherwise. Both travel over OP_MSG. - The
helloresponse payload is identical toisMasterexcept for the command name. - OP_QUERY support was removed from the driver when the minimum supported server version exceeded 3.6. All commands, including the initial handshake, now use OP_MSG exclusively.
8. Streaming hello / awaitable heartbeat edge cases
- Negotiated via
helloOkin the connection-establishing hello reply. - Issue: If the server goes down while waiting for a streamed response, the TCP connection hangs. The monitor has a heartbeat timeout to detect this.
- Fallback: If
awaitable: trueis not supported, the monitor falls back to polling. - Race condition: If a server topology changes (primary to secondary) while a response is streaming, the monitor may receive a stale response.
TopologyVersioncomparison detects this.
9. CSOT (Client-Side Operation Timeout) propagation
- The driver threads an
OperationContext(defined atsrc/MongoDB.Driver/OperationContext.cs, not underCore/Misc/despite being a Core-level concern) carrying bothCancellationTokenand a remaining-timeout deadline, from the public API down through bindings, server selection, connection checkout, and the wire protocol. - Each layer must call
ThrowIfTimedOutOrCanceledat re-entry points (e.g., before each retry attempt, before each pool wait). Skipping a check is a stall risk under deadline. - When changing this layer, verify the
OperationContextis propagated unchanged — wrapping or replacing it loses the deadline.
10. Retry logic lives in Operations, not Core
- This layer is responsible for discovering servers and routing commands.
- Retries (on transient errors, failover) are implemented in
Core/Operations/. The wire protocol layer is oblivious to retries. - Consequence: If a connection is dropped mid-operation, the operations layer decides whether to retry; the connection layer just reports the error.
How to test (Core-level changes)
# SDAM
dotnet test tests/MongoDB.Driver.Tests/MongoDB.Driver.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~Core.Clusters|FullyQualifiedName~Core.Servers"
# Wire protocol
dotnet test tests/MongoDB.Driver.Tests/MongoDB.Driver.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~Core.WireProtocol"
# Connection pool (CMAP)
dotnet test tests/MongoDB.Driver.Tests/MongoDB.Driver.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~ConnectionPools"
# Compression
dotnet test tests/MongoDB.Driver.Tests/MongoDB.Driver.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~Compression"JSON-driven SDAM and CMAP spec runners under tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ and …/connection-monitoring-and-pooling/ exercise the full state machines — see the spec-conformance AGENTS.md.
Key files quick reference
| Responsibility | Files |
| Topology discovery & SDAM | Clusters/Cluster.cs, Clusters/MultiServerCluster.cs, Clusters/ClusterDescription.cs, Servers/ServerMonitor.cs |
| Server selection | Clusters/ServerSelectors/*.cs |
| DNS-SRV & load balancing | Clusters/DnsMonitor.cs, Clusters/LoadBalancedCluster.cs |
| Connection lifecycle | Connections/BinaryConnection.cs, Connections/ConnectionInitializer.cs |
| Wire messages | WireProtocol/CommandWireProtocol.cs, WireProtocol/Messages/*.cs |
| Connection pooling | ConnectionPools/ExclusiveConnectionPool.cs |
| Compression | Compression/ICompressor.cs, Compression/*Compressor.cs |
| Settings & parsing | Configuration/ConnectionString.cs, Configuration/ClusterBuilder.cs |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

