⚡️ Speed up function heartbeat by 1,139%
#125
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.
📄 1,139% (11.39x) speedup for
heartbeatinskyvern/forge/sdk/routes/agent_protocol.py⏱️ Runtime :
1.16 milliseconds→93.5 microseconds(best of250runs)📝 Explanation and details
The optimization achieves a 1139% speedup by eliminating redundant object creation through response caching. Instead of constructing a new
Responseobject on every request, the optimized version creates a single_HEARTBEAT_RESPONSEobject at module import time and reuses it.Key Performance Impact:
Responseobject, dictionary for headers, and performs string operations on every call (5,822ns per hit). The optimized version simply returns a pre-constructed object (293.8ns per hit).Why This Works for Heartbeat Endpoints:
Heartbeat responses are inherently immutable - they always return the same content, status code, and headers. Since FastAPI handles the actual HTTP response serialization, reusing the same Response object is safe and doesn't affect concurrency.
Test Case Performance:
The optimization excels in all concurrent and high-load scenarios (10-500 concurrent calls), which is exactly what heartbeat endpoints experience in production. The throughput remains constant at 302,750 ops/sec because the async event loop capacity stays the same, but individual request latency drops dramatically.
Production Benefits:
This optimization is particularly valuable for heartbeat endpoints that handle health checks from load balancers, monitoring systems, and service meshes - all of which can generate high-frequency, concurrent requests where this 11x latency reduction significantly improves system responsiveness.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-heartbeat-mirodwi3and push.