Transações Distribuídas

Mecanismos que garantem que um conjunto de operações de banco de dados distribuídas entre vários nós independentes seja executado completamente (commit) ou revertido completamente (rollback) de forma atômica.

Teorema CAP (Brewer, 2000): um sistema distribuído pode garantir apenas duas de três propriedades — Consistência, Disponibilidade, Tolerância a Partições.

        graph LR
  Center["Transações Distribuídas"]:::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;

      

🧒 Explique como se eu tivesse 5 anos

Imagine que você compra um ingresso de show online. O site deve fazer duas coisas ao mesmo tempo: (1) debitar sua conta bancária, (2) dar a você o ingresso. Se o computador do banco debita mas o de ingressos trava, você pagou sem receber nada. Uma transação distribuída é a regra: 'Ou ambas as operações são bem-sucedidas, ou ambas são canceladas completamente como se nada tivesse acontecido.' Tudo ou nada em vários computadores.

🤓 Expert Deep Dive

2PC — Protocolo Bloqueante: Se o coordenador falha após receber todos os votos YES, os participantes mantêm bloqueios exclusivos indefinidamente. SAGA: Cada passo T_i tem uma transação compensatória C_i. Falha em T_3 executa C_2, depois C_1. SAGAs sacrificam Isolamento pela disponibilidade. HTLC: Alice bloqueia BTC com hash(secret); Bob bloqueia ETH com o mesmo hash. Alice revela o secret para reivindicar ETH, o que permite a Bob reivindicar BTC. Teorema CAP: Consistência vs. Disponibilidade durante partições de rede.

❓ Perguntas frequentes

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.

📚 Fontes