Robbie Ardiansyah
← All work

Reports, 190x faster

Three report generators in a Django reporting service for a retail loyalty programme were slow enough to be a problem. I led the work to fix them by moving the computation from Python into the database.

Best case
41.91s → 0.22s
Reports
3 generators
Built with
Python, Django ORM

01The problem

The reports covered point expirations and reward redemptions. They were written the straightforward way: fetch rows, loop over them in Python, look up related data as you go, add things up. That's fine with a few hundred rows. With a real programme's data it means many round trips to the database and a lot of Python doing what the database does better.

02The decision

Push the work down to the database and let Python receive results, not raw material:

  • Queryset annotations to compute per-row values in SQL instead of in a loop.
  • Coalesce to handle missing values inside the query, so Python doesn't have to patch nulls row by row.
  • values() to fetch only the columns the report uses rather than full model instances.
  • select_related to join related tables in one query instead of one lookup per row.

I applied the same approach to each generator in turn and measured each one.

03Result

ReportBeforeAfterSpeedup
Expiration journal41.91s0.22s~190x
Expiration log7.10s0.12s~57x
Redemption details5.73s0.11s~53x

This isn't Android work, and that's why it's here. The habit is the same on either platform: find where the work actually happens, measure it, and move it to the layer that's built for it.