Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In CockroachDB, how do batches and transactions interact?

Tags:

go

cockroachdb

When should I use batches and when should I use transactions? Can I embed a transaction in a batch? A batch in a transaction?

like image 214
Ben Darnell Avatar asked Jun 03 '15 20:06

Ben Darnell


1 Answers

A batch is a collection of operations that are sent to the server as a single unit for efficiency. It is equivalent to sending the same operations as individual requests from different threads. Requests in a batch may be executed out of order, and it's possible for some operations in a batch to succeed while others fail.

In Go, batches are created with the batcher object DB.B, and must be passed to DB.Run(). For example:

err := db.Run(db.B.Put("a", "1").Put("b", "2"))

is equivalent to:

_, err1 := db.Put("a", "1")
_, err2 := db.Put("b", "2")

A transaction defines a consistent and atomic sequence of operations. Transactions guarantee consistency with respect to all other operations in the system: the results of a transaction cannot be seen unless and until the transaction is committed. Since transactions may need to be retried, transactions are defined by function objects (typically closures) which may be called multiple times.

In Go, transactions are created with the DB.Tx method. The *client.Tx parameter to the closure implements a similar interface to DB; inside the transaction you must perform all your operations on this object instead of the original DB. If your function returns an error, the transaction will be aborted; otherwise it will commit. Here is a transactional version of the previous example (but see below for a more efficient version):

err := db.Tx(func(tx *client.Tx) error {
    err := tx.Put("a", "1")
    if err != nil {
        return err
    }
    return tx.Put("b", "2")
})

The previous example waits for the "a" write to complete before starting the "b" write, and then waits for the "b" write to complete before committing the transaction. It is possible to make this more efficient by using batches inside the transaction. Tx.B is a batcher object, just like DB.B. In a transaction, you can run batches with either Tx.Run or Tx.Commit. Tx.Commit will commit the transaction if and only if all other operations in the batch succeed, and is more efficient than letting the transaction commit automatically when the closure returns. It is a good practice to always make the last operation in a transaction a batch executed by Tx.Commit:

err := db.Tx(func(tx *client.Tx) error {
    return tx.Commit(tx.B.Put("a", "1").Put("b", "2"))
})
like image 80
Ben Darnell Avatar answered Oct 20 '22 21:10

Ben Darnell