System Design Cases
MongoDB
MongoDB document database deep dive: replica set with oplog (1 primary + N secondaries with automatic Raft-like failover), sharded cluster (mongos routers + config server replica set + 3 shard replica sets), writeConcern levels (1, majority, all), readPreference (primary, secondary, nearest), multi-document transactions (4.0+), and change streams (CDC built-in). Four scenarios: write with writeConcern majority, primary failover with election, sharded query routing (targeted vs scatter-gather), and change stream tailing oplog. Includes ADR comparing MongoDB vs PostgreSQL JSONB vs DynamoDB for evolving-schema document workloads.
MongoDB: document boundaries, replica concerns and sharded routing
MongoDB — document database с replica sets и optional sharding. Schema flexibility не отменяет schema governance; sharding не делает любой query targeted; retryable writes не заменяют idempotency for arbitrary workflows.
Корректная модель
- Atomicity is naturally scoped to one document; multi-document transactions are available but have broader coordination/cost.
- mongos routes all sharded-cluster application operations using config-server metadata.
- Shard key choice affects targeted routing, distribution, monotonic hot spots and resharding cost.
- Retryable writes cover a documented subset and time/history scope; arbitrary external effects remain outside.
Границы и компоненты
| Компонент | Ответственность |
|---|---|
| MongoDB Client | Использует sessions, concerns и retry classifications. |
| mongos Router | Единственный application interface к sharded cluster; использует config metadata. |
| Config Server Replica Set | Хранит chunk/range metadata и cluster configuration. |
| Shard A Primary | Принимает routed writes для своей shard-key range. |
| Shard A Secondary | Реплицирует oplog и может обслуживать разрешённые reads. |
| Shard B Primary | Владеет другой range; участвует в distributed transaction при необходимости. |
| Dedicated Search Index | Опциональная relevance/full-text projection с отдельной freshness model. |
Сценарии
Majority write and explicit read contract
A document mutation routes through mongos to one shard primary. Majority acknowledgement and journal behavior follow deployment settings; subsequent read freshness follows read preference/read concern/session choices.
Проверяемый исход: The API states the chosen guarantee instead of promising every secondary is immediately current.
Secondary read staleness
A secondary-preferred read may lag the primary or observe data with different rollback guarantees depending on read concern. Causal guarantees require the documented session/concern combination.
Проверяемый исход: The caller either accepts bounded/observed staleness or routes to a stronger read path.
Retryable write and ambiguous batch outcome
A supported acknowledged write can be retried by the driver using session and transaction numbers. Multi-operation batches can still report partial/no-write distinctions, and writes inside a transaction are not individually retryable.
Проверяемый исход: The application retries only classified operations and keeps a business id for longer or cross-system ambiguity.
Resharding and search freshness
A poor shard key can cause scatter/gather or hot ranges. MongoDB supports resharding, which redistributes data and needs capacity/verification. A dedicated search projection has its own asynchronous freshness.
Проверяемый исход: Shard-key evolution is a planned migration; full-text search never masquerades as a transactionally current primary read.
Failure, concurrency и replay checklist
- Do not connect application queries directly to one shard.
- Use majority/snapshot/causal settings only with their documented combinations.
- Handle transaction retry labels and unknown commit result separately.
- Test balancer/resharding/search lag under production-shaped data.
Формулы, units и допущения
- A query without shard-key targeting can fan out to S shards; latency follows the slowest required shard plus merge.
- Document growth is bounded by MongoDB limits and relocation cost; embedding an unbounded array is not a free join replacement.
- Shard-key cardinality alone is insufficient: frequency and monotonicity determine hot ranges.
Числа выше — учебные inputs или размерностные формулы. Их нельзя выдавать за benchmark или SLA конкретного продукта.
Связанные темы
[CONCEPT]partitioning-strategies
Первичные источники
- https://www.mongodb.com/docs/manual/applications/replication/
- https://www.mongodb.com/docs/manual/core/retryable-writes/
- https://www.mongodb.com/docs/manual/core/transactions/
- https://www.mongodb.com/docs/manual/core/sharding-shard-key/
- https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/
Scope note
Диаграмма показывает причинные границы и recovery contracts, а не скрытую реализацию конкретного managed-сервиса. Любая stronger guarantee действует только в явно названной transaction/checkpoint/acknowledgement boundary.