Repository navigation
Single-flight the agent count refresh to prevent ping stampedes on large stages - #1967
Merged
yongwen merged 1 commit intoAug 19, 2026
Conversation
The agent_counts row is a per-env cache with a ttl, but every ping that observed an expired entry ran both COUNT(*) queries over the env's agents rows before contending for the DEPLOY lock. Because the lock was acquired after the counting, it only guarded the write: on a large stage thousands of concurrent pings each paid for the scans and all but one discarded the result. The two reject paths also returned without writing the cache, so an env sitting at its parallel threshold never refreshed last_refresh, and every subsequent ping rescanned for the remainder of the deploy rather than for a single ttl. Acquire the lock before recounting so at most one ping per env recounts per ttl, let pings that lose the lock defer to their next cycle instead of duplicating the scans, and persist the recount even when the host is not admitted so the expired window stays bounded by the ttl. Test plan: mvn -pl common test -- PingHandlerTest, 27 tests, all passing Co-authored-by: Cursor <cursoragent@cursor.com>
Tweedeldee
approved these changes
Aug 17, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Problem (Why)
agent_countsis a per-env cache with a ttl (agentCountCacheTtl), read at the top ofPingHandler.canDeploy. While the entry is fresh, admission decisions are served from it cheaply. Once it expires, the ping recomputes it with twoCOUNT(*)queries over everyagentsrow belonging to the env.Two defects compound in that expired path. Both are plain from reading the code.
The lock did not protect the expensive work. The
DEPLOY-<envId>lock was acquired after both counts had already run, so it only guarded the write. Every ping arriving while the entry was expired paid for its own pair of scans, and all but the one that won the lock threw the result away.getLockuses a zero timeout, so the losers failed immediately and returned without refreshing anything — a textbook cache stampede.Nothing refreshed the cache while the env was at capacity. Both reject paths returned without writing
agent_counts. A stage pinned at its parallel threshold — the normal steady state for most of a large rollout, particularly whenmaxParallelThresholdcaps the configuredmax_parallel_pct— therefore never updatedlast_refresh. The expired window lasted for the remainder of the deploy rather than a single ttl, so every ping from every waiting host rescanned.Together these mean the expensive path is entered far more often than the ttl implies, and its cost scales with the same variable as the arrival rate into it: a bigger stage means more
agentsrows per scan and more hosts polling.Worth noting separately that
GET_DEPLOYING_TOTALis an expensive scan regardless: its top-levelOR state = 'STOP'prevents use ofagent_first_deploy_state_idx (env_id, first_deploy, deploy_stage, state), so it degenerates into scanning the env's rows and filtering. This PR reduces how often that query runs rather than fixing the query itself.What was observed in production, and how strongly it is attributable
A MySQL primary backing Teletraan saturated CPU in eight windows over ten days, peaking near 90% user CPU in bursts of three to eight minutes. The signature during those bursts is that of an aggregate over a large row set rather than a traffic increase: rows examined per row returned rose from roughly 2.4 to roughly 256, rows read rose about 70x, and threads running went from about 170 to over 13,000, while rows returned to callers and rows changed both stayed flat or dipped slightly. Query volume was not elevated. Cost per query was.
The most suggestive single datapoint is that writes to
agent_countswere measured falling by about half during a spike. That is backwards for any explanation based on load alone, but it is exactly what the second defect above predicts, since the write is skipped precisely when the env sits at capacity.To be explicit about the limits of that attribution: no query digest was captured naming these two
COUNT(*)statements, and no individual deploy has been placed inside a specific saturation window. This PR is therefore best read as fixing a defect that is real in the code and whose signature matches what was measured — not as a proven root cause. Two earlier hypotheses in the same investigation reproduced the observed peak arithmetically and both turned out to be wrong, so the distinction is worth keeping. Confirmation would come fromevents_statements_summary_by_digestsampled before and during a wave, and from re-measuring rows read and threads running on the first large rollout after this ships.Solution (What + How)
Restructure
canDeployinto three paths so the recount happens at most once per env per ttl.DEPLOY-<envId>before recounting instead of after. The winner recounts inside the critical section; pings that lose the lock return and retry on their next cycle rather than duplicating the scans. The winner now also runs two counts instead of three, since the old code counted before the lock and re-counted inside it.last_refreshand the expired window can never exceed one ttl.last_refreshis still extended only on a recount, never on an ordinary admission write. That is deliberate:active_countis increment-only and is never decremented when an agent finishes, so periodic expiry is the only thing that resyncs it against reality. Refreshing it on every admission would let the count inflate without bound and stall the rollout.flowchart TB subgraph before ["Before: every expired-cache ping scans"] b1["Ping arrives, cache expired"] --> b2["COUNT(*) non-first-deploy agents"] b2 --> b3["COUNT(*) deploying agents"] b3 --> b4{"At capacity?"} b4 -->|yes| b5["Return false, cache never written"] b4 -->|no| b6["GET_LOCK"] b6 -->|lock lost| b7["Return false, scans wasted"] b6 -->|lock won| b8["Third COUNT, write cache, take seat"] end subgraph after ["After: one ping per ttl scans"] a1["Ping arrives, cache expired"] --> a2["GET_LOCK"] a2 -->|lock lost| a3["Return false, no scans"] a2 -->|lock won| a4["COUNT(*) non-first-deploy agents"] a4 --> a5["COUNT(*) deploying agents"] a5 --> a6["Write refreshed cache"] a6 --> a7{"At capacity?"} a7 -->|yes| a8["Return false, staleness bounded by ttl"] a7 -->|no| a9["Take a seat, return true"] endThree behavior changes reviewers should weigh:
WARNtoDEBUG. Losing the lock is now the expected outcome for most pings rather than an anomaly, so leaving it atWARNwould flood the logs. Any alerting keyed on that line needs updating.countNonFirstDeployingAgentnow runs inside thetry, so an exception there returnsfalseinstead of propagating out ofcanDeploy. This matches howcountDeployingAgentalready behaved.Test Plan
Added seven cases to
PingHandlerTestcovering the new control flow:getLocklast_refreshactive_countlast_refreshuntouchedagent_countsrow recounts and initializes the rowfirst_deploystill bypasses the threshold entirely