Using git bisect
to Fix Slow Database Queries
When faced with a performance regression in your application, pinpointing the exact commit that introduced the issue can be daunting. In this article, we'll walk through using git bisect
to identify a specific regression in load times caused by an unindexed database call in a Node.js application.
Step-by-Step Guide
Initial Setup
First, ensure your repository is clean and all changes are committed. This avoids any interference with the bisect process:
git status
Start the Bisect Process
Initialize git bisect
by marking the current commit as bad and a known good commit:
git bisect start
git bisect bad
git bisect good v1.2.0 # Replace v1.2.0 with a known good tag or commit
The Bisect Process
git bisect
will now start checking out different commits. It will continue halving the commit range until the bad commit is found. Let's assume the application has a script or a simple command to measure load times.
Run the following command to check the performance at the current bisected commit:
node load_test.js # Replace with your actual performance testing script
Based on the results, mark the commit as good or bad:
git bisect good # If load times are acceptable
git bisect bad # If load times are slow
Repeat this process for each commit git bisect
checks out.
Finding the Culprit
Suppose after several iterations, git bisect
identifies the bad commit. Let's say the offending commit message is "Added user details fetching logic".
You can view the commit details:
git show <commit-hash>
Examine the changes. Here, you notice an unindexed database call:
// Example of the problematic code in userDetails.js
const userDetails = await db.collection('users').find({ lastName: 'Smith' });
Fixing the Issue
The issue arises from querying the users
collection without an index on the lastName
field. Add an index to improve performance:
// In your database setup script
db.collection('users').createIndex({ lastName: 1 });
Or, if adding an index isn't feasible, optimize the query logic.
Verifying the Fix
After implementing the fix, ensure the performance issue is resolved. Rerun the load test:
node load_test.js
If load times improve, commit the fix:
git add .
git commit -m "Optimized user details fetching by adding index on lastName"
Ending the Bisect Session
Finally, reset the bisect state:
git bisect reset
This returns you to the state before git bisect
was initiated.