Make agent heartbeat endpoint asynchronous for faster response

Changed heartbeat database update from synchronous to async using Task.start.
This reduces response time from ~20ms to <1ms by not waiting for the
database write to complete before sending the response.

The heartbeat is a fire-and-forget operation where the agent doesn't
need confirmation that the update succeeded.

In test environment, it remains synchronous to avoid DB ownership issues.
This commit is contained in:
Graham McIntire 2026-01-14 17:01:57 -06:00
parent 749efe4798
commit 0ed82c47b9
No known key found for this signature in database

View file

@ -116,8 +116,15 @@ defmodule ToweropsWeb.Api.AgentController do
}
end
# Update synchronously in the heartbeat endpoint
Agents.update_agent_token_heartbeat(agent_token.id, ip, metadata)
# In test environment, update synchronously to avoid DB ownership issues
# In production, update asynchronously for better performance
if Application.get_env(:towerops, :env) == :test do
Agents.update_agent_token_heartbeat(agent_token.id, ip, metadata)
else
Task.start(fn ->
Agents.update_agent_token_heartbeat(agent_token.id, ip, metadata)
end)
end
# Return response in appropriate format
case get_req_header(conn, "content-type") do