Distributed Transaction Saga

1. NP Challenge

In distributed system, we might experience the NPC Problem which NPC stand for Network Delay and Process Pauce

  1. Network Delay: Sometime due to network delay, an network send first might not get arrived first.
  2. Process Pause: Somtimes a process might pause due to garbage collectoin suspend all running threads, which cause some process might slow execute due to this

2. Three Problem

  1. Empty Compensation: When Compensate execute, but the branch operation has not executed. Compensate must detect that branch operation has not run and does nothing and simply return
  2. Dangling: When the branch operation executes, Compensate has already finished. The branch operatoin must detect that Compensation has already run, in which case it does nothing and simply returns.
  3. Idempotence: Since any request may hit a network anamaly and end up being sent moer thatn once, every distributed transaction branch operation must guarantee idempotence.

3. Eventual Sucess

Some operations must ultimately succeed. If they don’t succeed for the moment, they are retried repeatedly until they finally return success. For example, Compensation operations in SAGA.

4. Barrier

The principle behind the barrier technique is to maintain a branch-operation state table, dtm_barrier, in the local database, with a unique key of global transaction id - branch id - branch operation (action | compensate).

  1. Begin the local transaction.
  2. For the current operation op (action | compensate), insert ignore a row gid-branchid-op. If the insert doesn’t succeed, commit the transaction and return success (idempotence control).
  3. If the current operation is compensate, then insert ignore a row gid-branchid-action. If that insert succeeds (note: succeeds), commit the transaction and return success (empty-compensation control).
  4. Execute the branch’s business logic. If the business logic returns success, commit the transaction and return success; if it returns failure, roll back the transaction and return failure.

Anti-dangling control — if action executes after compensate, then compensate will have inserted gid-branchid-action in step 3, causing action’s insert in step 2 to fail. The branch business logic is therefore not executed, which achieves anti-dangling control.

5. Go Implementation of Barrier

          POST /transfer  (from, to, amount)
                  │
                  ▼
        ┌───────────────────┐
        │  AP  :7001        │  coordinator: drives both branches,
        │  ap/main.go       │  decides when to compensate
        └─────────┬─────────┘
          │               │      POST /adjust_balance (account, amount)
          ▼               ▼
  ┌──────────────┐ ┌──────────────┐
  │ RM A  :1234  │ │ RM B  :5678  │  two "banks" — same binary, two ports.
  │  rm/main.go  │ │  rm/main.go  │  Each just does balance += amount and
  └──────┬───────┘ └───────┬──────┘  knows nothing about transactions.
         └────────┬────────┘
                  ▼
          PostgreSQL  :5432
       bank_account  +  barrier

Start Postgres with Docker

docker run -d --name barrier-pg -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:18-alpine
docker exec barrier-pg sh -c 'until pg_isready -U postgres -q; do sleep 1; done'

Create the database and table

docker exec barrier-pg createdb -U postgres barrier
docker exec barrier-pg psql -U postgres -d barrier \
  -c 'CREATE TABLE bank_account (
        id              bigserial   PRIMARY KEY,
        user_id         integer     NOT NULL UNIQUE,
        balance         integer     NOT NULL,
        trading_balance integer     NOT NULL DEFAULT 0,
        create_time     timestamptz NOT NULL DEFAULT now(),
        update_time     timestamptz NOT NULL DEFAULT now()
      );' \
  -c 'CREATE TABLE barrier (
        id          bigserial    PRIMARY KEY,
        op          varchar(100) NOT NULL UNIQUE,
        create_time timestamptz  NOT NULL DEFAULT now()
      );' \
  -c 'INSERT INTO bank_account (user_id, balance) VALUES (1, 100), (2, 100);'

dao/bank_account.go - This is used for connect to postgres and provide dao to adjust balance

package dao

import (
	"database/sql"
	"errors"
	"log"
	"os"
	"sync"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

const defaultDSN = "postgres://postgres:postgres@127.0.0.1:5432/barrier?sslmode=disable"

func dsn() string {
	if url := os.Getenv("DATABASE_URL"); url != "" {
		return url
	}
	return defaultDSN
}

var (
	dbOnce sync.Once
	db     *sql.DB
)

func GetDB() *sql.DB {
	dbOnce.Do(func() {
		var err error
		db, err = sql.Open("pgx", dsn())
		if err != nil {
			log.Panicf("cannot open postgres: %s", err)
		}
		// Branches block on each other inside the barrier, so each in-flight
		// branch holds a connection. Keep the pool comfortably larger than the
		// number of concurrent branches.
		db.SetMaxOpenConns(20)
		db.SetMaxIdleConns(10)
		db.SetConnMaxLifetime(time.Hour)
		if err = db.Ping(); err != nil {
			log.Panicf("cannot reach postgres at %s: %s", dsn(), err)
		}
	})
	return db
}

func AdjustBalance(uid int, delta int) error {
	db := GetDB()
	result, err := db.Exec(
		"update bank_account set balance = balance + $1 where user_id = $2 and balance + $1 >= 0",
		delta, uid)
	if err != nil {
		log.Printf("failed to adjust the account balance: %s", err)
		return err
	}
	affected, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if affected == 0 {
		return errors.New("the balance would go negative, or the uid does not exist")
	}
	return nil
}

rm/main.go - This is used to spin up two banks, which on port 1234, 5678, and the purpose is to expose /adjust_balance endpoint and access the dao above to adjust balance

package main

import (
	"flag"
	"log"
	"net/http"
	"strconv"

	"github.com/Fulim13/barrier-saga-demo/dao"
	"github.com/gin-gonic/gin"
)

// TransReq is a request to change one account's balance.
type TransReq struct {
	Account int `form:"account" binding:"gt=0,required"`
	Amount  int `form:"amount" binding:"required"`
}

func AdjustBalance(ctx *gin.Context) {
	var req TransReq
	if err := ctx.ShouldBind(&req); err != nil {
		log.Printf("failed to bind the request parameters: %s", err)
		ctx.String(http.StatusBadRequest, "failed to bind the request parameters")
		return
	}
	if err := dao.AdjustBalance(req.Account, req.Amount); err != nil {
		log.Printf("failed to adjust the balance of account %d: %s", req.Account, err)
		ctx.String(http.StatusInternalServerError, "failed to adjust the account balance")
		return
	}
	log.Printf("account %d, adjusted by %d", req.Account, req.Amount)
	ctx.String(http.StatusOK, "")
}

func main() {
	port := flag.Int("port", 1234, "http server port")
	flag.Parse()

	engine := gin.Default()
	engine.POST("/adjust_balance", AdjustBalance)
	engine.Run("127.0.0.1:" + strconv.Itoa(*port))
}

ap/main.go

package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/Fulim13/barrier-saga-demo/dao"
	"github.com/gin-gonic/gin"
	"github.com/rs/xid"
)

const (
	// Money is moved between an account at bank A and an account at bank B.
	bankAURL         = "http://localhost:1234"
	bankBURL         = "http://localhost:5678"
	transOutBranchID = "trans_out_branchid"
	transInBranchID  = "trans_in_branchid"
	forward          = "action"
	backward         = "compensate"
)

type TransReq struct {
	FromUid int `form:"from" binding:"gt=0,required"`   // account the money leaves
	ToUid   int `form:"to" binding:"gt=0,required"`     // account the money arrives in
	Amount  int `form:"amount" binding:"gt=0,required"` // amount to move
}

// postForm sends a form-encoded POST request.
func postForm(reqURL string, account, amount int) error {
	data := url.Values{"account": []string{strconv.Itoa(account)}, "amount": []string{strconv.Itoa(amount)}}
	request, err := http.NewRequest(http.MethodPost, reqURL, strings.NewReader(data.Encode()))
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	client := http.Client{
		Timeout: time.Second,
	}
	resp, err := client.Do(request)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	bs, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		return errors.New(string(bs))
	}
	return nil
}

func barrier(ctx *gin.Context, tx *sql.Tx, branchID string, opName string) bool {
	return Barrier(tx, ctx.GetString("gid"), branchID, opName)
}

// Barrier inserts "<gid>-<branchID>-<op>" into the barrier table, which has a
// unique index on that column.
func Barrier(tx *sql.Tx, gid, branchID, op string) bool {
	// Different keys never interfere with each other. For the same key, one
	// transaction blocks the other until the first one finishes -- that wait is
	// what makes an in-flight branch and its compensation see a consistent view.
	result, err := tx.Exec(
		"insert into barrier (op) values ($1) on conflict (op) do nothing",
		fmt.Sprintf("%s-%s-%s", gid, branchID, op))
	affected, err := result.RowsAffected()
	if err != nil {
		log.Printf("cannot read the affected row count: %s", err)
		return false
	}
	return affected > 0
}

// transOut moves money out of the account at bank A.
func transOut(ctx *gin.Context, req *TransReq) error {
	tx, err := dao.GetDB().BeginTx(context.Background(), nil)
	if err != nil {
		return err
	}
	// Idempotency control and With transOutComp it also guarantee anti-hanging
	// (1) Even before a transaction has committed or rolled back, if another transaction tries to write the same `gid-branchid-op`,
	// it will block until the first transaction commits or rolls back.
	if !barrier(ctx, tx, transOutBranchID, forward) {
		tx.Commit() // commit or rollback, either is fine: the insert did nothing anyway
		// The barrier stopped us, so this branch already ran and store in db. Report success.
		return nil
	}

	log.Printf("about to transfer out")
	err = postForm(bankAURL+"/adjust_balance", req.FromUid, -req.Amount)
	if err == nil {
		log.Printf("transfer out succeeded")
		return tx.Commit()
	}
	log.Printf("transfer out failed")
	tx.Rollback()
	return err
}

// transOutComp compensates the transfer out.
func transOutComp(ctx *gin.Context, req *TransReq) {
	tx, err := dao.GetDB().BeginTx(context.Background(), nil)
	if err != nil {
		log.Printf("cannot start the compensation transaction: %s", err)
		return
	}
	defer tx.Commit()
	// Idempotency control.
	if !barrier(ctx, tx, transOutBranchID, backward) {
		return
	}
	// Empty-compensation control: if the forward key can still be inserted, the
	// forward branch never committed, so there is nothing to compensate.
	// (2) Even before a transaction has committed or rolled back, if another transaction tries to write the same `gid-branchid-op`,
	// it will block until the first transaction commits or rolls back.
	if barrier(ctx, tx, transOutBranchID, forward) {
		log.Println("the branch has not run yet, no compensation needed")
		return
	}

	// Else Need to do Compensation
	log.Printf("about to compensate the transfer out")
	// Keep retrying until it finally succeeds.
	// Compensation operations must ultimately succeed.
	// If they don't succeed for the moment,
	// they are retried repeatedly until they finally return success.
	// In practice, failures need to be monitored: once the failure count exceeds a threshold,
	// an alert must fire and an operator must step in to resolve the problem.
	for {
		if postForm(bankAURL+"/adjust_balance", req.FromUid, req.Amount) == nil {
			break
		}
		// Once the failure count crosses a threshold this should raise an alert
		// so that a human operator can step in.
		log.Printf("compensating the transfer out failed, retrying")
		time.Sleep(5 * time.Second)
	}
	log.Printf("compensating the transfer out succeeded")
}

// transIn moves money into the account at bank B.
func transIn(ctx *gin.Context, req *TransReq) error {
	tx, err := dao.GetDB().BeginTx(context.Background(), nil)
	if err != nil {
		return err
	}
	// Idempotency control, and at the same time protection against a dangling action.
	if !barrier(ctx, tx, transInBranchID, forward) {
		tx.Commit()
		// The barrier stopped us, so this branch already ran. Report success.
		return nil
	}

	log.Printf("about to transfer in")
	err = postForm(bankBURL+"/adjust_balance", req.ToUid, req.Amount)
	if err == nil {
		log.Printf("transfer in succeeded")
		return tx.Commit()
	}
	log.Printf("transfer in failed")
	tx.Rollback()
	return err
}

// transInComp compensates the transfer in.
func transInComp(ctx *gin.Context, req *TransReq) {
	tx, err := dao.GetDB().BeginTx(context.Background(), nil)
	if err != nil {
		log.Printf("cannot start the compensation transaction: %s", err)
		return
	}
	defer tx.Commit()
	// Idempotency control.
	if !barrier(ctx, tx, transInBranchID, backward) {
		return
	}
	// Empty-compensation control: if the forward key can still be inserted, the
	// forward branch never committed, so there is nothing to compensate.
	if barrier(ctx, tx, transInBranchID, forward) {
		log.Println("the branch has not run yet, no compensation needed")
		return
	}

	log.Printf("about to compensate the transfer in")
	// Keep retrying until it finally succeeds.
	for {
		if postForm(bankBURL+"/adjust_balance", req.ToUid, -req.Amount) == nil {
			break
		}
		// Once the failure count crosses a threshold this should raise an alert
		// so that a human operator can step in.
		log.Printf("compensating the transfer in failed, retrying")
		time.Sleep(5 * time.Second)
	}
	log.Printf("compensating the transfer in succeeded")
}

func Transfer(ctx *gin.Context) {
	var req TransReq
	if err := ctx.ShouldBind(&req); err != nil {
		log.Printf("failed to bind the request parameters: %s", err)
		ctx.String(http.StatusBadRequest, "failed to bind the request parameters")
		return
	}

	var (
		mu    sync.Mutex
		txErr error
	)
	fail := func(err error) {
		mu.Lock()
		if txErr == nil {
			txErr = err
		}
		mu.Unlock()
		// One (or more) branches failed, so run every compensation. They could
		// also run in parallel; for a transfer the order of the two does not matter.
		transInComp(ctx, &req)
		transOutComp(ctx, &req)
	}

	wg := sync.WaitGroup{}
	wg.Go(func() {
		if err := transOut(ctx, &req); err != nil {
			log.Printf("transfer out failed: %s", err)
			fail(err)
		}
	})
	wg.Go(func() {
		if err := transIn(ctx, &req); err != nil {
			log.Printf("transfer in failed: %s", err)
			fail(err)
		}
	})
	wg.Wait()

	if txErr != nil {
		ctx.String(http.StatusInternalServerError, txErr.Error())
		return
	}
	ctx.String(http.StatusOK, "ok")
}

func GidMW(ctx *gin.Context) {
	ctx.Set("gid", xid.New().String())
	ctx.Next()
}

func main() {
	engine := gin.Default()
	engine.Use(GidMW) // global middleware that assigns every request a fresh global transaction id.
	engine.POST("/transfer", Transfer)
	engine.Run("127.0.0.1:7001")
}

Start three services

go run ./rm -port=1234     # bank A
go run ./rm -port=5678     # bank B
go run ./ap                # coordinator, listens on :7001

Test the endpoint: Transer from 1 to 2 with $1

curl -X POST http://localhost:7001/transfer \
 -F "from=1" \
 -F "amount=1" \
 -F "to=2"

Output: Success

Test the endpoint: Transer from 1 to 2 with $100

curl -X POST http://localhost:7001/transfer \
-F "from=1" \
-F "amount=1000" \
-F "to=2"

Output: Failed. Not Enough Money

Test the endpoint: Kill the bank B

curl -X POST http://localhost:7001/transfer \
-F "from=1" \
-F "amount=1" \
-F "to=2"

Output: Failed. Bank B is not response