Розподілені транзакції
Механізми, що гарантують: набір операцій бази даних, розподілених між кількома вузлами, або повністю виконується (commit), або повністю скасовується (rollback) — атомарно.
CAP-теорема (Брюер, 2000) стверджує, що розподілена система може гарантувати лише два з трьох: Узгодженість (Consistency), Доступність (Availability), Стійкість до розбиття (Partition Tolerance).
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 — протокол із блокуванням (Blocking Protocol): Координатор надсилає PREPARE всім учасникам. Якщо координатор аварійно завершує роботу після отримання всіх відповідей YES, але до надсилання COMMIT, учасники утримують виключні блокування нескінченно. Шаблон SAGA: Кожен крок T_i має компенсаційну транзакцію C_i. Збій на T_3 запускає C_2, потім C_1. SAGA жертвує Ізольованістю заради доступності. HTLC (Hash Time Lock Contract): Аліса блокує 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.