mongodb/mongo
mongos
mongos is the sharding router. It speaks the same wire protocol as mongod but holds no user data of its own. Instead it consults the cluster's routing table, forwards each operation to the right shard or shards, and coordinates cross-shard transactions.
Purpose
For each client request, a mongos:
- Authenticates the client and authorizes the command.
- Looks up the target collection's routing in the catalog cache (
src/mongo/s/catalog_cache.h). - Targets one or more shards based on the shard key.
- Sends commands in parallel via the AsyncRequestsSender (
src/mongo/s/async_requests_sender.cpp). - Aggregates the per-shard results, transparently retries on shard primary changes, and returns one BSON reply.
- For multi-statement transactions, drives the cooperative two-phase commit via the TransactionRouter (
src/mongo/s/transaction_router.cpp).
Entry point
The entry point is in src/mongo/s/mongos_main.cpp (~1.7 k lines), which initializes:
- The transport layer (
src/mongo/transport/). - The catalog cache and config server connection pool.
- The cursor manager (
src/mongo/s/query/cluster_cursor_manager.h). - The query analysis sampler (
src/mongo/s/query_analysis_sampler.cpp). - Sharding-task executors and connection pools (
src/mongo/s/sharding_task_executor_pool*).
The router's service entry point is src/mongo/s/service_entry_point_router_role.cpp.
Inside a routed command
sequenceDiagram
participant Client
participant Router as mongos
participant Cache as CatalogCache
participant ARS as AsyncRequestsSender
participant ShardA as Shard A primary
participant ShardB as Shard B primary
Client->>Router: insert / find / update OP_MSG
Router->>Cache: getCollectionRoutingInfo(nss)
Cache-->>Router: ChunkManager, shard placement
Router->>ARS: scatter command to targeted shards
ARS->>ShardA: command
ARS->>ShardB: command
ShardA-->>ARS: response
ShardB-->>ARS: response
ARS-->>Router: AsyncRequestsSender::Response[]
Router->>Router: append responses, error labels
Router-->>Client: aggregated OP_MSG replyCluster transactions
A multi-statement, multi-shard transaction goes through the TransactionRouter:
stateDiagram-v2
[*] --> StartTransaction
StartTransaction --> InProgress: first command with txnNumber
InProgress --> InProgress: subsequent statements (per shard)
InProgress --> Committing: commitTransaction
Committing --> Committed: all shards ack
Committing --> Aborted: any shard rejects
InProgress --> Aborted: abortTransaction or error
Aborted --> [*]
Committed --> [*]The router tracks each participating shard, manages the at-cluster-time read snapshot, picks a coordinator, and runs the two-phase commit. The implementation is in transaction_router.cpp (3.7 k lines) and exhaustively tested in 13 k lines — the largest test file in the project).transaction_router_test.cpp (
For more on the protocol, see Transactions.
Catalog cache
The routing table is materialized into the CatalogCache, which stores:
- For each sharded collection, a
ChunkManagerthat maps shard-key ranges to shards. - For each unsharded collection, the owning shard.
- For each database, the primary shard.
The cache is populated on demand from the config server's catalog (config.collections, config.chunks, config.databases) and refreshed when shards return StaleConfig/StaleEpoch errors. The mongos process implements StaleShardVersion retries transparently to the client.
Background services
| Service | Where | Purpose |
|---|---|---|
| Catalog cache loader | src/mongo/s/catalog_cache_loader_* |
Pulls routing info from the config server. |
| Cluster cursor manager | src/mongo/s/query/cluster_cursor_manager.h |
Tracks open cursors fanned out across shards. |
| Query analysis sampler | src/mongo/s/query_analysis_sampler.cpp |
Samples queries for the analyzeShardKey command. |
| Router transactions metrics | src/mongo/s/router_transactions_metrics.cpp |
Counters for committed/aborted cluster transactions. |
| Migration blocking operations | src/mongo/s/migration_blocking_operation/ |
Coordinates operations that must block migrations (e.g. resharding cutover). |
Key source files
| File | Purpose |
|---|---|
src/mongo/s/mongos_main.cpp |
Process startup. |
src/mongo/s/service_entry_point_router_role.cpp |
Dispatch entry point. |
src/mongo/s/transaction_router.cpp |
Cluster transaction state machine and 2PC. |
src/mongo/s/async_requests_sender.cpp |
Multi-shard fan-out. |
src/mongo/s/catalog_cache.h |
Routing table cache. |
src/mongo/s/commands/ |
mongos-side command implementations (cluster_*). |
src/mongo/s/query/ |
Cluster cursor manager and aggregation runner. |
src/mongo/s/resharding/ |
The router-side resharding coordinator interface. |
Integration points
- Config server — every
mongoswatchesconfig.*collections for routing changes. - Shards — long-lived connections via the sharding-task executor pool.
- Drivers — the wire protocol surface looks identical to
mongodfrom a driver's perspective. mongodshard role — the same binary now hosts the router role too in some deployments. The two services share a process via theServiceabstraction.
Entry points for modification
Adding a router-side command means writing a cluster_*_cmd.cpp under src/mongo/s/commands/ that uses the ClusterCommandRoutingInfo and AsyncRequestsSender. Changing the cluster transaction protocol means modifying transaction_router.cpp and updating the (very large) test file. Changing routing-cache behavior is concentrated in src/mongo/s/catalog_cache.h and the loaders under src/mongo/s/catalog_cache_loader_*.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.