Skip to content

python driver connections do not work well with threading #2427

Open

Description

@larkost

The Python driver does not seem to be playing nice with threading, with a variety of problems:

  • Connection is broken exceptions on queries (but subsequent calls can work)
  • No JSON object could be decoded exceptions
  • hanging forever on queries, sometimes seen as a hang on threading.join()

I will be opening a branch on this, and in two subsequent checkins add a test that shows this, then a Proof-of-Concept fix. But there should probably be a discussion around what the proper strategy should be. My initial thoughts on the options:

  1. Explicitly declare that connections belong ONLY to the thread that started them and provide a reasonable exception to this end when people try to use the connection from another thread. This would be fairly easy using threading.local(). A way of making this somewhat easier to use would be to provide a method to clone a thread (i.e.: use the same connection information) from a connection object passed from another thread.
  2. Do the work within the driver to handle passing the thread object within threads. My initial Proof-of-Concept shows that at least the first part of the problem can be solved relatively simply by putting the socket connection in a thread-local object. But there is a lot of thinking that is going to been to be done about what parts of the current net.Connection object should be shared between threads and what should be thread-local, and putting appropriate locks around the former.

Note that a similar conversation is probably going to apply to things using the multiprocessing module. The same solutions can probably work for both types of (semi) concurrent methods, but we would need to confirm that both work.

Activity

  1. larkost commented on May 21, 2014

    @larkost
    CollaboratorAuthor

    I have created a branch to show this: larkost/2427-python-threading-problem, and have the two checkins:
    ab03a97 has the test to show the problem
    6f308bf adds Proof-of-Concept changes to the driver to work-around the parts of the issue exposed in the test

  2. added this to the milestone on May 21, 2014
  3. coffeemug commented on May 21, 2014

    @coffeemug
    Contributor
  4. coffeemug commented on May 21, 2014

    @coffeemug
    Contributor

    and @AtnNn

  5. Tryneus commented on May 21, 2014

    @Tryneus
    Member

    I was under the impression it was clearly stated that our python connection objects are not thread-safe. This behavior is undefined and somewhat expected when running multiple queries on a connection at the same time from different threads. I don't know if we already have an open issue about making our connection objects thread-safe, but @larkost makes some good suggestions. I would be careful about enforcing thread-locality, as some users have certainly built connection pool objects on top of the ReQL driver to pass connections between threads safely.

  6. coffeemug commented on May 21, 2014

    @coffeemug
    Contributor

    I don't know if we already have an open issue about making our connection objects thread-safe

    See #2082. This may or may not be a dup.

    Also, we'll be adding a connection pool API to our drivers soon too. We should keep that in mind (see #281).

  7. Tryneus commented on May 21, 2014

    @Tryneus
    Member

    After talking with @larkost in person, I think this issue should be to make the python connection objects fully thread-safe (that is, we lock and unlock a mutex for the internal socket, and make sure results get to the right reading thread). The other solutions don't play well with our guarantee that 'you see your own writes' and the case where users have built connection pools on top of the driver.

    This is basically the same as #2082, but a little more specific (regarding the python driver).

  8. larkost commented on May 21, 2014

    @larkost
    CollaboratorAuthor

    Should I put up the test for review for inclusion into next? Putting it into tests/regression/known_failures (just like the test for #1774) would make it clear to all that this is a known issue.

  9. coffeemug commented on May 21, 2014

    @coffeemug
    Contributor

    tests/regression/known_failures

    That's a surprisingly pragmatic and delightful idea.

  10. larkost commented on May 21, 2014

    @larkost
    CollaboratorAuthor

    Ok, I will put the test into review. @coffeemug: before either of the tests gets into next (and so creates the directory), do you have any comments on the specific name (i.e.: known_failures)

  11. coffeemug commented on May 21, 2014

    @coffeemug
    Contributor

    To me known_failures sounds good.

  12. larkost commented on May 30, 2014

    @larkost
    CollaboratorAuthor

    I forgot to mention that the review for the test proposed here was 1529. It is ready for checkin, but depends on a could of changes from #1402, and that needs a little more work.

  13. 6 remaining items

  14. sontek commented on Sep 14, 2015

    @sontek
    Contributor

    Has there been any working making this threadsafe? Whats the plan there? Most web applications are going to use the connections in a threaded manner

  15. coffeemug commented on Sep 15, 2015

    @coffeemug
    Contributor

    For multithreaded clients we normally recommend opening a connection per thread (connections in RethinkDB are really really cheap because of the coroutine engine). That tends to work really well, but if people still insist on making the driver thread-safe, it wouldn't be very hard; we can probably do it in a week or so once it's scheduled.

  16. sontek commented on Sep 15, 2015

    @sontek
    Contributor

    @coffeemug I was asking because I was seeing huge performance problems by establishing a connection per thread vs re-using the same connection so I don't think its as cheap as you are thinking it is. I wouldn't insist on re-using the connections in a threadsafe way if it wasn't so slow:

    Here is doing queries with a re-used connection:

    $ python one.py 
    queries took 538ms
    
    $ python one.py 
    queries took 548ms
    
    $ python one.py 
    queries took 547ms
    
    $ python one.py 
    queries took 548ms
    

    and here is a connection per query:

    $ python conns.py 
    queries took 872ms
    
    $ python conns.py 
    queries took 1141ms
    
    ]$ python conns.py 
    queries took 1134ms
    
    $ python conns.py 
    queries took 879ms
    

    Here is the code for each, this is selecting 10 documents so its very tiny queries:

    # one.py
    import rethinkdb as r
    import time
    
    start = time.time()
    conn = r.connect()
    for i in range(1000):
        len([x for x in r.table("boom").run(conn)])
    end = time.time()
    duration = int(1000 * (end - start))
    print("queries took %sms" % duration)
    # conns.py
    import rethinkdb as r
    import time
    
    start = time.time()
    
    for i in range(1000):
        conn = r.connect()
        len([x for x in r.table("boom").run(conn)])
    end = time.time()
    duration = int(1000 * (end - start))
    print("queries took %sms" % duration)
  17. sontek commented on Sep 15, 2015

    @sontek
    Contributor

    @coffeemug and those connections were connecting to a local database, I assume this would be even slower establishing remote connections.

  18. coffeemug commented on Sep 15, 2015

    @coffeemug
    Contributor

    Sorry, I should have been more clear. Establishing a connection isn't that cheap -- it requires a TCP handshake at the very least (which is expensive), and some setup on the server. What I meant by saying "connections are cheap" is that RethinkDB doesn't create a thread per connection, so once established, you can have tens of thousands of connections with very little overhead.

    The code above creates 1k connections (one per query) and even that just doubles the time (which is surprising, I would expect it to be more expensive). But that isn't representative of most multithreaded code -- you wouldn't normally open 1k threads + connections per client per query.

    Each thread would probably run a number of queries on a single connection, so the overhead would be minimal relative to the number of queries run. Additionally, you can always set up a pool, and take connections from the pool as needed to minimize handshake overhead.

    The problem with making the driver thread-safe in Python (or at least, in the defacto CPython implementation) is that the python interpreter would end up being stuck waiting on the GIL for a non-trivial amount of time. Some of the time is spent in native code/syscalls (which doesn't suffer from waiting on the GIL), but much of the code doesn't, so it's not immediately clear that that would be faster than opening a connection per thread.

    We can definitely give it a try, though; if it proves to be faster, it'd be great to merge it into mainline driver.

  19. sontek commented on Sep 15, 2015

    @sontek
    Contributor

    I'm not specifically asking for the connection itself to be thread safe but I don't think implementing thread safety/connection pooling should be an exercise left up to the reader.

    As far as I can tell it is not well documented that thread safety isn't guaranteed, here are the docs I've learned most of the driver stuff from and it never mentions this:

    https://rethinkdb.com/docs/guide/python/
    https://rethinkdb.com/docs/cookbook/python/

    Even here it doesn't mention it under connect: https://rethinkdb.com/api/python/ but does mention it under repl.

    But once you find out that it isn't thread safe your only options are to create a new connection whenever you need them (like my code example) or implement your own thread safe connection pool. I assume most users of the driver are not going to implement the pool and will take the slow route of opening a new connection every request.

    I think one of the primary use cases for rethinkdb is web applications and threaded applications servers are one of the most popular ways to serve web applications so how to use rethinkdb in that way should be a well documented and a supported use case in my opinion.

    For example, this is the first hit on how to use flask with rethinkdb and they open a connection per request:

    https://realpython.com/blog/python/rethink-flask-a-simple-todo-list-powered-by-flask-and-rethinkdb/

    The rethinkdb flask extension itself is thread safe but only because flask is a framework that heavily relies on thread local global magic, for frameworks like pyramid that don't follow those bad practices it'll be less common to accidentally attach to a threadlocal.

    Even code in the rethinkdb does a connection per request:

    https://github.com/rethinkdb/countdown/blob/master/countdown.py

    I think since making the connection has significant overhead that connection pooling should be a first class citizen in the driver.

  20. coffeemug commented on Sep 15, 2015

    @coffeemug
    Contributor

    I don't think implementing thread safety/connection pooling should be an exercise left up to the reader.

    Oh, I definitely agree that an easy to use, canonical, thread-safe connection pool baked into the driver is super-important. We'll try to get that done soon.

    As far as I can tell it is not well documented that thread safety isn't guaranteed.

    That's definitely an oversight -- I've opened rethinkdb/docs#897 to address it.

  21. removed their assignment
    on Sep 15, 2015
  22. jab commented on Nov 17, 2015

    @jab
    Contributor

    Just as a sanity check (in case anyone here can confirm), if you're connecting to Rethinkdb from a Flask app, and using a multithreaded server like uwsgi, Flask-Rethinkdb's use of Flask's _app_ctx_stack should have you covered, right? (IIUC, under the hood, this opens a new connection per thread for you.)

  23. Tryneus commented on Nov 17, 2015

    @Tryneus
    Member
  24. jab commented on Nov 18, 2015

    @jab
    Contributor

    Cool, thanks @Tryneus. (And hope this is helpful to anyone else who sees the warning on https://rethinkdb.com/api/python/connect/ linking to this issue.)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions