Performance

How can I profile a SQLAlchemy powered application?

Looking for performance issues typically involves two strategies. Oneis query profiling, and the other is code profiling.

Query Profiling

Sometimes just plain SQL logging (enabled via python’s logging moduleor via the echo=True argument on create_engine()) can give anidea how long things are taking. For example, if you log somethingright after a SQL operation, you’d see something like this in yourlog:

  1. 17:37:48,325 INFO [sqlalchemy.engine.base.Engine.0x...048c] SELECT ...
  2. 17:37:48,326 INFO [sqlalchemy.engine.base.Engine.0x...048c] {<params>}
  3. 17:37:48,660 DEBUG [myapp.somemessage]

if you logged myapp.somemessage right after the operation, you knowit took 334ms to complete the SQL part of things.

Logging SQL will also illustrate if dozens/hundreds of queries arebeing issued which could be better organized into much fewer queries.When using the SQLAlchemy ORM, the “eager loading”feature is provided to partially (contains_eager()) or fully(joinedload(), subqueryload())automate this activity, but withoutthe ORM “eager loading” typically means to use joins so that results across multipletables can be loaded in one result set instead of multiplying numbersof queries as more depth is added (i.e. r + rr2 + rr2*r3 …)

For more long-term profiling of queries, or to implement an application-side“slow query” monitor, events can be used to intercept cursor executions,using a recipe like the following:

  1. from sqlalchemy import event
  2. from sqlalchemy.engine import Engine
  3. import time
  4. import logging
  5.  
  6. logging.basicConfig()
  7. logger = logging.getLogger("myapp.sqltime")
  8. logger.setLevel(logging.DEBUG)
  9.  
  10. @event.listens_for(Engine, "before_cursor_execute")
  11. def before_cursor_execute(conn, cursor, statement,
  12. parameters, context, executemany):
  13. conn.info.setdefault('query_start_time', []).append(time.time())
  14. logger.debug("Start Query: %s", statement)
  15.  
  16. @event.listens_for(Engine, "after_cursor_execute")
  17. def after_cursor_execute(conn, cursor, statement,
  18. parameters, context, executemany):
  19. total = time.time() - conn.info['query_start_time'].pop(-1)
  20. logger.debug("Query Complete!")
  21. logger.debug("Total Time: %f", total)

Above, we use the ConnectionEvents.before_cursor_execute() andConnectionEvents.after_cursor_execute() events to establish an interceptionpoint around when a statement is executed. We attach a timer onto theconnection using the _ConnectionRecord.info dictionary; we use astack here for the occasional case where the cursor execute events may be nested.

Code Profiling

If logging reveals that individual queries are taking too long, you’dneed a breakdown of how much time was spent within the databaseprocessing the query, sending results over the network, being handledby the DBAPI, and finally being received by SQLAlchemy’s result setand/or ORM layer. Each of these stages can present their ownindividual bottlenecks, depending on specifics.

For that you need to use thePython Profiling Module.Below is a simple recipe which works profiling into a context manager:

  1. import cProfile
  2. import io
  3. import pstats
  4. import contextlib
  5.  
  6. @contextlib.contextmanager
  7. def profiled():
  8. pr = cProfile.Profile()
  9. pr.enable()
  10. yield
  11. pr.disable()
  12. s = io.StringIO()
  13. ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
  14. ps.print_stats()
  15. # uncomment this to see who's calling what
  16. # ps.print_callers()
  17. print(s.getvalue())

To profile a section of code:

  1. with profiled():
  2. Session.query(FooClass).filter(FooClass.somevalue==8).all()

The output of profiling can be used to give an idea where time isbeing spent. A section of profiling output looks like this:

  1. 13726 function calls (13042 primitive calls) in 0.014 seconds
  2.  
  3. Ordered by: cumulative time
  4.  
  5. ncalls tottime percall cumtime percall filename:lineno(function)
  6. 222/21 0.001 0.000 0.011 0.001 lib/sqlalchemy/orm/loading.py:26(instances)
  7. 220/20 0.002 0.000 0.010 0.001 lib/sqlalchemy/orm/loading.py:327(_instance)
  8. 220/20 0.000 0.000 0.010 0.000 lib/sqlalchemy/orm/loading.py:284(populate_state)
  9. 20 0.000 0.000 0.010 0.000 lib/sqlalchemy/orm/strategies.py:987(load_collection_from_subq)
  10. 20 0.000 0.000 0.009 0.000 lib/sqlalchemy/orm/strategies.py:935(get)
  11. 1 0.000 0.000 0.009 0.009 lib/sqlalchemy/orm/strategies.py:940(_load)
  12. 21 0.000 0.000 0.008 0.000 lib/sqlalchemy/orm/strategies.py:942(<genexpr>)
  13. 2 0.000 0.000 0.004 0.002 lib/sqlalchemy/orm/query.py:2400(__iter__)
  14. 2 0.000 0.000 0.002 0.001 lib/sqlalchemy/orm/query.py:2414(_execute_and_instances)
  15. 2 0.000 0.000 0.002 0.001 lib/sqlalchemy/engine/base.py:659(execute)
  16. 2 0.000 0.000 0.002 0.001 lib/sqlalchemy/sql/elements.py:321(_execute_on_connection)
  17. 2 0.000 0.000 0.002 0.001 lib/sqlalchemy/engine/base.py:788(_execute_clauseelement)
  18.  
  19. ...

Above, we can see that the instances() SQLAlchemy function was called 222times (recursively, and 21 times from the outside), taking a total of .011seconds for all calls combined.

Execution Slowness

The specifics of these calls can tell us where the time is being spent.If for example, you see time being spent within cursor.execute(),e.g. against the DBAPI:

  1. 2 0.102 0.102 0.204 0.102 {method 'execute' of 'sqlite3.Cursor' objects}

this would indicate that the database is taking a long time to start returningresults, and it means your query should be optimized, either by adding indexesor restructuring the query and/or underlying schema. For that task,analysis of the query plan is warranted, using a system such as EXPLAIN,SHOW PLAN, etc. as is provided by the database backend.

Result Fetching Slowness - Core

If on the other hand you see many thousands of calls related to fetching rows,or very long calls to fetchall(), it maymean your query is returning more rows than expected, or that the fetchingof rows itself is slow. The ORM itself typically uses fetchall() to fetchrows (or fetchmany() if the Query.yield_per() option is used).

An inordinately large number of rows would be indicatedby a very slow call to fetchall() at the DBAPI level:

  1. 2 0.300 0.600 0.300 0.600 {method 'fetchall' of 'sqlite3.Cursor' objects}

An unexpectedly large number of rows, even if the ultimate result doesn’t seemto have many rows, can be the result of a cartesian product - when multiplesets of rows are combined together without appropriately joining the tablestogether. It’s often easy to produce this behavior with SQLAlchemy Core orORM query if the wrong Column objects are used in a complex query,pulling in additional FROM clauses that are unexpected.

On the other hand, a fast call to fetchall() at the DBAPI level, but thenslowness when SQLAlchemy’s ResultProxy is asked to do a fetchall(),may indicate slowness in processing of datatypes, such as unicode conversionsand similar:

  1. # the DBAPI cursor is fast...
  2. 2 0.020 0.040 0.020 0.040 {method 'fetchall' of 'sqlite3.Cursor' objects}
  3.  
  4. ...
  5.  
  6. # but SQLAlchemy's result proxy is slow, this is type-level processing
  7. 2 0.100 0.200 0.100 0.200 lib/sqlalchemy/engine/result.py:778(fetchall)

In some cases, a backend might be doing type-level processing that isn’tneeded. More specifically, seeing calls within the type API that are sloware better indicators - below is what it looks like when we use a type likethis:

  1. from sqlalchemy import TypeDecorator
  2. import time
  3.  
  4. class Foo(TypeDecorator):
  5. impl = String
  6.  
  7. def process_result_value(self, value, thing):
  8. # intentionally add slowness for illustration purposes
  9. time.sleep(.001)
  10. return value

the profiling output of this intentionally slow operation can be seen like this:

  1. 200 0.001 0.000 0.237 0.001 lib/sqlalchemy/sql/type_api.py:911(process)
  2. 200 0.001 0.000 0.236 0.001 test.py:28(process_result_value)
  3. 200 0.235 0.001 0.235 0.001 {time.sleep}

that is, we see many expensive calls within the type_api system, and the actualtime consuming thing is the time.sleep() call.

Make sure to check the Dialect documentationfor notes on known performance tuning suggestions at this level, especially fordatabases like Oracle. There may be systems related to ensuring numeric accuracyor string processing that may not be needed in all cases.

There also may be even more low-level points at which row-fetching performance is suffering;for example, if time spent seems to focus on a call like socket.receive(),that could indicate that everything is fast except for the actual network connection,and too much time is spent with data moving over the network.

Result Fetching Slowness - ORM

To detect slowness in ORM fetching of rows (which is the most common areaof performance concern), calls like populate_state() and _instance() willillustrate individual ORM object populations:

  1. # the ORM calls _instance for each ORM-loaded row it sees, and
  2. # populate_state for each ORM-loaded row that results in the population
  3. # of an object's attributes
  4. 220/20 0.001 0.000 0.010 0.000 lib/sqlalchemy/orm/loading.py:327(_instance)
  5. 220/20 0.000 0.000 0.009 0.000 lib/sqlalchemy/orm/loading.py:284(populate_state)

The ORM’s slowness in turning rows into ORM-mapped objects is a productof the complexity of this operation combined with the overhead of cPython.Common strategies to mitigate this include:

  • fetch individual columns instead of full entities, that is:
  1. session.query(User.id, User.name)

instead of:

  1. session.query(User)
  • Use Bundle objects to organize column-based results:
  1. u_b = Bundle('user', User.id, User.name)
  2. a_b = Bundle('address', Address.id, Address.email)
  3.  
  4. for user, address in session.query(u_b, a_b).join(User.addresses):
  5. # ...
  • Use result caching - see Dogpile Caching for an in-depth exampleof this.

  • Consider a faster interpreter like that of PyPy.

The output of a profile can be a little daunting but after somepractice they are very easy to read.

See also

Performance - a suite of performance demonstrationswith bundled profiling capabilities.

I’m inserting 400,000 rows with the ORM and it’s really slow!

The SQLAlchemy ORM uses the unit of work pattern when synchronizingchanges to the database. This pattern goes far beyond simple “inserts”of data. It includes that attributes which are assigned on objects arereceived using an attribute instrumentation system which trackschanges on objects as they are made, includes that all rows insertedare tracked in an identity map which has the effect that for each rowSQLAlchemy must retrieve its “last inserted id” if not already given,and also involves that rows to be inserted are scanned and sorted fordependencies as needed. Objects are also subject to a fair degree ofbookkeeping in order to keep all of this running, which for a verylarge number of rows at once can create an inordinate amount of timespent with large data structures, hence it’s best to chunk these.

Basically, unit of work is a large degree of automation in order toautomate the task of persisting a complex object graph into arelational database with no explicit persistence code, and thisautomation has a price.

ORMs are basically not intended for high-performance bulk inserts -this is the whole reason SQLAlchemy offers the Core in addition to theORM as a first-class component.

For the use case of fast bulk inserts, theSQL generation and execution system that the ORM builds on top ofis part of the Core. Using this system directly, we can produce an INSERT thatis competitive with using the raw database API directly.

Note

When using the psycopg2 dialect, consider making use of thebatch execution helpers feature of psycopg2,now supported directly by the SQLAlchemy psycopg2 dialect.

Alternatively, the SQLAlchemy ORM offers the Bulk Operationssuite of methods, which provide hooks into subsections of the unit ofwork process in order to emit Core-level INSERT and UPDATE constructs witha small degree of ORM-based automation.

The example below illustrates time-based tests for several differentmethods of inserting rows, going from the most automated to the least.With cPython 2.7, runtimes observed:

  1. SQLAlchemy ORM: Total time for 100000 records 6.89754080772 secs
  2. SQLAlchemy ORM pk given: Total time for 100000 records 4.09481811523 secs
  3. SQLAlchemy ORM bulk_save_objects(): Total time for 100000 records 1.65821218491 secs
  4. SQLAlchemy ORM bulk_insert_mappings(): Total time for 100000 records 0.466513156891 secs
  5. SQLAlchemy Core: Total time for 100000 records 0.21024107933 secs
  6. sqlite3: Total time for 100000 records 0.137335062027 sec

We can reduce the time by a factor of nearly three using recent versions of PyPy:

  1. SQLAlchemy ORM: Total time for 100000 records 2.39429616928 secs
  2. SQLAlchemy ORM pk given: Total time for 100000 records 1.51412987709 secs
  3. SQLAlchemy ORM bulk_save_objects(): Total time for 100000 records 0.568987131119 secs
  4. SQLAlchemy ORM bulk_insert_mappings(): Total time for 100000 records 0.320806980133 secs
  5. SQLAlchemy Core: Total time for 100000 records 0.206904888153 secs
  6. sqlite3: Total time for 100000 records 0.165791988373 sec

Script:

  1. import time
  2. import sqlite3
  3.  
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from sqlalchemy import Column, Integer, String, create_engine
  6. from sqlalchemy.orm import scoped_session, sessionmaker
  7.  
  8. Base = declarative_base()
  9. DBSession = scoped_session(sessionmaker())
  10. engine = None
  11.  
  12.  
  13. class Customer(Base):
  14. __tablename__ = "customer"
  15. id = Column(Integer, primary_key=True)
  16. name = Column(String(255))
  17.  
  18.  
  19. def init_sqlalchemy(dbname='sqlite:///sqlalchemy.db'):
  20. global engine
  21. engine = create_engine(dbname, echo=False)
  22. DBSession.remove()
  23. DBSession.configure(bind=engine, autoflush=False, expire_on_commit=False)
  24. Base.metadata.drop_all(engine)
  25. Base.metadata.create_all(engine)
  26.  
  27.  
  28. def test_sqlalchemy_orm(n=100000):
  29. init_sqlalchemy()
  30. t0 = time.time()
  31. for i in xrange(n):
  32. customer = Customer()
  33. customer.name = 'NAME ' + str(i)
  34. DBSession.add(customer)
  35. if i % 1000 == 0:
  36. DBSession.flush()
  37. DBSession.commit()
  38. print(
  39. "SQLAlchemy ORM: Total time for " + str(n) +
  40. " records " + str(time.time() - t0) + " secs")
  41.  
  42.  
  43. def test_sqlalchemy_orm_pk_given(n=100000):
  44. init_sqlalchemy()
  45. t0 = time.time()
  46. for i in xrange(n):
  47. customer = Customer(id=i + 1, name="NAME " + str(i))
  48. DBSession.add(customer)
  49. if i % 1000 == 0:
  50. DBSession.flush()
  51. DBSession.commit()
  52. print(
  53. "SQLAlchemy ORM pk given: Total time for " + str(n) +
  54. " records " + str(time.time() - t0) + " secs")
  55.  
  56.  
  57. def test_sqlalchemy_orm_bulk_save_objects(n=100000):
  58. init_sqlalchemy()
  59. t0 = time.time()
  60. for chunk in range(0, n, 10000):
  61. DBSession.bulk_save_objects(
  62. [
  63. Customer(name="NAME " + str(i))
  64. for i in xrange(chunk, min(chunk + 10000, n))
  65. ]
  66. )
  67. DBSession.commit()
  68. print(
  69. "SQLAlchemy ORM bulk_save_objects(): Total time for " + str(n) +
  70. " records " + str(time.time() - t0) + " secs")
  71.  
  72.  
  73. def test_sqlalchemy_orm_bulk_insert(n=100000):
  74. init_sqlalchemy()
  75. t0 = time.time()
  76. for chunk in range(0, n, 10000):
  77. DBSession.bulk_insert_mappings(
  78. Customer,
  79. [
  80. dict(name="NAME " + str(i))
  81. for i in xrange(chunk, min(chunk + 10000, n))
  82. ]
  83. )
  84. DBSession.commit()
  85. print(
  86. "SQLAlchemy ORM bulk_insert_mappings(): Total time for " + str(n) +
  87. " records " + str(time.time() - t0) + " secs")
  88.  
  89.  
  90. def test_sqlalchemy_core(n=100000):
  91. init_sqlalchemy()
  92. t0 = time.time()
  93. engine.execute(
  94. Customer.__table__.insert(),
  95. [{"name": 'NAME ' + str(i)} for i in xrange(n)]
  96. )
  97. print(
  98. "SQLAlchemy Core: Total time for " + str(n) +
  99. " records " + str(time.time() - t0) + " secs")
  100.  
  101.  
  102. def init_sqlite3(dbname):
  103. conn = sqlite3.connect(dbname)
  104. c = conn.cursor()
  105. c.execute("DROP TABLE IF EXISTS customer")
  106. c.execute(
  107. "CREATE TABLE customer (id INTEGER NOT NULL, "
  108. "name VARCHAR(255), PRIMARY KEY(id))")
  109. conn.commit()
  110. return conn
  111.  
  112.  
  113. def test_sqlite3(n=100000, dbname='sqlite3.db'):
  114. conn = init_sqlite3(dbname)
  115. c = conn.cursor()
  116. t0 = time.time()
  117. for i in xrange(n):
  118. row = ('NAME ' + str(i),)
  119. c.execute("INSERT INTO customer (name) VALUES (?)", row)
  120. conn.commit()
  121. print(
  122. "sqlite3: Total time for " + str(n) +
  123. " records " + str(time.time() - t0) + " sec")
  124.  
  125. if __name__ == '__main__':
  126. test_sqlalchemy_orm(100000)
  127. test_sqlalchemy_orm_pk_given(100000)
  128. test_sqlalchemy_orm_bulk_save_objects(100000)
  129. test_sqlalchemy_orm_bulk_insert(100000)
  130. test_sqlalchemy_core(100000)
  131. test_sqlite3(100000)