Skip to content

Transactions, even if they would be slow #4598

Open

Description

@ha1331

Feature request or an idea that could be a feature at some point. I would love to have them for those cases when you absolutely need them. Like ecommerce applications or similar use cases.

My understanding from the discussions I have had with @danielmewes is, that transaction in general could be slow and not trivial to implement. I personally would love to have them even if it would mean, that they are indeed slow. Kind of like majority reads. I think there is more value in having slow transactions than not having them at all. I cant say if implementing them is actually worth the trouble, but my thinking is, that transactions could be one of those big features people coming from SQL world expect to have.

I wrote this because "felixis" came to #rethinkdb and asked about them and @AtnNn pointed out, that he wasn't able to find feature request for them.

Activity

  1. thelinuxlich commented on Jul 29, 2015

    @thelinuxlich

    Maybe a poor man's distributed lock?

  2. mlucy commented on Jul 29, 2015

    @mlucy
    Member

    We should definitely consider doing this.

    (It is worth noting that in many cases you can denormalize your data to prevent the need for multi-document transactions, although obviously this doesn't work for e.g. transactions across 2 user accounts.)

  3. added this to the subsequent milestone on Jul 29, 2015
  4. danielmewes commented on Jul 29, 2015

    @danielmewes
    Member

    I think this would be really interesting. Probably not super easy to do, but we should think about it.

    We would probably need a distributed locking mechanism plus something akin to 2 or 3 phase commit (#1863 (comment) has an implmenetation of that in ReQL by @nviennot).

  5. frankleng commented on Aug 16, 2015

    @frankleng

    +1

  6. robertjpayne commented on Aug 29, 2015

    @robertjpayne
    Contributor

    This would be amazing, even if it has some pretty harsh restrictions and was slow there's a few places it would just be magical to have an all or nothing multi-document write.

  7. mike-marcacci commented on Sep 11, 2015

    @mike-marcacci

    Hey there, I've been trying to think through this for some time, and have discovered that getting the RQL semantics right for transactions is extremely difficult, even when ignoring the actual implementation details. In particular, RQL (and all functional languages) are built for parallism, and have rather poor ergonomics when dealing with sequence. I'm going to just record some of my thoughts here to get the conversation moving, and possibly save somebody else the trouble of getting at least this far.

    To start off, I'll make one assumption: rethinkdb transactions should be confined to a single query. Because RQL is so expressive, I don't think we need to take on the complexity of SQL's multi-query, connection-scoped transaction model. The SQL model would put cluster performance at the mercy of whatever else happens in the app during the transaction, and it would be difficult to implement on multiplexed rethinkdb connections. Furthermore, distributed locks are so easy for an application to implement these days (I had node-redlock in production the same day I started it) that rethinkdb can focus on query atomicity instead of worrying about application-level concurrency tools.

    My following examples can be assumed to begin with:

    'use strict';
    
    var sender_id   = 'mike';
    var receiver_id = 'james';
    var amount      = 500.00;
    
    // ...

    Transactions Wrappers

    This is probably what most people think about when coming from the SQL world, where a set of update requests are wrapped in a "transaction" block:

    r.transaction(function(tx) {
        var sender   = r.table('accounts').get(sender_id);
        var receiver = r.table('accounts').get(receiver_id);
    
        return r.table('transfers').insert({
            sender_id: sender_id,
            receiver_id: receiver_id,
            amount: amount
        })
        .do(function(transfer) {
            // ...sub amount from sender
            // ...add amount to receiver
    
            // update the transfer?
        })
    
    });

    Problem: Ambiguity

    This looks really simple at first, but quickly breaks down as you realize that the variables sender and receiver are stateless queries, not the tables themselves. Under MVCC, it's unclear what happens in the following scenario:

    1. get the sender (state A)
    2. update the sender (state B)
    3. reference the sender object <-- does this return state A or B?

    Because the transaction has not been committed, an argument can be made for serving state A; because you're inside the same transaction, an equally valid argument can be made for serving state B.

    Problem: Multiple Writes

    It's unclear if the transfer object could be updated after it is inserted.

    Explicit Locks

    This feels much more clean to me, and alleviates some of the ambiguity of Problem #1: just like .update() RQL function, the returned tables are atomic records, not queries. In the following example, it's clear that last_sender_balance will use the starting balance of the sender.

    r.lock(r.table('accounts').get(sender_id), r.table('accounts').get(receiver_id), function(sender, receiver) {
        return {
            sender: sender.update({ balance: sender('balance').sub(amount) }),
            receiver: receiver.update({
                balance: receiver('balance').add(amount),
                last_sender_balance: sender('balance')    // <-- this will be the starting balance
            })
        };
    });

    Problem: Write Order

    Both models allow for something like this:

    r.lock(r.table('accounts').get(sender_id), r.table('accounts').get(receiver_id), function(sender, receiver) {
        return {
            sender_tx_one: sender.update({ balance: 10 }),
            sender_tx_two: sender.update({ balance: 5 })
        };
    });

    Will the sender's balance be 10 or 5? Because there is no key order guarantee to JSON, there is no consistent answer. While this example doesn't make any sense, this situation is bound to be encountered. This could probably be detected, and an error thrown.

    Aborting, Recovering & Nesting

    Regardless of the transaction creation syntax, we will need a way to "rollback" or "abort" the current transaction. Because rethinkdb is so flexible, there will innevitably be requests to detect aborted transactions, and this could open the door to nested locks (if that's even theoretically possible, not sure yet).

    r.attempt

    Expanding on r.branch for transactions:

    r.attempt(
        r.transaction(function() {
            //...
        }),
        function(result) { return 'it succeeded'; },
        function(error) { return 'it failed'; }
    );

    .catch

    Perhaps a more generic form of .default could work here:

        r.lock(r.table('accounts').get(sender_id), r.table('accounts').get(receiver_id), function(sender, receiver) {
            //...
        }).catch(function(error) {
            return 'it failed';
        })

    After many hours thinking this through, I'm still pretty much undecided at every level. I think that the biggest challenge here is designing the language to be intuitive and consistent, and I think understanding everybody's use cases is the place to start. RQL is so versatile that it risks becoming very general purpose... which may or may not be a good thing.

  8. danielmewes commented on Sep 17, 2015

    @danielmewes
    Member

    This is an awesome write-up @mike-marcacci .

    I wonder if we could do something simpler and more constrained to solve the issue of atomic multi-document writes.

    Here's a very rough idea of something that might be an option, though we could probably make the interface nicer:

    r.updateAtomically(precondition, [table1, key1, updateValue1], [table2, key2, updateValue2], ...)

    A call to updateAtomically could either complete or fail. If it completes, it guarantees that

    1. precondition held at some point in time
    2. while precondition kept holding, the documents to all supplied keys in the supplied tables were updated (or inserted) to their respective update values

    If it fails, it guarantees that none of the updates were performed.

    The argument types would be restricted as follows, in order to make sure that the semantics are easier to reason about:

    • precondition is a function that doesn't perform a write. In order to guarantee the semantics of updateAtomically, it should also not use any non-deterministic terms other than reading from a table (e.g. not r.uuid, sample or r.http). For implementing the updateAtomically command, we would probably extract all tables that the function accesses, and establish a simple table lock on those.
    • tableX is a value of type TABLE, i.e. r.db(...).table(...)
    • keyX is the primary key value. It must be a literal, and cannot be a subquery itself
    • updateValueX must be an object value. For simplicity let's say that it must be a constant literal as well. Specifically it cannot depend on the previous value of the document (though we could probably lift parts of that restriction).

    updateAtomically would behave similar to a multi-document check-and-set operation, except that the precondition is more flexible.

    So you would call this function like this:

    sender_balance = r.table('accounts').get(sender_id)('balance').run();
    receiver_balance = r.table('accounts').get(receiver_id)('balance').run();
    precondition = function() {
        // Make sure that the balance hasn't changed since we've retrieved the documents
        return r.table('accounts').get(sender_id)('balance').eq(sender_balance)
                    .and(r.table('accounts').get(receiver_id)('balance').eq(receiver_balance));
    };
    
    // Update the sender and receiver documents atomically
    success = r.updateAtomically(
      precondition,
      [r.table('accounts'), sender_id, {balance: sender_balance - transfer_amount}],
      [r.table('accounts'), receiver_id, {balance: receiver_balance + transfer_amount}]).run().
    
    if (!success) {
     // Fail, or start over...
    }
  9. marshall007 commented on Sep 17, 2015

    @marshall007
    Contributor

    @danielmewes building off r.updateAtomically, I think we could simply if even further:

    r.atomic(task1, task2, ..., taskN)
    

    Where taskN can be an arbitrary ReQL expression (that can be proved deterministic) or a callback function that will be invoked with the result of the previous operation (or undefined for the first task). The nice thing about this is you can get rid of the dedicated precondition argument and still keep the usefulness of that concept.

    Your example could then be rewritten as:

    r.atomic(
      r.table('accounts').get(sender_id)('balance'),
      function (sender_balance) {
        return r.table('accounts').get(sender_id).update({balance: sender_balance - transfer_amount});
      },
      r.table('accounts').get(receiver_id)('balance'),
      function (receiver_balance) {
        return r.table('accounts').get(receiver_id).update({balance: receiver_balance  - transfer_amount});
      }
    )
  10. 8 remaining items

  11. kofalt commented on May 31, 2016

    @kofalt

    @danielmewes Any chance of seeing this on the roadmap? The latest features from the RDB team have been stellar, but many of us still pine for transactions to safely manipulate our data.

    If any form of atomic multi-document manipulation were implemented I'd be absolutely ecstatic. This could be full-blown transactions - I naively envision the ideal feature as an array of arbitrary commands, similar in nature to BEGIN TRANSACTION, and the database locks whatever it needs to make it happen - but a simple version could have a narrower scope.

    I'd be willing to learn just about any syntax or limitations to get off the ground. Balancing transactional features with horizontal scaling is also clearly a challenge - I suspect several users, like myself, would be willing to trade some of that for this feature.

    I realize that the team has a lot of priorities to juggle and are pulled in many directions, and I greatly prefer quality over speed (and the RDB teams seems to have accomplished both!), but it would be great to have a rough idea where this falls on the next week / next year / next decade / never spectrum.

  12. ha1331 commented on May 31, 2016

    @ha1331
    Author

    Would also love to see this feature or even get some kind of estimation when or if this is going to be implemented. I would settle for "stupidly slow" ones too, because transactions or getting around them are pretty much the last cause of head scratching for my projects and rethink. I feel just being able to trust that all or nothing happened, would be pretty darn valuable. If I got to choose any feature to be added, this surely would be it.

  13. danielmewes commented on Jun 1, 2016

    @danielmewes
    Member

    I think this is a super interesting and useful feature, but also quite hard to implement.

    Even if we ignore performance and lock contention, we will still need to implement a distributed commit protocol, including the ability to either rollback or replay commits on startup after a crash.

    I think a realistic estimate for this is about a year from now.

  14. modified the milestones: subsequent, backlog on Jun 1, 2016
  15. kofalt commented on Jun 1, 2016

    @kofalt

    Thanks Daniel! That's great to hear 😄

  16. elifarley commented on Jun 2, 2016

    @elifarley

    Once they publish their (open) source code, we could borrow some ideas from Consus.

    Consus can commit a transaction across multiple data centers in three wide-area message delays during regular execution. Simply sending a message to a remote data center and receiving acknowledgement of its receipt---the bare minimum necessary to tolerate a data center failure---requires two message delays. Protocols such as 2-phase commit or Paxos require two round trips, or four message delays.

  17. lukeholder commented on Jul 14, 2016

    @lukeholder

    /remindme to check in on rethinkDB in about a year

  18. xfg commented on Jul 14, 2016

    @xfg

    +1

  19. milanvlacil commented on Jul 16, 2016

    @milanvlacil

    +1

  20. xfg commented on Jul 20, 2016

    @xfg

    Check out this neumino/thinky#529 too

  21. danielmewes commented on Jul 20, 2016

    @danielmewes
    Member

    @xfg That's an interesting link in that issue. http://rystsov.info/2012/09/01/cas.html could be implemented on top of RethinkDB for sure.

    @Suvitruf Thanks for the link to the paper. I'll have a look.

  22. ansarizafar commented on Jul 18, 2017

    @ansarizafar

    It is a must have feature. RethinkDb can rule NoSQL DB world with this feature. Any update?

  23. rushmorem commented on Feb 17, 2018

    @rushmorem
    Member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions