Распределённые транзакции
Механизмы, гарантирующие, что набор операций с базой данных, охватывающих несколько независимых узлов, либо полностью выполнится (commit), либо полностью откатится (rollback) — атомарно.
Теорема CAP (Брюер, 2000): Распределённая система может гарантировать только два из трёх: Согласованность, Доступность, Устойчивость к разделению.
graph LR
Center["Распределённые транзакции"]:::main
Rel_decentralized_derivatives_pricing_models["decentralized-derivatives-pricing-models"]:::related -.-> Center
click Rel_decentralized_derivatives_pricing_models "/terms/decentralized-derivatives-pricing-models"
Rel_transaction_sharding["transaction-sharding"]:::related -.-> Center
click Rel_transaction_sharding "/terms/transaction-sharding"
Rel_decentralized_exchange_dex_order_book["decentralized-exchange-dex-order-book"]:::related -.-> Center
click Rel_decentralized_exchange_dex_order_book "/terms/decentralized-exchange-dex-order-book"
classDef main fill:#7c3aed,stroke:#8b5cf6,stroke-width:2px,color:white,font-weight:bold,rx:5,ry:5;
classDef pre fill:#0f172a,stroke:#3b82f6,color:#94a3b8,rx:5,ry:5;
classDef child fill:#0f172a,stroke:#10b981,color:#94a3b8,rx:5,ry:5;
classDef related fill:#0f172a,stroke:#8b5cf6,stroke-dasharray: 5 5,color:#94a3b8,rx:5,ry:5;
linkStyle default stroke:#4b5563,stroke-width:2px;
🧒 Простыми словами
Представьте, что вы покупаете концертный билет онлайн. Сайт должен сделать два дела одновременно: (1) снять деньги с вашего банка, (2) дать вам билет. Если компьютер банка спишет деньги, а компьютер с билетами упадёт — вы заплатили, но ничего не получили. Распределённая транзакция — это правило: «Либо оба действия успешны, либо оба полностью отменяются, как будто ничего не было». Всё или ничего на нескольких компьютерах.
🤓 Expert Deep Dive
2PC — Блокирующий протокол: Если координатор падает после сбора всех голосов YES, участники удерживают эксклюзивные блокировки бесконечно. Шаблон SAGA: Каждый шаг T_i имеет компенсирующую транзакцию C_i. Сбой на T_3 запускает C_2, затем C_1. SAGA жертвует Изолированностью ради доступности. HTLC: Алиса блокирует BTC с hash(secret); Боб блокирует ETH тем же хэшем. Алиса раскрывает secret, чтобы получить ETH, что автоматически позволяет Бобу получить BTC. Теорема CAP: Согласованность против Доступности при разделении сети.
❓ Частые вопросы
What is the main problem with Two-Phase Commit (2PC)?
It is a blocking protocol. If the coordinator crashes after collecting all 'YES' votes but before sending the final COMMIT or ABORT decision, all participant nodes freeze, holding database locks indefinitely, until the coordinator recovers.
What is the SAGA pattern and why is it preferred in microservices?
A SAGA breaks a long transaction into smaller local transactions, each with a compensating transaction that undoes it. It avoids distributed locks, making services more available, but sacrifices strict isolation (intermediate states may be visible to other services).
How does a Hash Time Lock Contract (HTLC) enable trustless atomic swaps?
Both parties lock their assets using the same cryptographic secret hash. The first party reveals the secret to claim the other's asset, and this revelation automatically unlocks the secret for the second party to claim the first's asset. If either party doesn't act within the time limit, funds are refunded.