Designing the System's Core
I'm starting by dissecting the initial request. The core is the 2PC mechanism, and I need to identify the essential components. The simulation's design must accommodate this, so I will start by figuring out the essential functions the system needs to support.
Architecting the Transaction Flow
Now, I'm focusing on the architectural components. I've broken down the system into actors: the Coordinator, the Participants, and the Client. I am working through the step-by-step protocol. I'm exploring the Prepare phase and how the coordinator handles participant votes, building out the message structure for each state. The next step is to examine timeout and failure scenarios.
Analyzing System Requirements
I've outlined the actors, flow, and components, and am now solidifying the details. I'm focusing on the Global Transaction ID, and state machines for the Coordinator and Participants. Write-Ahead Logs are crucial for durability, as are the state machines. Next, I am ready to delve into designing the specific protocol flow, beginning with a more robust structure.
Mapping Out Protocol Steps
The flow now is clear. I've broken down Phase 1 and Phase 2, with commit/rollback details, complete with actors' actions and states. Now, I'm focusing on those edge cases. What happens when a Participant crashes? How do we handle network partitions, simulating packet loss? The simulation facet is coming into focus. Finally, I'll structure the document to include diagrams and data structures.
Outlining the Edge Cases
I'm now diving deep into the simulation aspects. I'm exploring the behavior under failures; specifically, what happens if a participant goes down after voting? The in-doubt state is a critical point. I'm also planning out how to implement network partitions for the simulation. Further, I am developing the data structures for each component.
Clarifying Simulation Requirements
I'm now prioritizing the simulation's features. The design must handle Participant crashes post-vote, the "in-doubt" state is key, and simulating network partitions is crucial. Data structures, logs, and state machines are essential to the simulation's success. The ultimate goal is to see exactly what happens under failure.
This design outlines a system to simulate Distributed Transactions using the Two-Phase Commit (2PC) protocol. The goal is to create a testbed where we can visualize the consensus process and observe how the system behaves under both success and failure scenarios.
1. High-Level Architecture
The system consists of three main entity types:
- Client: Initiates the transaction.
- Coordinator (Transaction Manager): Orchestrates the 2PC protocol, tracks global state, and handles timeouts.
- Participants (Resource Managers): Simulate database nodes. They hold data, manage local locks, and persist a Write-Ahead Log (WAL).
Communication
We will simulate an asynchronous message-passing network (e.g., using message queues or gRPC) to allow for simulating network latency and packet loss.
2. Data Structures
A. Global Transaction ID (GTID)
Every transaction is assigned a unique UUID. All messages related to that transaction must carry this ID.
B. Transaction State Machine
Coordinator States:
INIT: Transaction started.
WAITING_VOTES (Phase 1): Sent prepare requests, waiting for replies.
COMMITTING (Phase 2): Decision made to commit.
ABORTING (Phase 2): Decision made to abort.
DONE: Transaction finished.
Participant States:
INIT: Resting state.
PREPARED: Voted YES, locked resources, waiting for Coordinator decision (In-Doubt State).
COMMITTED: Data written permanently.
ABORTED: Changes rolled back.
C. Simulated Write-Ahead Log (WAL)
To survive simulated crashes, every node writes to a local append-only log before sending network messages.
- Entry Format:
[Timestamp, GTID, State, Metadata]
3. The Protocol Workflow
Phase 0: Setup
The Client requests the Coordinator to update Data X on Node A and Data Y on Node B.
Phase 1: The Prepare Phase (Voting)
- Coordinator:
- Creates GTID.
- Writes
START to WAL.
- Sends
PREPARE message to Participants (Node A, Node B).
- enters
WAITING_VOTES state.
- Participants:
- Receive
PREPARE.
- Check: Can we execute this? (Are locks available? Is disk full?)
- Action (If Yes):
- Acquire locks on Data
X / Y.
- Write
PREPARE (VOTE_COMMIT) to local WAL.
- Send
VOTE_COMMIT to Coordinator.
- Enter
PREPARED state.
- Action (If No):
- Send
VOTE_ABORT to Coordinator.
Phase 2: The Commit Phase (Decision)
- Coordinator:
- Wait for all votes.
- Scenario A (All Commit):
- Write
GLOBAL_COMMIT to WAL.
- Send
COMMIT message to all Participants.
- Enter
COMMITTING state.
- Scenario B (Any Abort or Timeout):
- Write
GLOBAL_ABORT to WAL.
- Send
ROLLBACK message to all Participants.
- Enter
ABORTING state.
- Participants:
- Receive Decision (
COMMIT or ROLLBACK).
- If Commit: Apply changes to "Simulated DB", release locks, write
COMMIT to WAL.
- If Rollback: Undo changes, release locks, write
ABORT to WAL.
- Send
ACK to Coordinator.
- Coordinator:
- Receive
ACKs.
- Once all
ACKs received, write END to WAL.
4. System Components Design (Pseudo-Code)
Here is the Python-style logic for the core components.
The Coordinator
class Coordinator:
def __init__(self):
self.wal = Log()
self.transactions = {} # GTID -> TransactionContext
def begin_transaction(self, participants, payload):
gtid = generate_uuid()
self.wal.write(gtid, "START")
# PHASE 1: PREPARE
responses = []
for p in participants:
resp = p.send_message("PREPARE", gtid, payload)
responses.append(resp)
# DECISION LOGIC
if all(r == "VOTE_COMMIT" for r in responses):
self.wal.write(gtid, "GLOBAL_COMMIT")
decision = "COMMIT"
else:
self.wal.write(gtid, "GLOBAL_ABORT")
decision = "ROLLBACK"
# PHASE 2: EXECUTE DECISION
for p in participants:
p.send_message(decision, gtid)
# WAIT FOR ACKS
# (In a real system this is async w/ retries)
wait_for_acks(participants)
self.wal.write(gtid, "END")
return decision
The Participant
class Participant:
def __init__(self, name):
self.name = name
self.store = {} # The "Database"
self.locks = set() # Active Locks
self.wal = Log()
self.temp_state = {} # Uncommitted changes
def on_message(self, msg_type, gtid, payload=None):
if msg_type == "PREPARE":
# Simulation: Randomly fail or check locks
if self.is_locked(payload['key']):
return "VOTE_ABORT"
# Lock and log
self.locks.add(payload['key'])
self.temp_state[gtid] = payload
self.wal.write(gtid, "PREPARED")
return "VOTE_COMMIT"
elif msg_type == "COMMIT":
if gtid in self.temp_state:
# Apply to real DB
data = self.temp_state.pop(gtid)
self.store[data['key']] = data['val']
self.locks.remove(data['key'])
self.wal.write(gtid, "COMMITTED")
return "ACK"
elif msg_type == "ROLLBACK":
if gtid in self.temp_state:
data = self.temp_state.pop(gtid)
self.locks.remove(data['key'])
self.wal.write(gtid, "ABORTED")
return "ACK"
5. Handling Failures (The "Simulation" Features)
To make this a true simulation, the system must support Chaos Injection.
A. Coordinator Failure
- Scenario: Coordinator crashes after writing
GLOBAL_COMMIT onto disk but before sending messages.
- Recovery: On reboot, Coordinator reads WAL. Finds
GLOBAL_COMMIT but no END. It re-sends COMMIT messages to all participants.
- Simulation: A
ChaosMonkey function kills the Coordinator thread at specific lines of code.
B. Participant Failure (The Blocking Problem)
- Scenario: Participant A votes
COMMIT then crashes.
- State: It is in the "In-Doubt" state. It knows it can commit, but doesn't know if it should.
- Recovery: On reboot, it reads WAL. Finds
PREPARED. It must poll the Coordinator: "What happened to transaction GTID?"
- Blocking: While Participant A is down or In-Doubt, the locks it holds are frozen. Other transactions attempting to access those keys will halt.
C. Network Partition (Packet Loss)
- Scenario: Coordinator sends
COMMIT, but the network drops the packet to Participant B.
- Resolution:
- Participant B times out waiting for decision → Polling mechanism (Termination Protocol).
- Coordinator times out waiting for
ACK → Retries sending COMMIT.
6. Simulation Dashboard / API
To visualize the system, provide a simple CLI or Web UI output:
start_tx(key, val): Kicks off the workflow.
inject_failure(node, phase): E.g., inject_failure('Coordinator', 'POST_WAL_PRE_SEND').
get_status(): Returns the current state of locks and values on all nodes.
Example Output trace:
[COORD] Starting TX 101
[COORD] Sent PREPARE to [Node A, Node B]
[Node A] Lock acquired. VOTE_COMMIT.
[Node B] **SIMULATED FAILURE: DISK FULL**
[Node B] VOTE_ABORT.
[COORD] Received [COMMIT, ABORT]. Decision: ROLLBACK.
[COORD] Sent ROLLBACK to [Node A, Node B]
[Node A] Releasing locks. ACK.
[Node B] Releasing locks. ACK.
[COORD] TX 101 Finished. Result: Failed.
7. Summary of Limitations (Simulation vs Reality)
- Blocking: This simulation highlights the biggest flaw of 2PC. If the Coordinator fails permanently while Participants are in the
PREPARED state, the Participants are stuck indefinitely (they cannot unlock).
- Throughput: The extensive message passing (4 messages per node per transaction) creates high latency, which this simulation should monitor via timestamps.