AlgoViz

Two-stage processing

medium 30 min

Two-stage processing, known as two-phase commit (2PC), makes several databases commit or abort together.

See it run

Votes, decision, and every place where somebody can crash.

Operations

Commit

All three databases vote yes.

Step 1 of 7

Transaction request

Coordinatorstarts t1DB1idleDB2idleDB3idle

Init

A client starts a transaction over three databases.

Step 1: Transaction request

def run(tx):    votes = [p.prepare(tx) for p in participants]    if all(votes):        log("COMMIT", tx)        tell_all("commit", tx)    else:        log("ABORT", tx)        tell_all("abort", tx)    wait_for_acks(tx)
Rounds
2
Locks held
Until commit
Local commit
no round trips

The commit counts from the moment it is in the coordinator's log.

In the real world

The same two-phase commit doing real jobs. Pick one and step through it.

A team keeps adding participants to one transaction.

Step 1 of 4

Two databases

PREPAREPREPARECoordinatorwaitingDB1ordersDB2stockDB3unused

About 5 ms of locks

Fast enough. Both are in the same data centre.

Step 1: Two databases

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Voting yes before the log is on disk

    critical

    After a crash the promise is gone, and the others have committed.

    Wrong
    vote("YES")wal.write("PREPARE")
    Right
    wal.write("PREPARE")wal.flush()vote("YES")
  • Guessing when in doubt

    critical

    Half of the databases may have the other outcome.

    Wrong
    on_timeout: abort()   # after a yes
    Right
    on_timeout: ask_coordinator()            ask_others()            wait()
  • Reporting failure after COMMIT

    critical

    The transaction is committed. The client retries and buys twice.

    Wrong
    except SendError:    return False
    Right
    except SendError:    keep_retrying(tx)return True
  • Not watching prepared transactions

    major

    A forgotten one holds locks for days and survives restarts.

    Wrong
    # no dashboard
    Right
    alert_if(prepared_age > minutes(5))

Interview tips

  • How to explain it

    • Ask everyone, then tell everyone.
    • All yes, or abort.
    • Atomic, but blocking.
  • Memory trick: PREP

    • Prepare asks all to vote.
    • Response is yes or no.
    • Execute commit if all said yes.
    • Persist logs.
  • Good fit

    • Few databases.
    • Close together.
    • Short work.
  • Use something else

    • Microservices: a saga.
    • Long work: a saga.
    • High availability: consensus groups.