Optimistic locking inside a transaction (Ecto.Multi)

In our application we have a code like below in Elixir:

      Multi.new()
  |> Multi.update(
    :some_operation_name,
    Entity
    |> Repo.preload(:some_entity)
    |> Ecto.Changeset.optimistic_lock(:lock_version)
    |> Ecto.Changeset.change(some_id: some_uuid)
  )
   |> Repo.transaction()

We are using MYSql database, I find this code a little bit strange because it is using optimistic_locking inside a transation,I am wondering if we might run into issues because of using optimistic_locking inside a transction (pessimistic locking).

A transaction essentially means “everything succeeds or nothing succeeds”, and although locking plays a part in determine the success or otherwise many other issues come into play: access control, timeouts, constraints and so on.

So here the optimistic lock may or may not succeed whether a lock of some kind is acquired or not. But if the optimistic lock fails, you want all of the multi steps to rollback, which is what the transaction will accomplish.

MySQL uses REPEATABLE_READ as the default isolation level so another transaction may have updated the optmistic lock column while the current transaction is in process. Therefore the optimistic lock will fail and the transaction would roll back.