System Design Cases
CockroachDB / NewSQL
CockroachDB / NewSQL — distributed SQL database. Postgres wire-compatible, Raft per range, HLC instead of TrueTime, multi-region survival/locality, range splits/rebalancing. Inspired by Spanner (PC/EC) but no atomic clocks needed. 4 scenarios: cross-range distributed transaction (HLC + Raft + 2PC), range rebalance after node add (auto-split, auto-rebalance), multi-region locality via REGIONAL BY ROW (GDPR data residency), region failure (REGION survival mode). 2 ADRs: CockroachDB vs Postgres+Citus vs Spanner choice; HLC vs TrueTime trade-off.
CockroachDB: ranges, Raft, serializable transactions and retries
Distributed SQL сохраняет SQL transactions поверх partitioned replicated keyspace, но сеть остаётся частью latency/failure model. «NewSQL» не отменяет quorum, retries, hotspots или compliance design.
Корректная модель
- Keyspace is split into replicated ranges; each range has its own consensus/lease path.
- Serializable transactions may require client-visible retries under contention or uncertainty.
- Multi-range atomicity adds coordination latency but does not permit partial committed business state.
- Locality/survival configuration is not by itself a complete data-residency or GDPR guarantee.
Границы и компоненты
| Компонент | Ответственность |
|---|---|
| SQL Client with Retry Loop | Повторяет всю transaction closure по retryable error и не дублирует side effects. |
| SQL Gateway | Планирует запрос и координирует transaction across ranges. |
| Range A Leaseholder | Обслуживает consistent operations и предлагает writes в Raft group A. |
| Range A Replica | Участвует в Raft quorum and recovery. |
| Range B Leaseholder | Вторая key range, добавляющая coordination к transaction. |
| Range B Replica | Независимая failure-domain copy range B. |
| Transaction Record and Intents | Отслеживает atomic outcome и provisional writes. |
| Clock and Locality Monitor | Контролирует clock health, lease/locality и hot ranges. |
Сценарии
Single-range serializable transaction
A transaction whose keys are colocated can execute through one leaseholder and its Raft group, though acknowledgement still depends on replication and durability.
Проверяемый исход: Atomic commit is scoped to the transaction; latency is measured, not promised from topology alone.
Multi-range atomic transaction
The gateway touches two independently replicated ranges and coordinates intents/outcome. More participants mean more network and contention surface, not weaker atomicity.
Проверяемый исход: Both ranges expose one committed outcome or the transaction aborts.
Serializable contention retry
Concurrent transactions form a conflict that cannot be hidden safely. The database returns a retryable serialization error; the client re-executes the whole closure.
Проверяемый исход: A stale partial retry cannot leak business side effects or break the invariant.
Range failure, lease and locality
Loss of one replica does not automatically mean data loss; availability depends on the range quorum and locality placement. Residency/compliance requires controls beyond REGIONAL BY ROW.
Проверяемый исход: The system fails closed when quorum is unavailable and separately audits where data/backups/keys can reside.
Failure, concurrency и replay checklist
- Use official retry wrappers or an equivalent bounded whole-transaction loop.
- Keep retried closures deterministic and free of unguarded external side effects.
- Monitor hot ranges, leaseholder locality, clock offset, retry rate and unavailable ranges.
- Test region/node failures against the configured survival goal and backup placement.
Формулы, units и допущения
- Replication factor and survival goal are configured per deployment/table behavior; do not infer one from a three-box picture.
- A transaction spanning k ranges has at least k independent contention/replication surfaces; latency is not k times a constant because work can overlap.
- Monotonic keys can concentrate writes in the end range; use measured distribution/splitting rather than claiming every UUID variant solves hotspots.
Числа выше — учебные inputs или размерностные формулы. Их нельзя выдавать за benchmark или SLA конкретного продукта.
Связанные темы
[CONCEPT]partitioning-strategies
Первичные источники
- https://www.cockroachlabs.com/docs/stable/architecture/overview.html
- https://www.cockroachlabs.com/docs/stable/developer-basics.html
- https://www.cockroachlabs.com/docs/stable/transactions.html
- https://www.cockroachlabs.com/docs/stable/multiregion-overview.html
- https://www.cockroachlabs.com/pdf/cockroachdb-the-resilient-geo-distributed-sql-database-sigmod-2020.pdf
Scope note
Диаграмма показывает причинные границы и recovery contracts, а не скрытую реализацию конкретного managed-сервиса. Любая stronger guarantee действует только в явно названной transaction/checkpoint/acknowledgement boundary.