I have a simple get query
key = TenantKey.objects.get(pk=api_key)
When I'm running a load test, for many requests the above query is taking multiple seconds (max 15s) which is very strange. So I ran a raw sql query equivalent to the above ORM like below
with connection.cursor() as cursor:
cursor.execute("SELECT app_tenantkey.key_id, app_tenantkey.name FROM app_tenantkey WHERE app_tenantkey.value=%s",[key])
row = cursor.fetchone()
Surprisingly this query was way faster than the ORM which is what we were expecting as the table is very small and contains about 20 entries.
I'm also attaching the max durations of both queries just FYI
The ORM query is taking almost 100x when compared to time taken by the raw query in similar situation. I want to understand what's causing the ORM is taking so long while the raw is quick.
I figured what the issue was, it turns out that the issue was not with django's ORM. The real issue was DNS name resolution to the DB. This Query was the first query to the DB that's the reason why only this line took multiple seconds while other query's were running as expected.