Skip to content

Single-flight the agent count refresh to prevent ping stampedes on large stages - #1967

Merged
yongwen merged 1 commit into
pinterest:masterfrom
yongwen:yongwen/single-flight-agent-count-refresh
Aug 19, 2026
Merged

yongwen merged 1 commit into
pinterest:masterfrom
yongwen:yongwen/single-flight-agent-count-refresh

Conversation

@yongwen

@yongwen yongwen commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Problem (Why)

agent_counts is a per-env cache with a ttl (agentCountCacheTtl), read at the top of PingHandler.canDeploy. While the entry is fresh, admission decisions are served from it cheaply. Once it expires, the ping recomputes it with two COUNT(*) queries over every agents row 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. getLock uses 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 when maxParallelThreshold caps the configured max_parallel_pct — therefore never updated last_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 agents rows per scan and more hosts polling.

Worth noting separately that GET_DEPLOYING_TOTAL is an expensive scan regardless: its top-level OR state = 'STOP' prevents use of agent_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_counts were 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 from events_statements_summary_by_digest sampled 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 canDeploy into three paths so the recount happens at most once per env per ttl.

  1. Fast path. A fresh count already reporting the env at capacity rejects immediately on a single primary-key lookup — no lock, no scans. This is the common case for hosts queued behind the threshold.
  2. Single flight. Acquire 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.
  3. Bounded staleness. Persist the recount even when the host is not admitted, so an env sitting at capacity still refreshes last_refresh and the expired window can never exceed one ttl.

last_refresh is still extended only on a recount, never on an ordinary admission write. That is deliberate: active_count is 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"]
    end
Loading

Three behavior changes reviewers should weigh:

  • The "failed to grab lock" log dropped from WARN to DEBUG. Losing the lock is now the expected outcome for most pings rather than an anomaly, so leaving it at WARN would flood the logs. Any alerting keyed on that line needs updating.
  • Rejecting on an expired cache now requires taking the lock, where previously it could reject without one. That is inherent to single-flight, and it is why the recount is persisted on rejection.
  • countNonFirstDeployingAgent now runs inside the try, so an exception there returns false instead of propagating out of canDeploy. This matches how countDeployingAgent already behaved.

Test Plan

Added seven cases to PingHandlerTest covering the new control flow:

  • a fresh at-capacity count rejects without calling either count query or getLock
  • losing the lock skips both counts and writes nothing
  • a stale at-capacity count rejects but still persists a refreshed last_refresh
  • a stale under-capacity count recounts exactly once, admits, and increments active_count
  • a fresh under-capacity count admits without recounting and leaves last_refresh untouched
  • a missing agent_counts row recounts and initializes the row
  • first_deploy still bypasses the threshold entirely
mvn -pl common -am -Dtest=PingHandlerTest test
# Tests run: 27, Failures: 0, Errors: 0, Skipped: 0

mvn -pl common -am test
# Tests run: 194, Failures: 0, Errors: 3, Skipped: 1
# The 3 errors are DBAgentDAOImplTest, DBDAOTest and DBEnvironDAOImplTest failing in
# setUpClass because no Docker environment was available for Testcontainers locally.
# They are unrelated to this change, but they are the suites that exercise the real
# SQL in DBAgentDAOImpl, so CI should be green on them before this is trusted.

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>
@yongwen
yongwen requested a review from a team as a code owner August 14, 2026 17:24
@github-actions github-actions Bot added the deploy-service Includes changes to deploy-service label Aug 14, 2026
@yongwen
yongwen merged commit fc7835f into pinterest:master Aug 19, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deploy-service Includes changes to deploy-service

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants