Awesome Go

committer

CategoryDistributed Systems
SubcategoryDistributed Systems
Stars45

A distributed transactions management system (2PC/3PC implementation)

About committer

tests Go Reference Go Report Card Mentioned in Awesome Go

Committer

Go implementation of Two-Phase Commit (2PC) and Three-Phase Commit (3PC) for distributed systems.

Use it in two ways:

  • As a demo cluster. Run a replicated key/value store with a protocol visualization — useful for learning how 2PC (and optionally 3PC) behave.
  • As a library. Make one change commit atomically across several services: each service plugs its own storage into the protocol as a Resource.

Quick start (about 60 seconds)

Both options below use two-phase commit to write and read greeting=hello.

git clone https://github.com/vadiminshakov/committer.git
cd committer

Option A — Docker Compose

Requires Docker with Compose:

docker compose up --build --wait
docker compose exec coordinator committer put greeting hello
docker compose exec cohort committer get greeting

Open the protocol visualization. Compose enables the CLI on the coordinator (published at localhost:4000) and starts one coordinator plus two cohorts (cohort, cohort2). Ports 4000 and 8080 must be free.

Stop with docker compose down. Named volumes keep WAL/DB state; docker compose down --volumes deletes them.

Option B — Local one-command demo

Requires Go 1.25+, free ports 3000, 3001, 4000, 4001 and 8080:

make build
./bin/committer demo

In another terminal:

./bin/committer put greeting hello
./bin/committer get greeting

Open localhost:8080. demo starts a coordinator and one cohort with the CLI and visualization enabled. Press Ctrl+C in the demo terminal to stop.

put records a durable COMMIT decision; cohorts apply it asynchronously. The get command retries briefly so a read right after put usually succeeds.

Client commands

--addr / -addr is the node's protocol -addr. put goes to a coordinator (default localhost:3000) and get to a cohort (default localhost:3001). The CLI dials that address's port + 1000 (printed when a node starts with -cli). If a node uses -cli-addr instead, pass the same address to the command's -cli-addr flag.

./bin/committer put greeting hello
./bin/committer get greeting
./bin/committer put -timeout 10s greeting "hello world"

Flags must precede key/value arguments. Run ./bin/committer --help or ./bin/committer put -h for details.

Install the binary: go install github.com/vadiminshakov/committer/v2/cmd/committer@latest.

Protocol visualization

The web UI animates protocol messages and shows an event log. It opens in Live (follows new events). Choose Replay to step through a snapshot with Play / Next step / speed controls.

An empty cluster shows the command for your first write. Select a transaction by number, or All transactions in Replay.

Use as a library

go get github.com/vadiminshakov/committer/v2

Start one coordinator and a cohort next to each piece of state that must change atomically (github.com/vadiminshakov/committer/v2/core/cohort and …/core/coordinator):

cohortNode, err := cohort.Start(ctx, cohort.Config{
    Addr:        "localhost:3001",
    Coordinator: "localhost:3000",
    DataDir:     ".data/orders", // WAL; reuse it across restarts
}, ordersDB) // your cohort.Resource
if err != nil {
    return err
}
defer cohortNode.Close()

coord, err := coordinator.Start(coordinator.Config{
    Addr:    "localhost:3000",
    Cohorts: []dto.Addr{"localhost:3001"},
    DataDir: ".data/coordinator",
})
if err != nil {
    return err
}
defer coord.Close()

payload := []byte(`{"status": "paid"}`)

height, err := coord.Commit(ctx, "order-42", payload)
switch {
case errors.Is(err, coordinator.ErrAborted):
    // voting failed; ABORT is durable, safe to retry
case errors.Is(err, coordinator.ErrInvalidTransaction),
     errors.Is(err, coordinator.ErrCoordinatorNotReady):
    // this request did not start; fix its input or recover the coordinator
case err != nil:
    // outcome unknown for now: check coord.Decision(height) later
}

Commit returns once the COMMIT decision is durable; cohorts apply it in the background and keep retrying until they succeed.

Try the full example first: examples/transfer moves money between two banks, each with its own Resource. Run it with:

go run ./examples/transfer

Architecture

           your code
              │ coord.Commit(key, value)
              ▼
        ┌─────────────┐
        │ coordinator │── WAL
        └─────────────┘
          │ gRPC    │
          ▼         ▼
     ┌────────┐ ┌────────┐
     │ cohort │ │ cohort │── WAL
     └────────┘ └────────┘
          │         │
          ▼         ▼
      Resource   Resource      your storage
  • Coordinator assigns each transaction a height (sequence id), collects votes from every cohort, and decides COMMIT or ABORT. A transaction commits only if all cohorts vote YES.
  • Cohort runs the protocol on one node. It does not store your data: it calls your Resource to vote on, apply, or discard each transaction.
  • Resource is your storage behind Prepare / Commit / Abort (below).
  • WAL. Every node logs each protocol step before acting. After a crash the coordinator finishes the interrupted transaction; a cohort repeats its last decision. An in-doubt cohort asks the coordinator for the outcome.

Nodes communicate over gRPC. The committer binary is the same library with a Badger key/value store plugged in as each cohort's resource, plus a small CLI API for put and get.

Resource

At each protocol step the cohort calls the cohort.Resource you pass to cohort.Start:

type Resource interface {
    // Prepare votes on tx: nil is YES, any error is NO. A YES may still
    // end in Abort, but if the decision is COMMIT, Commit is retried
    // until it succeeds, so reserve what it needs now.
    Prepare(ctx context.Context, tx dto.Tx) error
    // Commit applies tx. It must be idempotent.
    Commit(ctx context.Context, tx dto.Tx) error
    // Abort releases height. It must be idempotent and accept unknown heights.
    Abort(ctx context.Context, height uint64) error
}

dto.Tx carries the coordinator-assigned Height (the transaction's id) and the Key/Value payload from coord.Commit; their meaning is up to your resource.

What the cohort guarantees your resource: calls arrive one at a time, in height order. After a restart the cohort repeats the last COMMIT or ABORT. It also calls Abort for the next height: the cohort records its vote in the WAL only after Prepare returns, so a crash in between may leave a reservation it cannot see. That vote never reached the coordinator, so aborting is safe. A failed Commit or Abort is retried.

Finish transactions and Resource calls before closing a cohort. Close() cancels background work without waiting for in-flight Resource calls. If a transaction is interrupted, restart with the same WAL and resource data to recover it.

Advanced: run nodes yourself

make build

# Terminal 1: cohort (pass -cli to serve get)
./bin/committer cohort -coordinator localhost:3000 -cli

# Terminal 2: coordinator (pass -cli to serve put; -viz-port for the UI)
./bin/committer coordinator -cohorts localhost:3001 -cli -viz-port 8080

# Terminal 3
./bin/committer put greeting hello
./bin/committer get greeting

Node commands do not enable the CLI by default — use -cli (or -cli-addr host:port). demo and Docker Compose turn it on for you.

Node configuration

FlagWhoDescriptionDefault
addrbothProtocol listen address, host:portcoordinator: localhost:3000; cohort: localhost:3001
clibothServe put (coordinator) or get (cohort) on the protocol port + 1000off
cli-addrbothServe put/get on this address (overrides the port + 1000 default)empty
coordinatorcohortCoordinator addressrequired
cohortscoordinatorComma-separated cohort addressesrequired
protocolbothtwo-phase or three-phase (-committype is a deprecated alias)two-phase
decision-timeoutcohortHow long the cohort waits for the coordinator's decision: 3PC autocommit delay and in-doubt retry interval1s
data-dirbothRoot for the WAL and a cohort's database.data
viz-portbothProtocol visualization HTTP port; 0 disables it0

Three-phase commit

For 3PC, pass -protocol three-phase to every node (coordinator and all cohorts). Quick start paths stay on 2PC on purpose.

Atomic Commit Protocols

Two-Phase Commit (2PC)

The Two-Phase Commit protocol ensures atomicity in distributed transactions through two distinct phases:

Phase 1: Voting Phase (Propose)

  1. Coordinator sends a PROPOSE request to all cohorts with transaction data
  2. Each Cohort validates the transaction locally and responds:
    • ACK (Yes) - if ready to commit
    • NACK (No) - if unable to commit
  3. Coordinator waits for all responses

Phase 2: Commit Phase

  1. If all cohorts voted ACK:
    • Coordinator sends COMMIT to all cohorts
    • Each Cohort commits the transaction and responds with ACK
  2. If any cohort voted NACK:
    • Coordinator sends ABORT to all cohorts
    • Each Cohort aborts the transaction

Three-Phase Commit (3PC)

The Three-Phase Commit protocol extends 2PC with an additional phase to reduce blocking scenarios:

Phase 1: Voting Phase (Propose)

  1. Coordinator sends PROPOSE request to all cohorts
  2. Cohorts respond with ACK/NACK (same as 2PC)

Phase 2: Preparation Phase (Precommit)

  1. If all cohorts voted ACK:
    • Coordinator sends PRECOMMIT to all cohorts
    • Cohorts acknowledge they're prepared to commit
    • Timeout mechanism: If cohort doesn't receive COMMIT within timeout, it auto-commits
  2. If any cohort voted NACK:
    • Coordinator sends ABORT to all cohorts

Phase 3: Commit Phase

  1. Coordinator sends COMMIT to all cohorts
  2. Cohorts perform the actual commit operation

Contributions

PRs and issues are welcome.

License

Apache License

Frequently Asked Questions

What is committer?

committer is a Distributed Systems library for the Go programming language. A distributed transactions management system (2PC/3PC implementation)

How do I install committer?

Install committer with the Go module system using `go get vadiminshakov/committer`. Check the repository for the current installation instructions.

What category does committer belong to?

committer is listed under Distributed Systems, specifically Distributed Systems.

← Back to Distributed Systems