Sobes.tech
Middle

How does two-phase commit (2PC) work?

sobes.tech AI

Answer from AI

Two-phase commit (2PC) is a protocol for ensuring the atomicity of distributed transactions.

It consists of two phases:

  1. Prepare phase: The coordinator sends a request to all participants to prepare for commit. Participants perform all necessary checks and operations, lock resources, but do not finalize changes, and respond with 'ready' or 'not ready'.

  2. Commit/abort phase: If all participants respond 'ready', the coordinator sends a commit command; otherwise, it aborts.

Thus, either all participants commit changes or all abort, ensuring consistency.

An example of simplified logic in Go:

// Pseudocode
func twoPhaseCommit(participants []Participant) error {
    for _, p := range participants {
        if !p.Prepare() {
            // if someone is not ready, abort
            for _, p2 := range participants {
                p2.Abort()
            }
            return errors.New("prepare failed")
        }
    }
    for _, p := range participants {
        p.Commit()
    }
    return nil
}
How does two-phase commit (2PC) work? — Golang - sobes.tech