Skip to content

Optimize the python driver's serialization code. #4569

Closed

Description

@sontek

Currently if you want to work with 100,000 records it is extremely slow:

$ python foo.py 
count is 164717
int query took 4086ms

4 seconds to query 164,000 rows! I dug into this a little bit using the python library yappi and the tool kcachegrind to see where it was spending the time. Here is the python code I used:

import rethinkdb as r
import random
import pytz
import time
import yappi
from datetime import datetime

UTC = pytz.utc

YAPPI = False
DO_CREATE = False
DO_INSERTS = False

conn = r.connect()

if DO_CREATE:
    r.table_create('test').run(conn)

START_BIGINT = 100000000000000000
END_BIGINT = 999999999999999999


def utc_now():
    now = datetime.utcnow()
    tz_now = now.replace(tzinfo=UTC)
    return tz_now


def get_rint(start=1000000, end=9999999):
    """
    Generate a very large integer
    :return:
    """
    return random.randint(start, end)


def get_bigint():
    """
    Generate a random BIGINT
    :return:
    """
    return get_rint(start=START_BIGINT, end=END_BIGINT)


if DO_INSERTS:
    for i in range(0, 300000):
        r.table('test').insert({
            'respondent_id': get_bigint(),
            'row_id': get_bigint(),
            'column_id': get_bigint(),
            'value_id': get_bigint(),
            'rid1': get_bigint(),
            'rid2': get_bigint(),
            'rid3': get_rint(),
            'now': utc_now()
        }).run(conn)

start = time.time()

if YAPPI:
    yappi.set_clock_type('cpu')
    yappi.start(builtins=True)

result = r.table('test').run(conn)
data = []
for row in result:
    data.append(row)

count = len(data)
end = time.time()

if YAPPI:
    stats = yappi.get_func_stats()
    stats.save('callgrind.out', type='callgrind')
    print('checkout callgrind.out')

print("count is %s" % count)
duration = int(1000 * (end - start))
print("int query took %sms" % duration)

and this showed that most of the time is spent in recursively_convert_pseudo_types, here is a screenshot of the kcachegrind:

screenshot from 2015-07-23 13 06 13

Activity

  1. danielmewes commented on Jul 23, 2015

    @danielmewes
    Member

    Thank you for the script and data @sontek !
    We'll look into it and see if we can optimize that function.

  2. added this to the milestone on Jul 23, 2015
  3. deontologician commented on Jul 23, 2015

    @deontologician
    Contributor

    One avenue might be to write a custom JSONDecoder that does pseudotype conversion at parse time. If we did that it would open the door to #3506

  4. sontek commented on Jul 23, 2015

    @sontek
    ContributorAuthor

    Yeah, I think having a JSONDecoder will be a great approach (I've monkeypatched it to use simplejson to get 5% perf boost) but until we convert that function to use a while loop instead of recursion then JSON actually isn't the slow part yet

  5. deontologician commented on Jul 23, 2015

    @deontologician
    Contributor

    I was thinking in lieu of having the recursive function at all. So it would do the work of that recursive function during the initial parse. Right now it does everything in two passes, the second one being slow because of function call overhead in the recursive pseudotype conversion

  6. sontek commented on Jul 23, 2015

    @sontek
    ContributorAuthor

    So I changed the query to be:

    result = r.table('test').map(r.row.to_json_string()).run(conn)

    so skip the slow function and it shaved off 50% of my time but was still pretty slow so there are some other gains to be had in other areas:

    screenshot from 2015-07-23 16 03 46

  7. modified the milestones: , on Aug 11, 2015
  8. coffeemug commented on Aug 24, 2015

    @coffeemug
    Contributor

    For anyone watching this thread, we're doing an on-the-wire performance test (without the Python driver) to figure out baseline server performance for this workload. Once we get this information, it will be relatively easy to figure out what we need to do to fix this.

  9. danielmewes commented on Aug 25, 2015

    @danielmewes
    Member

    The raw server performance for a single client reading the data, measured without any parsing on the client-side, is approximately 0.8 seconds per 100,000 documents.

    This is using the documents generated by the script above, just slightly modified to store a more compact unix timestamp rather than a ReQL date/time object in the now field.

    In this test, all data gets transferred to the client, but the client doesn't parse the response (except for a small header).

    @sontek would that be fast enough or do you need higher single-client throughput?
    I imagine that we might be able to do some more tuning on the server side for this workload.

  10. sontek commented on Aug 25, 2015

    @sontek
    ContributorAuthor

    @danielmewes Does that scale out linearly? Whats it at for 50,000 and 500,000? I think 0.8 seconds would be acceptable as long as the python driver overhead wasn't adding much on top of that. Another thing we could look at is building out an async query model like:

    import rethinkdb as r
    conn = r.connect()
    
    futures = []
    
    for i in range(0, 2):
        future = r.table('boom').filter(
            lambda row: row['id'] % 2 == i
         ).run_async(conn)
        futures.append(future)
    
    for f in futures:
        f.join()

    So if we know the queries scale linearly we can asynchronously spawn the queries off to get the desired query speed. So if there are 200k results set, in that example I would still expect to wait no more than 0.8 seconds to get the data.

  11. 13 remaining items

  12. danielmewes commented on Sep 14, 2015

    @danielmewes
    Member

    For the between, we tested with splitting the queries up by primary index rather than by using a secondary index. Not sure if that explains the difference.

  13. coffeemug commented on Sep 14, 2015

    @coffeemug
    Contributor

    Also note that this use case (returning a large resultset) isn't yet well parallelizable across shards. We're working on this now, and it will go into 2.2 (due out in about a month). So right now you won't see the benefit of sharding on this use case, but you will see a large benefit after 2.2 is out.

  14. sontek commented on Sep 18, 2015

    @sontek
    ContributorAuthor

    After talking with @danielmewes a bit yesterday I tried to do a few benchmarks:

    1. Difference between single node vs multi-node cluster
    2. No full table scans, use a secondary index on all queries.
    3. Between vs Filter
    4. Threads vs Processes

    This is my results:

    screenshot from 2015-09-18 10 10 16

    You can see it pretty much always slows down from 1 to 4 nodes, here is the actual data:

    # Full table scan (SELECT * FROM ..)
    int query took 15740ms
    int query took 14524ms
    int query took 14466ms
    int query took 14285ms
    
    # Filter single query single node
    int query took 19005ms
    int query took 18482ms
    int query took 18220ms
    int query took 24998ms
    
    
    # Between single query single node
    int query took 15970ms
    int query took 15818ms
    int query took 15878ms
    int query took 15700ms
    
    
    # Multi-threaded single query
    int query took 11077ms
    int query took 11609ms
    int query took 10852ms
    int query took 11621ms
    
    
    # Multi-processes single query
    int query took 15251ms
    int query took 15907ms
    int query took 14677ms
    int query took 14374ms
    
    
    
    
    # Full table scan (SELECT * FROM ..) 4 nodes
    int query took 18882ms
    int query took 16515ms
    int query took 17638ms
    int query took 16100ms
    
    
    # Filter single query 4 nodes
    int query took 20862ms
    int query took 20141ms
    int query took 20481ms
    int query took 19868ms
    
    
    # Between single query 4 nodes
    int query took 23500ms
    int query took 24951ms
    int query took 24233ms
    int query took 24213ms
    
    
    # Multi-threaded 4 nodes
    int query took 12882ms
    int query took 12124ms
    int query took 12317ms
    int query took 11718ms
    
    # Multi-processes 4 nodes
    int query took 15131ms
    int query took 14618ms
    int query took 15284ms
    int query took 15193ms
    

    This is the code:

    import rethinkdb as r
    import random
    import rapidjson
    import pytz
    import time
    import yappi
    from datetime import datetime
    from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
    UTC = pytz.utc
    
    YAPPI = False
    DO_CREATE = False
    DO_INSERTS = False
    SERVER = "mt1-rethinkd1c1"
    TABLE = "test2"
    
    class RapidJsonDecoder(object):
        def __init__(self, reql_format_opts):
            pass
    
        def decode(self, s):
            return rapidjson.loads(s)
    
    def create_decoder(format_opts):
        return RapidJsonDecoder(format_opts)
    
    conn = r.connect(SERVER)
    conn._get_json_decoder = create_decoder
    
    
    if DO_CREATE:
        r.table_create(TABLE).run(conn)
    
    START_BIGINT = 100000000000000000
    END_BIGINT = 999999999999999999
    
    
    def utc_now():
        now = datetime.utcnow()
        tz_now = now.replace(tzinfo=UTC)
        return tz_now.timestamp()
    
    
    def get_rint(start=1000000, end=9999999):
        """
        Generate a very large integer
        :return:
        """
        return random.randint(start, end)
    
    
    def get_bigint():
        """
        Generate a random BIGINT
        :return:
        """
        return get_rint(start=START_BIGINT, end=END_BIGINT)
    
    
    if DO_INSERTS:
        objects_to_insert = []
    
        for i in range(0, 1000000):
            objects_to_insert.append({
                'survey_id': get_rint(start=1, end=4),
                'respondent_id': get_bigint(),
                'row_id': get_bigint(),
                'column_id': get_bigint(),
                'value_id': get_bigint(),
                'rid1': get_bigint(),
                'rid2': get_bigint(),
                'rid3': get_rint(),
                'now': utc_now()
            })
    
            if i % 4000 == 0:
                r.table(TABLE).insert(objects_to_insert).run(conn)
                objects_to_insert = []
    
        r.table(TABLE).insert(objects_to_insert).run(conn, noreply=True, durability="soft")
    
    start = time.time()
    
    if YAPPI:
        yappi.set_clock_type('cpu')
        yappi.start(builtins=True)
    
    
    def query(survey_id):
        data = []
        tconn = r.connect("mt1-rethinkd1c1")
        tconn._get_json_decoder = create_decoder
        results = r.table(TABLE).filter({'survey_id': survey_id}).run(tconn)
    
        for result in results:
            data.append(result)
    
        return data
    
    def get_multi_proc(use_threads=True):
        futures = []
    
        if use_threads:
            klass = ThreadPoolExecutor
        else:
            klass = ProcessPoolExecutor
    
        with klass(max_workers=4) as executor:
            for i in range(1, 5):
                future = executor.submit(query, i)
                futures.append(future)
    
            data = []
    
        for future in futures:
            data += future.result()
    
        return data
    
    def get_single():
        # select all
        data = []
    #    result = r.table(TABLE).run(conn)
        result = r.table(TABLE).between(1, 5, index='survey_id').run(conn)
    #    result = r.table(TABLE).filter(
    #        (r.row['survey_id'] >= 1) & (r.row['survey_id'] <= 4)
    #    ).run(conn)
    
        for row in result:
            data.append(row)
    
        return data
    
    
    #data = get_single()
    #data = get_multi_proc()
    data = get_multi_proc(use_threads=False)
    
    count = len(data)
    end = time.time()
    
    if YAPPI:
        stats = yappi.get_func_stats()
        stats.save('callgrind.out', type='callgrind')
        print('checkout callgrind.out')
    
    print("count is %s" % count)
    duration = int(1000 * (end - start))
    print("int query took %sms" % duration)

    I have a secondary index on survey_id.

    Here is a google drive excel document with the numbers in it:

    https://docs.google.com/spreadsheets/d/1kfyt9DjYrZwXowCVx4eSA7kLUrgK6oYvgbmtoOnXsTE/edit?usp=sharing

  15. sontek commented on Sep 18, 2015

    @sontek
    ContributorAuthor

    I'm not able to reproduce that 500ms per 100k resultsets you were able to get. The fastest I'm able to get is with the threaded worker which gets be down to 11seconds for 1million records

  16. danielmewes commented on Sep 18, 2015

    @danielmewes
    Member

    The difference in performance could be because of hardware differences. We'll re-test this with a configuration closer to yours.

  17. modified the milestones: 2.2, on Oct 5, 2015
  18. modified the milestones: 2.2, on Nov 13, 2015
  19. danielmewes commented on Nov 17, 2015

    @danielmewes
    Member

    I'm marking this closed. The prominent inefficiencies in the Python driver have been addressed in the past few releases.

    @sontek I'll contact you directly in the next days regarding any additional testing and/or bottlenecks.

  20. modified the milestones: outdated, on Nov 17, 2015
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

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions