Enhance health check endpoint #1115
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR introduces a patch to the current
health_check
endpoint to address potential performance and semantic issues.Problem
Performance
The
health_check
view executes a potentially expensive operation, specificallyPetition.objects.count()
. Under the hood, Django runsSELECT COUNT(*)...
, which steps through each record one by one. For an endpoint that's hit frequently - depending on the number of rows in your table - this becomes computationally expensive and introduces unnecessary overhead.Semantics
Beyond performance, the semantics of the current code could be misleading. Given no assignment, it seems we don't need to do anything with the count. In addition, executing
<model>.objects.count()
returns anint
. If there are no records in the DB for thePetition
model, we simply return0
. This means we may never even raise based on the code we execute in the try block.Yes, from a broader database connectivity perspective, this can be considered logically correct - the DB being down, disconnected, the table doesn't exist, etc., will raise an exception. However, the current code doesn't easily express or infer this intent.
Solution
This update alternatively replaces the unnecessary overhead query and executes a pure database connection check. It's lightweight since we bypass the ORM and only interact with the database connection layer. It's expressive enough to communicate intent at first glance.
Disclaimer: If more is required from this health check, like ensuring we can execute a query, then this solution is insufficient. Prefer
cursor.execute("SELECT 1")
or<model>.objects.exists()
as better yet, non-expensive alternatives in this respect.Motivation
I enjoy giving back to open-source projects I either use or have learned from a thing or two.
Type of change
Checklist: