What's the simplest solution to my use case?

I’m using FDB to do these things:

  1. set a key and increment it’s counter
  2. if the key already exists in FDB, don’t increment the counter

When I use C bindings and run it concurrently, the transaction conflict occurs.

My codes like:

void put_key(std::string_view key, std::string_view value)
{
  auto tr = make_txn();
  if (tr.get(key)) {
    tr->add_counter_for_key(key); // using fdb_transaction_atomic_op and FDB_MUTATION_TYPE_ADD
  }
  tr->set(key, value);
  tr->commit();
}

Looks like other transactions may write the key when a transaction is reading the key, so there’s conflict.

Is there any problem for my codes, or my solution is not suitable?

I can’t figure out what it is you’re doing. Is add_counter_for_key operating on a key that’s actually key + "counter", or something similar?

Are the transaction conflicts that big of a problem? You should be retrying the operation in the event of a conflict; occasional conflicts are to be expected.

If you’re writing stuff in C(++) you’ll want to write yourself some sort of handler which can retry transactions. Something like: