0

I am trying that both these functions execute together or not at all. If one func fails then the other shouldn't execute either.

func SomeFunc() error {
    //Write to DB1
    if err1 != nil {
        return err
    }
}

func OtherFunc() error {
    //Write to DB2
    if err2 != nil {
        return err
    }
}

I am trying to write to two different databases and the writes should either happen in both or neither.

I tried having like if err1 == nil then execute Otherfunc() but then Otherfunc() can fail.

Then we can rollback changes like if err2!= nil then Update db1 back to what it was before. Problem with this is that this Update operation may fail too.

I see this as a slippery slope. I want that these operations to happen together or not at all.

Thanks for any help.

EDIT:

I found this question and the "eventual consistency" makes sense to me.

This is my implementation now:

func SomeFunc() error {
    //Write to DB1
    if err1 != nil {
        return err
    }
}

func OtherFunc() error {
    //Write to DB2
    if err2 != nil {
        return err2
    }
}
func RevertSomeFunc() {
    //Revert back changes by SomeFunc
    fmt.Println("operation failed.")
    if err3 != nil {
        time.Sleep(time.Second * 5) //retry every 5 sec
        RevertSomeFunc()
    }
}

func main() {
    err1 := SomeFunc()
    if err1 != nil {
        fmt.Println("operation failed.")
        return
    }
    err2 := OtherFunc()
    if err2 != nil {
        go RevertSomeFunc() // launch it off to a go-routine so that it doesnt block the code.
    }
}

If there is some improvement I can make to this implementation. Please lmk.

YAPS
  • 511
  • 6
  • 7
  • 2
    What you're looking for is https://en.wikipedia.org/wiki/Two-phase_commit_protocol – zerkms Jul 30 '21 at 02:56
  • Thanks for the response. I read about it. It's interesting. I found this question though which answers my doubt though. https://stackoverflow.com/questions/30213456/transactions-across-rest-microservices – YAPS Jul 30 '21 at 03:12

0 Answers0