Django Queryset Extremely Slow on RDS

I’m facing a strange performance issue with one of my Django API endpoints connected to AWS RDS PostgreSQL.

  • The endpoint is very slow (8–11 seconds) when accessed without any query parameters.
  • If I pass a specific query param like type=sale, it becomes even slower.
  • Oddly, the same endpoint with other types (e.g., type=expense) runs fast (~100ms).
  • The queryset uses:
    • .select_related() on from_account, to_account, party, etc.
    • .prefetch_related() on some related image objects.
    • .annotate() for conditional values and a window function (Sum(...) OVER (...)).
    • .distinct() at the end to avoid duplicates from joins.

Behavior:

  • Works perfectly and consistently on localhost Postgres and EC2-hosted Postgres.
  • Only on AWS RDS, this slow behavior appears, and only for specific types like sale.

My Questions:

  1. Could the combination of .annotate() (with window functions) and .distinct() be the reason for this behavior on RDS?
  2. Why would RDS behave differently than local/EC2 Postgres for the same queryset and data?
  3. Any tips to optimize or debug this further?

Would appreciate any insight or if someone has faced something similar.

1 Like

Hello there!
RDS is a set of abstractions on top of a virtual machine.
So the performance can depend on a lot of different things.
That depends on the instance being used on AWS, the amount of CPU credits or Burst balance available for the instance and many others.
I suggest that you go into the AWS web console, and check on the “Monitoring” and “Logs & Events” tabs to verify if there are any warnings, or low “balance” of the credits for that instance.

Basically, these AWS services are, the more you pay, the less pain you have.

If you have any further issues or questions, feel free to report them. It would be nice to also have more details about the setup.

Cheers,

To add onto what @leandrodesouzadev already said, you should also check the queries your endpoint is performing when used on AWS RDS.

You could either use something django-debug-toolbar, call the .explain() method on your queries to look at the underlining SQL, et.c.

Perhaps there is an issue that arises with certain data when not working on localhost, that would explain why certain query params are slow, while others are much faster.