Detect stalled Cloud Run work behind a healthy endpoint
In brief
Detect stalled Cloud Run work from overdue operations and their last meaningful progress.
- Allow for scheduled starts, retry backoff, and planned pauses. Lease renewals alone don't prove progress.
- Monitor the detector's own successful scans so its silence can't hide a stalled worker.
A worker endpoint can return successful health checks while accepted work stops moving. The dispatcher may have missed an operation, a worker may keep renewing its lease without making progress, or every attempt may be delayed by retries. None of them has to raise the HTTP error rate.
We’d detect this from the durable work record. Start with the completion obligation and the last meaningful progress, then use queue and request metrics to locate the failure.
For disposable, best-effort work, queue monitoring may be enough. An application that promises a result needs a record of that promise and a detector that can find it even when no message was successfully enqueued.
Define the clocks before the thresholds
Keep the initial eligibility time separate from the next retry time.
A document scheduled for tomorrow shouldn’t look stuck tonight. A document due ten minutes ago shouldn’t disappear from the overdue count because the retry scheduler pushed its next attempt into the future.
Record a completion deadline from the workload’s contract: a fixed allowance after initial eligibility, or a deadline the requester set. Don’t extend it on every retry. If the promised outcome changes, change the deadline through an authorized transition and record why.
Progress needs an equally concrete definition. For a document conversion, a completed stage or durably written output segment can advance progress_at, but a timer announcing that the process is alive can’t. Keep lease renewal and progress separate, and initialize progress time when an attempt starts. That way, a worker that never reaches its first milestone can still be detected.
An intentional pause suppresses execution-stall detection but needs a reason and a review time. The completion promise stays in force, so a paused operation can still be overdue until someone changes it.
Use a few signals that tell the cases apart
Cloud Tasks exposes queue depth, attempts, and attempt delay. Attempt delay measures the gap between a scheduled attempt and its dispatch, not the time since the user requested a result. Queue depth also can’t include a durable operation that the dispatcher never enqueued.
Use those metrics alongside these application observations:
| Observation | First condition to inspect |
|---|---|
| Ready work is aging, with no attempt recorded | Durable dispatch record and queue admission |
| Running work has no meaningful progress | Current processing stage and its expected duration |
| Running work has an expired lease | Ownership loss or failed renewal |
| Completion deadline passed | Remaining obligation, including backoff or paused work |
| Pause review time passed | Whether the suspension still has a valid reason |
A rising backlog can be healthy during a planned burst if age stays inside the completion contract, and zero completions can be healthy when no work is eligible. A steady stream of easy completions can also hide one old operation that never finishes.
Keep an age or deadline signal even when aggregate throughput looks good.
Query the obligation independently of the worker
For a small PostgreSQL-backed service, a periodic read of active operations is often enough. This example assumes a work_operation table with an operation ID, a state, and the timestamp-with-time-zone fields named below. Eligibility, retry time, and completion deadline are required, and the deadline must be at or after initial eligibility. Running rows also need progress and lease timestamps, and paused rows need a review timestamp. Enforce all of this when writing state.
Bind $1 to one database-derived observation time. PostgreSQL’s statement timestamp gives a stable instant for a statement, and a fixed timestamp makes the same query reproducible in tests.
Pick the no-progress allowance for each workload class. This query uses five minutes:
WITH active AS (
SELECT *, $1::timestamptz AS observed_at,
state = 'queued'
AND eligible_at <= $1::timestamptz
AND retry_at <= $1::timestamptz AS ready
FROM work_operation
WHERE state IN ('queued', 'running', 'paused')
)
SELECT
count(*) FILTER (WHERE ready) AS ready_count,
coalesce(max(extract(epoch FROM observed_at - eligible_at))
FILTER (WHERE ready), 0) AS oldest_ready_seconds,
count(*) FILTER (
WHERE completion_due_at < observed_at
) AS overdue_count,
count(*) FILTER (
WHERE state = 'running'
AND progress_at < observed_at - interval '5 minutes'
) AS no_progress_count,
count(*) FILTER (
WHERE state = 'running' AND lease_until < observed_at
) AS expired_lease_count,
count(*) FILTER (
WHERE state = 'paused' AND pause_review_at < observed_at
) AS pause_review_due_count
FROM active;The ready-age value is the time since initial eligibility among operations currently ready to run. It includes earlier backoff instead of restarting with each queue attempt. Overdue count ignores retry timing altogether. A healthy heartbeat can keep the lease current while the no-progress count increases.
An empty active set produces zero counts, but the maximum needs coalesce because PostgreSQL aggregates other than count return null on no input. Export those zeros after a successful scan. A failed scan must produce a detector failure, not a fabricated zero backlog.
A retryable attempt failure returns the operation to queued state. Reserve a terminal failed state for an outcome the requester can inspect, and monitor those failures separately. This query excludes terminal operations. Relabeling one without resolving its obligation would make the result wrong.
Run the scan through a read-only role with a bounded statement timeout. A full count isn’t free. Measure its query plan against representative active-state volume, and index or partition accordingly. Read authoritative state or account for replica lag. Polling faster than that state becomes visible tells you nothing new.
Make the detector’s silence visible
Publish the observations as gauge metrics with a small set of workload labels, and keep operation IDs in investigation records. Emit a scan-success signal only after reading the database and exporting the measurements. Where you can, expose failures through an independent path too.
Choose the notification delay from the time available to intervene. If a result must complete within an hour and recovery commonly needs fifteen minutes, a warning at the deadline leaves no recovery margin. An age threshold can warn earlier, while the overdue count records a missed obligation.
Cloud Monitoring alert conditions have separate settings for the alignment period, retest window, and missing-data behavior. A brief spike may not deserve an interruption. But a long aggregation window combined with a long retest window can use up the time you have to respond.
Don’t let missing measurements count as healthy work.
Use a separate absence condition for the scan-success signal. A metric-absence condition needs an initial successful measurement, so it won’t detect a subsystem that has never emitted a point. Verify the first sample during rollout, then stop the detector in a controlled test and check that its absence becomes visible.
Before enabling notifications, test cases that should stay quiet: a future schedule, no incoming work, and healthy long stages. Then test cases that should fire: a missing dispatch, fresh lease renewals without progress, backoff beyond the completion deadline, and an overdue pause review. Complete or cancel each affected operation and verify that the matching count clears. Keep lease recovery and replay as separate actions, and decide separately whether an external effect may run again.
More in this domain: Infrastructure
Browse allWhen a BigQuery service perimeter earns its operational cost
Adopt a service perimeter for a named prohibited data-transfer path, then prove that required queries still work and the prohibited transfer fails.
Give Cloud Run health probes a recovery policy
Match each Cloud Run health probe to a recovery action.
Rotating a Cloud Run credential while old revisions still exist
Keep both credentials valid while Cloud Run consumers move to a verified replacement.
Cloud Tasks vs. Pub/Sub for Cloud Run: routing, retries, and rate limits
Use Cloud Tasks to schedule or throttle a specific operation. Use Pub/Sub to deliver one event to independent consumers.
Cloud Run scale to zero: cold starts and minimum instances
Let Cloud Run scale to zero when the first useful request after idle time meets the caller's deadline.
Related patterns
Cloud Run request timeouts don't kill your code (so your architecture has to)
A Cloud Run request timeout returns a 504 while the handler may keep running.
Direct VPC egress vs. Serverless VPC Access for Cloud Run
Start with Direct VPC egress for new Cloud Run connections to a VPC.
How we decide between Cloud SQL connectors, Auth Proxy, and private IP
Choose the Cloud SQL network route and the connection helper separately. Either a language connector or the Auth Proxy can use private IP.
Safe scaling defaults for Cloud Run + Postgres
Set Cloud Run instance limits, request concurrency, and per-process pools together so the fleet fits within PostgreSQL's connection budget.